Snippets Collections
import java.util.*;

public class Dijkstra {

 
    public static void dijkstra(int[][] cost, int source) {
        int n = cost.length; 
        boolean[] visited = new boolean[n]; 
        double[] dist = new double[n]; 

        Arrays.fill(dist, Double.POSITIVE_INFINITY);
        dist[source] = 0.0; 

        for (int count = 0; count < n - 1; count++) {
           
            int u = minDistance(dist, visited);
            visited[u] = true; 

       
            for (int v = 0; v < n; v++) {
               
                if (!visited[v] && cost[u][v] != 0 && dist[u] != Double.POSITIVE_INFINITY
                        && dist[u] + cost[u][v] < dist[v]) {
                    dist[v] = dist[u] + cost[u][v];
                }
            }
        }


        printSolution(dist);
    }


    private static int minDistance(double[] dist, boolean[] visited) {
        double min = Double.POSITIVE_INFINITY;
        int minIndex = -1;

        for (int v = 0; v < dist.length; v++) {
            if (!visited[v] && dist[v] <= min) {
                min = dist[v];
                minIndex = v;
            }
        }
        return minIndex;
    }


    private static void printSolution(double[] dist) {
        System.out.println("Vertex Distance from Source");
        for (int i = 0; i < dist.length; i++) {
            System.out.println(i + " \t\t " + dist[i]);
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of vertices: ");
        int n = scanner.nextInt();

   
        int[][] cost = new int[n][n];
        System.out.println("Enter the adjacency matrix (enter 0 for no edge):");
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                cost[i][j] = scanner.nextInt();
            }
        }

        System.out.print("Enter the source vertex (0 to " + (n - 1) + "): ");
        int source = scanner.nextInt();

  
        dijkstra(cost, source);

        scanner.close();
    }
}

Algorithm ShortestPaths(v, cost, dist, n)
// dist[j], 1 ≤ j ≤ n, is set to the length of the shortest path 
// from vertex v to vertex j in a digraph G with n vertices. 
// dist[v] is set to zero. G is represented by its 
// cost adjacency matrix cost[1 : n, 1 : n].

for i := 1 to n do {
    // Initialize S and distances.
    S[i] := false;
    dist[i] := cost[v, i];
}
S[v] := true; dist[v] := 0.0; // Put v in S.

for num := 1 to n - 1 do {
    // Determine n - 1 shortest paths from v.
    Choose u from among those vertices not in S such that dist[u] is minimum;
    S[u] := true; // Put u in S.

    for (each w adjacent to u with S[w] = false) do {
        // Update distances.
        if (dist[w] > dist[u] + cost[u, w]) then
            dist[w] := dist[u] + cost[u, w];
    }
}


import java.util.Scanner;

class PrimsAlgorithm {
    private static int V;

    int minKey(int key[], boolean mstSet[]) {
        int min = Integer.MAX_VALUE, minIndex = -1;
        for (int v = 0; v < V; v++) {
            if (!mstSet[v] && key[v] < min) {
                min = key[v];
                minIndex = v;
            }
        }
        return minIndex;
    }

    void printMST(int parent[], int graph[][]) {
        int totalCost = 0;
        System.out.println("Edge \tWeight");
        for (int i = 1; i < V; i++) {
            System.out.println(parent[i] + " - " + i + "\t" + graph[i][parent[i]]);
            totalCost += graph[i][parent[i]];
        }
        System.out.println("Total cost of the MST: " + totalCost);
    }

    void primMST(int graph[][]) {
        int parent[] = new int[V];
        int key[] = new int[V];
        boolean mstSet[] = new boolean[V];

        for (int i = 0; i < V; i++) {
            key[i] = Integer.MAX_VALUE;
            mstSet[i] = false;
        }

        key[0] = 0;
        parent[0] = -1;

        for (int count = 0; count < V - 1; count++) {
            int u = minKey(key, mstSet);
            mstSet[u] = true;

            for (int v = 0; v < V; v++) {
                if (graph[u][v] != 0 && !mstSet[v] && graph[u][v] < key[v]) {
                    parent[v] = u;
                    key[v] = graph[u][v];
                }
            }
        }

        printMST(parent, graph);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of vertices: ");
        V = scanner.nextInt();

        int[][] graph = new int[V][V];

        System.out.println("Enter the adjacency matrix (enter 0 if there is no edge between two vertices):");
        for (int i = 0; i < V; i++) {
            for (int j = 0; j < V; j++) {
                graph[i][j] = scanner.nextInt();
            }
        }

        PrimsAlgorithm t = new PrimsAlgorithm();
        t.primMST(graph);

        scanner.close();
    }
}




Algorithm Prim(E, cost, n, t)
// E is the set of edges in G. cost[1 : n, 1 : n] is the cost
// adjacency matrix of an n vertex graph such that cost[i, j] is
// either a positive real number or ∞ if no edge (i, j) exists.
// A minimum spanning tree is computed and stored as a set of
// edges in the array t[1 : n − 1, 1 : 2]. (t[i, 1], t[i, 2]) is an edge in
// the minimum-cost spanning tree. The final cost is returned.

css
Copy code
Let (k, l) be an edge of minimum cost in E;  
mincost := cost[k, l];  
t[1, 1] := k; t[1, 2] := l;  
for i := 1 to n do  // Initialize near.  
{  
    if (cost[i, l] < cost[i, k]) then near[i] := l;  
    else near[i] := k;  
}  
near[k] := near[l] := 0;  
for i := 2 to n − 1 do  
{  
    // Find n − 2 additional edges for t.  
    Let j be an index such that near[j] ≠ 0 and  
    cost[j, near[j]] is minimum;  
    t[i, 1] := j; t[i, 2] := near[j];  
    mincost := mincost + cost[j, near[j]];  
    near[j] := 0;  
    for k := 1 to n do  // Update near[ ].  
    {  
        if ((near[k] ≠ 0) and (cost[k, near[k]] > cost[k, j]))  
            then near[k] := j;  
    }  
}  
return mincost;
import java.util.*;

public class Graph {
    private int vertices;
    private LinkedList<Integer>[] adjList;
    private int time;

    public Graph(int v) {
        vertices = v;
        adjList = new LinkedList[v];
        for (int i = 0; i < v; i++) {
            adjList[i] = new LinkedList<>();
        }
        time = 0;
    }

    public void addEdge(int v, int w) {
        adjList[v].add(w);
        adjList[w].add(v);
    }

    public void findArticulationPoints() {
        boolean[] visited = new boolean[vertices];
        int[] dfn = new int[vertices];
        int[] low = new int[vertices];
        int[] parent = new int[vertices];
        Arrays.fill(parent, -1);

        for (int i = 0; i < vertices; i++) {
            if (!visited[i]) {
                DFSArt(i, visited, dfn, low, parent);
            }
        }
    }

    private void DFSArt(int u, boolean[] visited, int[] dfn, int[] low, int[] parent) {
        visited[u] = true;
        dfn[u] = low[u] = ++time;
        int childCount = 0;
        boolean isArticulation = false;

        for (int v : adjList[u]) {
            if (!visited[v]) {
                childCount++;
                parent[v] = u;
                DFSArt(v, visited, dfn, low, parent);

                low[u] = Math.min(low[u], low[v]);

                if (parent[u] != -1 && low[v] >= dfn[u]) {
                    isArticulation = true;
                }

                if (parent[u] == -1 && childCount > 1) {
                    isArticulation = true;
                }
            } else if (v != parent[u]) {
                low[u] = Math.min(low[u], dfn[v]);
            }
        }

        if (isArticulation) {
            System.out.println("Articulation Point: " + u);
        }
    }

    public static Graph createGraphFromAdjMatrix(int[][] adjMatrix) {
        int n = adjMatrix.length;
        Graph g = new Graph(n);
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (adjMatrix[i][j] == 1) {
                    g.addEdge(i, j);
                }
            }
        }
        return g;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of vertices: ");
        int v = scanner.nextInt();

        System.out.println("Enter the adjacency matrix:");
        int[][] adjMatrix = new int[v][v];
        for (int i = 0; i < v; i++) {
            for (int j = 0; j < v; j++) {
                adjMatrix[i][j] = scanner.nextInt();
            }
        }

        Graph g = Graph.createGraphFromAdjMatrix(adjMatrix);

        System.out.println("Articulation Points:");
        g.findArticulationPoints();
    }
}





AlgorithmArt(u, v)
// u: Start vertex for Depth First Search (DFS)
// v: Parent of u in the DFS tree (if any)
// dfn: Global array initialized to 0, storing discovery times of vertices
// L: Global array to store the lowest discovery time reachable from each vertex
// num: Global variable initialized to 1, represents the discovery order
// n: Number of vertices in the graph

{
    dfn[u] := num;           // Assign discovery time for u
    L[u] := num;             // Initialize lowest discovery time for u
    num := num + 1;          // Increment discovery counter

    for each vertex w adjacent to u do
    {
        if (dfn[w] = 0) then  // If w is unvisited
        {
            Art(w, u);        // Recursively visit w
            L[u] := min(L[u], L[w]);  // Update the lowest discovery time for u
        }
        elseif (w ≠ v) then   // If w is not the parent of u
        {
            L[u] := min(L[u], dfn[w]); // Update the lowest discovery time
        }
    }
}
 AlgorithmBiComp(u, v)
// u: Start vertex for Depth First Search (DFS)
// v: Parent of u in the DFS tree (if any)
// dfn: Global array initialized to 0, storing discovery times of vertices
// L: Global array to store the lowest discovery time reachable from each vertex
// num: Global variable initialized to 1, represents the discovery order
// s: Stack to store edges
// n: Number of vertices in the graph

{
    dfn[u] := num;           // Assign discovery time for u
    L[u] := num;             // Initialize lowest discovery time for u
    num := num + 1;          // Increment discovery counter

    for each vertex w adjacent to u do
    {
        // Push edge (u, w) onto the stack if it exists and w is not the parent
        if ((w ≠ v) and (dfn[w] < dfn[u])) then
            Add edge (u, w) to the top of the stack s;

        if (dfn[w] = 0) then  // If w is unvisited
        {
            BiComp(w, u);     // Recursively apply BiComp on w

            if (L[w] > dfn[u]) then  // Found a new biconnected component
            {
                write("New biconnected component:");
                repeat
                {
                    Delete an edge from the top of stack s;
                    Let this edge be (x, y);
                    write(x, y);   // Output the edges in the component
                } until (((x, y) = (u, w)) or ((x, y) = (w, u))); 
            }

            L[u] := min(L[u], L[w]);  // Update the lowest discovery time for u
        }
        elseif (w ≠ v) then
        {
            L[u] := min(L[u], dfn[w]);  // Update the lowest discovery time if w is already visited
        }
    }
}
import java.util.Scanner;

public class OBST {
    private double[][] w;
    private double[][] c;
    private int[][] r;

    public OBST(int n, double[] p, double[] q) {
        w = new double[n + 1][n + 1];
        c = new double[n + 1][n + 1];
        r = new int[n + 1][n + 1];

        for (int i = 0; i <= n; i++) {
            w[i][i] = q[i];
            r[i][i] = 0;
            c[i][i] = 0.0;

            if (i < n) {
                w[i][i + 1] = q[i] + q[i + 1] + p[i + 1];
                r[i][i + 1] = i + 1;
                c[i][i + 1] = w[i][i + 1];
            }
        }

        for (int m = 2; m <= n; m++) {
            for (int i = 0; i <= n - m; i++) {
                int j = i + m;
                w[i][j] = w[i][j - 1] + p[j] + q[j];
                int k = findOptimalRoot(i, j);
                c[i][j] = w[i][j] + c[i][k - 1] + c[k][j];
                r[i][j] = k;
            }
        }
    }

    private int findOptimalRoot(int i, int j) {
        double minCost = Double.POSITIVE_INFINITY;
        int optimalRoot = i;

        for (int m = r[i][j - 1]; m <= r[i + 1][j]; m++) {
            double cost = c[i][m - 1] + c[m][j];
            if (cost < minCost) {
                minCost = cost;
                optimalRoot = m;
            }
        }

        return optimalRoot;
    }

    public void printResult() {
        System.out.println("Cost of Optimal BST: " + c[0][w.length - 1]);
        System.out.println("Root of Optimal BST: " + r[0][w.length - 1]);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of keys: ");
        int n = scanner.nextInt();

        double[] p = new double[n + 1];
        double[] q = new double[n + 1];

        System.out.println("Enter the probabilities of keys (p[1] to p[" + n + "]):");
        for (int i = 1; i <= n; i++) {
            System.out.print("p[" + i + "]: ");
            p[i] = scanner.nextDouble();
        }

        System.out.println("Enter the probabilities of dummy keys (q[0] to q[" + n + "]):");
        for (int i = 0; i <= n; i++) {
            System.out.print("q[" + i + "]: ");
            q[i] = scanner.nextDouble();
        }

        OBST obst = new OBST(n, p, q);
        obst.printResult();

        scanner.close();
    }
}





ALGORITHM:
// Algorithm OBST(p, q, n)
// Given n distinct identifiers a1 < a2 < ... < an and probabilities
// p[i], 1 ≤ i ≤ n, and q[i], 0 ≤ i ≤ n, this algorithm computes
// the cost c[i, j] of optimal binary search trees tij for identifiers
// a[i+1],...,a[j]. It also computes r[i, j], the root of tij.
// w[i, j] is the weight of tij.

for i := 0 to n - 1 do
{
    // Initialize.
    w[i, i] := q[i]; r[i, i] := 0; c[i, i] := 0.0;
    // Optimal trees with one node
    w[i, i + 1] := q[i] + q[i + 1] + p[i + 1];
    r[i, i + 1] := i + 1;
    c[i, i + 1] := q[i] + q[i + 1] + p[i + 1];
}
w[n, n] := q[n]; r[n, n] := 0; c[n, n] := 0.0;
for m := 2 to n do // Find optimal trees with m nodes.
    for i := 0 to n - m do
    {
        j := i + m;
        w[i, j] := w[i, j - 1] + p[j] + q[j];
        // Solve 5.12 using Knuth's result.
        k := Find(c, r, i, j);
        // A value of l in the range r[i, j - 1] ≤ l ≤ r[i + 1, j] that minimizes c[i, l - 1] + c[l, j];
        c[i, j] := w[i, j] + c[i, k - 1] + c[k, j];
        r[i, j] := k;
    }
write (c[0, n], w[0, n], r[0, n]);

// Algorithm Find(c, r, i, j)
min := ∞;
for m := r[i, j - 1] to r[i + 1, j] do
    if (c[i, m - 1] + c[m, j]) < min then
    {
        min := c[i, m - 1] + c[m, j];
        l := m;
    }
return l;
import java.util.*;

class Job {
    int id, deadline, profit;

    Job(int id, int deadline, int profit) {
        this.id = id;
        this.deadline = deadline;
        this.profit = profit;
    }
}

public class JobScheduling {

    public static int scheduleJobs(Job[] jobs, int n) {
        Arrays.sort(jobs, (a, b) -> b.profit - a.profit);

        boolean[] slots = new boolean[n];
        int maxProfit = 0;

        for (Job job : jobs) {
            for (int j = Math.min(n, job.deadline) - 1; j >= 0; j--) {
                if (!slots[j]) {
                    slots[j] = true;
                    maxProfit += job.profit;
                    System.out.print("Job " + job.id + " ");
                    break;
                }
            }
        }

        System.out.println("\nMax Profit: " + maxProfit);
        return maxProfit;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter number of jobs: ");
        int n = sc.nextInt();
        Job[] jobs = new Job[n];

        for (int i = 0; i < n; i++) {
            System.out.print("Enter job ID, deadline, and profit: ");
            jobs[i] = new Job(sc.nextInt(), sc.nextInt(), sc.nextInt());
        }

        scheduleJobs(jobs, n);
        sc.close();
    }
}




 GreedyJob(d, J, n)
{
    // J is the set of jobs that can be completed by their deadlines.
    J := {1};  // Start with the first job

    for i := 2 to n do
    {
        // Check if adding job i to the set J allows all jobs in J to be completed by their deadlines.
        if (all jobs in J ∪ {i} can be completed by their deadlines) then
        {
            J := J ∪ {i};  // Add job i to the set
        }
    }
}



 Algorithm JS(d, p, n)
// d[i] > 1, 1 ≤ i ≤ n are the deadlines, n > 1.
// The jobs are ordered such that p[1] > p[2] > ... > p[n].
// J[i] is the ith job in the optimal solution, 1 ≤ i ≤ k.
// At termination, d[J[i]] < d[J[i+1]], 1 ≤ i < k.
{
    rf[0] := J[0] := 0;  // Initialize.
    J[1] := 1;           // Include job 1 in the solution.
    k := 1;

    for i := 2 to n do
    {
        // Consider jobs in non-increasing order of profit p[i].
        // Find position for job i and check feasibility of insertion.
        r := k;

        while ((d[J[r]] > d[i]) and (d[J[r]] ≠ r)) do
        {
            r := r - 1;
        }

        if ((d[J[r]] < d[i]) and (d[i] > r)) then
        {
            // Insert job i into J[].
            for q := k to (r + 1) step -1 do
            {
                J[q + 1] := J[q];
            }
            J[r + 1] := i;
            k := k + 1;
        }
    }
    return k;
}
from sklearn.tree import DecisionTreeClassifier
from sklearn.preprocessing import LabelEncoder

df = pd.read_csv('/content/iris.csv')
df.info()
encoder = LabelEncoder()
df["variety"] = encoder.fit_transform(df["variety"])
df.info()
X = df.iloc[:,:-1] #df.drop(columns=["speices"])
y = df.iloc[:,-1] #df["species"]
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=42)
dtc = DecisionTreeClassifier()
dtc.fit(X_train,y_train)
y_pred = dtc.predict(X_test)
print(y_test,y_pred)


from sklearn.metrics import accuracy_score,classification_report,confusion_matrix

accuracy = accuracy_score(y_pred,y_test)
print(accuracy)
print(classification_report(y_pred,y_test))
print(confusion_matrix(y_pred,y_test))


# prompt: Visualize insights of Above decision tree classification on iris dataset
from sklearn import tree
import matplotlib.pyplot as plt

plt.figure(figsize=(15,10))
tree.plot_tree(dtc,filled=True,feature_names=X.columns,class_names=['0','1','2'])
plt.show()

1. Distance-based Pricing
A food delivery service charges a base fee of $2, plus $1.50 per mile for delivery. If the customer is 5 miles away, the fare will be:

Base Fare = $2
Distance Fare = $1.50 × 5 = $7.50
Total Fare = $2 + $7.50 = $9.50

2. Time-based Pricing
A grocery delivery service charges based on time taken. There’s a base fee of $3, plus $0.10 per minute for the duration of the delivery. If a delivery takes 45 minutes:

Base Fare = $3
Time Fare = $0.10 × 45 = $4.50
Total Fare = $3 + $4.50 = $7.50

3. Weight/Size-based Pricing
A furniture delivery service charges a base fee of $10, plus $2 per 10 lbs for items over 50 lbs. If a delivered item weighs 70 lbs:

Base Fare = $10
Weight Fare = $2 × 2 = $4
Total Fare = $10 + $4 = $14

4. Dynamic/Surge Pricing
A ride-sharing delivery charges a base fare of $5, with $2 per mile, but due to high demand, a surge multiplier of 1.5x is applied. For a 4-mile delivery:

Base Fare = $5
Distance Fare = $2 × 4 = $8
Surge Multiplier = 1.5
Total Fare = ($5 + $8) × 1.5 = $19.50

5. Zonal Pricing
A local courier service charges $10 for deliveries within Zone A and $15 for Zone B. If a delivery is in Zone B:

Zone Fare = $15
Total Fare = $15

6. Hybrid Pricing (Distance + Time)
A parcel delivery service charges a base fare of $3, $1 per mile, and $0.05 per minute. If a 10-mile delivery takes 30 minutes:

Base Fare = $3
Distance Fare = $1 × 10 = $10
Time Fare = $0.05 × 30 = $1.50
Total Fare = $3 + $10 + $1.50 = $14.50

7. Fuel Surcharge Additions
A delivery service charges $2 per mile, but also adds a $0.10 per mile fuel surcharge when fuel prices rise. For a 12-mile delivery:

Base Fare = $2 × 12 = $24
Fuel Surcharge = $0.10 × 12 = $1.20
Total Fare = $24 + $1.20 = $25.20

8. Crowdsourced/Bid-based Pricing
In a freelance courier platform, drivers bid for deliveries. A customer needs to deliver a package 5 miles away. Three drivers submit bids:

Driver 1: $15
Driver 2: $12
Driver 3: $18
The customer selects Driver 2’s bid of $12.
import java.util.Scanner;

public class Quick {
    
    public static int partition(int[] arr, int low, int high) {
        int pivot = arr[low];
        int i = low;
        int j = high;

        while (i < j) {
            while (i <= high && arr[i] <= pivot) {
                i++;
            }
            while (arr[j] > pivot) {
                j--;
            }
            if (i < j) {
                interchange(arr, i, j);
            }
        }

     
        interchange(arr, low, j);
        return j; 
    }


    public static void interchange(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }


    public static void quickSort(int[] arr, int low, int high) {
        if (low < high) {
            int j = partition(arr, low, high);
            quickSort(arr, low, j - 1);
            quickSort(arr, j + 1, high);
        }
    }

   
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

    
        System.out.print("Enter the size of the array: ");
        int n = scanner.nextInt();

        
        int[] arr = new int[n];
        System.out.println("Enter " + n + " elements:");
        for (int i = 0; i < n; i++) {
            arr[i] = scanner.nextInt();
        }

       
        System.out.println("Original array:");
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();

        
        quickSort(arr, 0, arr.length - 1);

       
        System.out.println("Sorted array:");
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}




Algorithm Partition(a, m, p)
Within a[m], a[m+1],...,a[p-1] the elements are rearranged in such a manner that if initially t = a[m],
then after completion a[q] = t for some q between m and p-1, a[k] < t for m ≤ k < q, and a[k] ≥ t for q < k < p. q is returned. Set a[p] = ∞.
v := a[m]; i := m; j := p;
repeat
    repeat
        i := i + 1;
    until (a[i] ≥ v);
    repeat
        j := j - 1;
    until (a[j] < v);
    if (i < j) then
        Interchange(a, i, j);
} until (i ≥ j);

a[m] := a[j]; a[j] := v;
return j;

Algorithm Interchange(a, i, j)
// Exchange a[i] with a[j].
temp := a[i];
a[i] := a[j];
a[j] := temp;


Algorithm: QuickSort (p, q)

// Sorts the elements in the array a[p : q] in non-decreasing order.

if (p < q) then // If there is more than one element
{
    // Divide the array into two subproblems.
    j := Partition(a, p, q + 1);
    // 'j' is the position of the partitioning element.

    QuickSort(p, j - 1); // Sort the left subarray.
    QuickSort(j + 1, q); // Sort the right subarray.


OUTPUT:

Enter the size of the array: 5
Enter 5 elements:
9
3
7
1
5

Original array:
9 3 7 1 5 
Sorted array:
1 3 5 7 9
import java.util.Scanner;

public class Merge {
    public void merge(int arr[], int l, int m, int r) {
        int[] left = new int[m - l + 1];
        int[] right = new int[r - m];
        
        // Copy data into left[] and right[]
        System.arraycopy(arr, l, left, 0, left.length);
        System.arraycopy(arr, m + 1, right, 0, right.length);

        int i = 0, j = 0, k = l;
        
        // Merge the left and right arrays back into arr[]
        while (i < left.length && j < right.length) {
            if (left[i] <= right[j]) {
                arr[k++] = left[i++];
            } else {
                arr[k++] = right[j++];
            }
        }

        // Copy remaining elements of left[], if any
        while (i < left.length) {
            arr[k++] = left[i++];
        }

        // Copy remaining elements of right[], if any
        while (j < right.length) {
            arr[k++] = right[j++];
        }
    }

    public void sort(int arr[], int l, int r) {
        if (l < r) {
            int mid = (l + r) / 2;
            sort(arr, l, mid);
            sort(arr, mid + 1, r);
            merge(arr, l, mid, r);
        }
    }

    public static void display(int[] arr) {
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Prompt user for array size
        System.out.print("Enter the size of the array: ");
        int n = scanner.nextInt();

        // Create array and input elements
        int[] arr = new int[n];
        System.out.println("Enter " + n + " elements:");
        for (int i = 0; i < n; i++) {
            arr[i] = scanner.nextInt();
        }

        System.out.println("Original array:");
        display(arr);
        
        // Perform merge sort
        new Merge().sort(arr, 0, arr.length - 1);
        
        System.out.println("Sorted array:");
        display(arr);

        scanner.close();
    }
}


Algorithm:



Algorithm MergeSort(low, high)
    // a[low : high] is a global array to be sorted.
    // Small(P) is true if there is only one element to sort.
    // In this case, the list is already sorted.

    if (low < high) then  
        // Step 1: Divide the problem into subproblems
    {
        mid := ⌊(low + high) / 2⌋;  // Find where to split the set
        
        // Step 2: Solve the subproblems
        MergeSort(low, mid);
        MergeSort(mid + 1, high);

        // Step 3: Combine the solutions
        Merge(low, mid, high);
    }
}



Algorithm Merge (low, mid, high)
k := low; i := low; j := mid + 1;  
while ((i ≤ mid) and (j ≤ high)) do  
    if (a[i] ≤ a[j]) then  
    {  
        b[k] := a[i]; i := i + 1;  
    }  
    else  
    {  
        b[k] := a[j]; j := j + 1;  
    }  
    k := k + 1;  
end  

if (i > mid) then  
    for k := j to high do  
    {  
        b[k] := a[k]; i := i + 1;  
    }  
else  
    for k := i to mid do  
    {  
        b[k] := a[k]; i := i + 1;  
    }  

for k := low to high do a[k] := b[k];  



OUTPUT:
Enter the size of the array: 5
Enter 5 elements:
10
3
6
2
9
Original array:
10 3 6 2 9 
Sorted array:
2 3 6 9 10 
from sklearn.datasets import load_iris
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_rand_score, silhouette_score

# Step 1: Load the Iris dataset
iris = load_iris()
df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
print("DataFrame Head:\n", df.head())
print("DataFrame Info:\n", df.info())

# Step 2: Scale the features
scaler = StandardScaler()
X_scaled = scaler.fit_transform(df)

# Step 3: Apply K-Means Clustering
kmeans = KMeans(n_clusters=3, random_state=42)
kmeans.fit(X_scaled)

# Get cluster labels
cluster_labels = kmeans.labels_
df['Cluster'] = cluster_labels

# Cluster centers
cluster_centers = kmeans.cluster_centers_
print("Cluster Centers:\n", cluster_centers)

# Step 4: Evaluate the Clustering Performance
true_labels = iris.target

# Adjusted Rand Index (ARI)
ari = adjusted_rand_score(true_labels, cluster_labels)
print(f"Adjusted Rand Index (ARI): {ari}")

# Silhouette Score
silhouette_avg = silhouette_score(X_scaled, cluster_labels)
print(f"Silhouette Score: {silhouette_avg}")
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, accuracy_score
# Assuming the dataset is in CSV format, replace 'data.csv' with your actual file path.
data = pd.read_csv('Soybean.csv')
# Display the first few rows of the dataset to understand its structure
print(data.head())
# Separate features and target variable
X = data.drop('Class', axis=1)  # Features
y = data['Class']                # Target variable
# Split the dataset into training and testing sets (80% train, 20% test)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Create a Random Forest classifier
rf_classifier = RandomForestClassifier(n_estimators=100, random_state=42)
# Fit the model on the training data
rf_classifier.fit(X_train, y_train)
# Predict the labels for the test set
y_pred = rf_classifier.predict(X_test)
# Print accuracy and classification report
accuracy = accuracy_score(y_test, y_pred)
print(f'Accuracy: {accuracy:.2f}')
print(classification_report(y_test, y_pred))


# Display feature importances
importances = rf_classifier.feature_importances_
feature_importance = pd.DataFrame({'Feature': X.columns, 'Importance': importances})
print(feature_importance.sort_values(by='Importance', ascending=False))
MainActivity:
package com.cscorner.myapplication5

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
//Bundle is a class in android studio used to transfer data from one UI component activity to another UI component activity to another UI component activity.
import android.widget.Toast
class MainActivity : AppCompatActivity()
{
    override fun onCreate(savedInstanceState: Bundle?)
    {
//Bundle defines 2 methods onFreeze() and onCreate() onFreeze() assigns value to UI component in design phase and onCreate() takes parameter of component during runtime
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
//R is a resource set in activity_main.xml and used in kt file with resource id
    }
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:minHeight="48dp"
        android:textAllCaps="true"
        android:textColor="#289428"
        android:text="MAD LAB"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5" />
</androidx.constraintlayout.widget.ConstraintLayout>
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report


#step 1 load real time dataset
data=load_iris()
x= data.data#features
y=data.target#labelsA

#step 2 split the dataset into training amd testing sets
X_train,X_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=42)

#step 3 standardize the features
scaler=StandardScaler()
X_train=scaler.fit_transform(X_train)
X_test=scaler.transform(X_test)

#STEP 4 Initialize the KNN classifier and fit to the training data
knn= KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train,y_train)

#step 5 make predictions on the test data
y_pred=knn.predict(X_test)

#step  6 evaluate the model accuracy,confusion matrix, classification report
accuracy=accuracy_score(y_test,y_pred)
conf_matrix=confusion_matrix(y_test,y_pred)
class_report=classification_report(y_test,y_pred)
print(f'Accuracy: {accuracy}')
print('Confusion Matrix:')
print(conf_matrix)
print('Classification Report:')
print(class_report)
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report


#step 1 load real time dataset
data=load_iris()
x= data.data#features
y=data.target#labelsA

#step 2 split the dataset into training amd testing sets
X_train,X_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=42)

#step 3 standardize the features
scaler=StandardScaler()
X_train=scaler.fit_transform(X_train)
X_test=scaler.transform(X_test)

#STEP 4 Initialize the KNN classifier and fit to the training data
knn= KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train,y_train)

#step 5 make predictions on the test data
y_pred=knn.predict(X_test)

#step  6 evaluate the model accuracy,confusion matrix, classification report
accuracy=accuracy_score(y_test,y_pred)
conf_matrix=confusion_matrix(y_test,y_pred)
class_report=classification_report(y_test,y_pred)
print(f'Accuracy: {accuracy}')
print('Confusion Matrix:')
print(conf_matrix)
print('Classification Report:')
print(class_report)
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report

iris = datasets.load_iris()
x = iris.data
y = iris.target

X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=42)

#Initialize the Naive Bayes model
nb_model = GaussianNB()

# Fit the model to the training data
nb_model.fit(X_train, y_train)

#Predict on the test data
y_pred = nb_model.predict(X_test)


#Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
confusion = confusion_matrix(y_test, y_pred)
classification_rep = classification_report(y_test, y_pred)

print(f"Accuracy: {accuracy}")
print("Confusion Matrix:")
print(confusion)
print("Classification Report:")
print(classification_rep)
import numpy as np
import pandas as pd
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report



data = datasets.load_iris()

x = data.data
y = data.target

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)

scaler = StandardScaler()
x_train = scaler.fit_transform(x_train)
x_test = scaler.transform(x_test)

knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(x_train, y_train)

y_pred = knn.predict(x_test)

accuracy = accuracy_score(y_test, y_pred)
confusion = confusion_matrix(y_test, y_pred)
classification_rep = classification_report(y_test, y_pred)

print(f"Accuracy: {accuracy * 100 : .2f}%")
print("Confusion Matrix:\n", confusion)
print("Classification Report:\n", classification_rep)

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

training_set = pd.read_csv('/content/Facebook_Ads_2.csv',encoding='ISO-8859-1')

training_set.head()

click = training_set[training_set['Clicked'] == 1 ]
no_click = training_set[training_set['Clicked'] == 0]


click.head()

# no_click.head()

print("Total = ",len(training_set))
print("Click = ",len(click))
print("No click = ",len(no_click))

print("% who not clicked ", 1.*len(no_click)/len(training_set)*100.0,"%")
print("% who clicked ", 1.*len(click)/len(training_set)*100.0,"%")

training_set.Clicked.value_counts().plot(kind='bar')
training_set.Clicked.value_counts().plot(kind='pie')
sns.scatterplot(x='Time Spent on Site', y='Salary', hue='Clicked', data=training_set)
plt.figure(figsize=(5,5))
sns.boxplot(x='Clicked', y='Salary',data= training_set)

training_set.drop(['Names','emails','Country'],axis=1,inplace=True)

training_set.head()

x = training_set.drop('Clicked',axis=1).values
y = training_set['Clicked'].values

from sklearn.preprocessing import StandardScaler

sc = StandardScaler()
x = sc.fit_transform(x)

from sklearn.model_selection import train_test_split

x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=0)

from sklearn.linear_model import LogisticRegression

classifier = LogisticRegression(random_state = 0)
classifier.fit(x_train, y_train)

y_predict_train = classifier.predict(x_train)
y_predict_train
y_predict_test = classifier.predict(x_test)
y_predict_test

from sklearn.metrics import classification_report, confusion_matrix

cm = confusion_matrix(y_test, y_predict_test)
sns.heatmap(cm, annot=True, fmt='d')

from sklearn.metrics import classification_report

print(classification_report(y_test, y_predict_test))
MainActivity:
package com.cscorner.myapplication5

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        val button:Button=findViewById(R.id.button)
        val et:EditText=findViewById(R.id.editTextText)
        val tv:TextView=findViewById(R.id.textView)

        button.setOnClickListener{
            tv.text=et.text.toString()
            Toast.makeText(this,"Text Copied",Toast.LENGTH_LONG).show()
        }
    }
}
activivty_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5" />

    <EditText
        android:id="@+id/editTextText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="text"
        android:minHeight="48dp"
        android:text="Name"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.279" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.728" />
</androidx.constraintlayout.widget.ConstraintLayout>
Main_Activity .kt:
package com.cscorner.myapplication5

import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        val button:Button=findViewById(R.id.button)
        button.setOnClickListener{
            Toast.makeText(this,"Clicked",Toast.LENGTH_LONG).show()
        }

    }
}
activivty_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5" />
</androidx.constraintlayout.widget.ConstraintLayout>
import java.util.*;

public class PrimsAlgorithm {

    // A utility method to print the resulting MST
    public static void printMST(int[] parent, int[][] graph, int V) {
        System.out.println("Edge \tWeight");
        for (int i = 1; i < V; i++) {
            System.out.println(parent[i] + " - " + i + "\t" + graph[i][parent[i]]);
        }
    }

    // A utility method to find the vertex with the minimum key value
    public static int minKey(int[] key, boolean[] mstSet, int V) {
        int min = Integer.MAX_VALUE, minIndex = -1;

        for (int v = 0; v < V; v++) {
            if (!mstSet[v] && key[v] < min) {
                min = key[v];
                minIndex = v;
            }
        }

        return minIndex;
    }

    // Function to implement Prim's algorithm
    public static void primMST(int[][] graph, int V) {
        // Array to store the MST
        int[] parent = new int[V];
        // Key values used to pick the minimum weight edge
        int[] key = new int[V];
        // To track vertices included in MST
        boolean[] mstSet = new boolean[V];

        // Initialize all keys as infinity and mstSet[] as false
        Arrays.fill(key, Integer.MAX_VALUE);
        Arrays.fill(mstSet, false);
        key[0] = 0; // Start with the first vertex
        parent[0] = -1; // The first node is the root of the MST

        // Run Prim's algorithm
        for (int count = 0; count < V - 1; count++) {
            // Pick the minimum key vertex from the set of vertices not yet included in MST
            int u = minKey(key, mstSet, V);

            // Include the picked vertex in the MST set
            mstSet[u] = true;

            // Update key value and parent index of the adjacent vertices of the picked vertex
            for (int v = 0; v < V; v++) {
                // graph[u][v] is non-zero only for adjacent vertices of u
                // mstSet[v] is false for vertices not yet included in MST
                // Update the key and parent if the weight of edge u-v is less than the current key value of v
                if (graph[u][v] != 0 && !mstSet[v] && graph[u][v] < key[v]) {
                    key[v] = graph[u][v];
                    parent[v] = u;
                }
            }
        }

        // Print the constructed MST
        printMST(parent, graph, V);
    }

    public static void main(String[] args) {
        // Input: number of vertices (V) and the graph as an adjacency matrix
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of vertices: ");
        int V = scanner.nextInt();

        int[][] graph = new int[V][V];
        System.out.println("Enter the adjacency matrix (use 0 for no edge):");

        for (int i = 0; i < V; i++) {
            for (int j = 0; j < V; j++) {
                graph[i][j] = scanner.nextInt();
            }
        }

        // Run Prim's algorithm to find the Minimum Spanning Tree
        primMST(graph, V);

        scanner.close();
    }
}

i/p

Enter the number of vertices: 5
Enter the adjacency matrix (use 0 for no edge):
0 2 0 6 0
2 0 3 8 5
0 3 0 0 7
6 8 0 9 0
0 5 7 0 0

o/p

Edge    Weight
0 - 1    2
1 - 2    3
0 - 3    6
1 - 4    5

//Line Plot
import matplotlib.pyplot as plt

x = [1,2,3,4,5]
y = [10, 20, 30, 40, 50]

plt.plot(x,y)
plt.title("Line Plot")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
/Bar Graph
plt.bar(x,y)
plt.title("Bar Graph")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
#Histogram
import numpy as np
data = np.random.randn(1000)

plt.hist(data, bins = 30)
plt.show()
#Box Plot
import seaborn as sns
import matplotlib.pyplot as plt

# Example data
data = sns.load_dataset('tips')

# Box plot
sns.boxplot(x='day', y='total_bill', data=data)
plt.title('Box Plot')
plt.show()
#Scatter Plot

import matplotlib.pyplot as plt

# Example data
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]

# Scatter plot
plt.scatter(x, y, color='red')
plt.title('Scatter Plot')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
#Pie Chart

import matplotlib.pyplot as plt

# Example data
labels = ['Apple', 'Banana', 'Cherry', 'Date']
sizes = [10, 20, 30, 40]

# Pie chart
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
plt.title('Pie Chart')
plt.show()
#Heatmap

import seaborn as sns
import matplotlib.pyplot as plt

# Example data
data = np.random.rand(10, 12)

# Heatmap
sns.heatmap(data, cmap='coolwarm', annot=True)
plt.title('Heatmap')
plt.show()
#Pair plot
import seaborn as sns
import matplotlib.pyplot as plt

# Example data
data = sns.load_dataset('iris')

# Pair plot
sns.pairplot(data, hue='species')
plt.title('Pair Plot')
plt.show()
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of vertices:");
        int v = sc.nextInt();
        int adj[][] = new int[v + 1][v + 1];

        System.out.println("Enter the adjacency matrix:");
        for (int i = 1; i <= v; i++) {
            for (int j = 1; j <= v; j++) {
                adj[i][j] = sc.nextInt();
            }
        }

        System.out.println("Articulation points and the vertices they disconnect:");
        for (int i = 1; i <= v; i++) {
            boolean[] visited = new boolean[v + 1];
            int components = 0;

            List<List<Integer>> disconnectedGroups = new ArrayList<>();
            for (int j = 1; j <= v; j++) {
                if (j != i && !visited[j]) {
                    List<Integer> group = new ArrayList<>();
                    dfs(j, visited, adj, v, i, group);
                    disconnectedGroups.add(group);
                    components++;
                }
            }

            if (components > 1) {
                System.out.println("Vertex " + i + " is an articulation point.");
                System.out.println("Disconnected groups:");
                for (List<Integer> group : disconnectedGroups) {
                    System.out.println(group);
                }
            }
        }

        sc.close();
    }

    private static void dfs(int curr, boolean[] visited, int[][] adj, int v, int ignore, List<Integer> group) {
        visited[curr] = true;
        group.add(curr);

        for (int k = 1; k <= v; k++) {
            if (adj[curr][k] == 1 && k != ignore && !visited[k]) {
                dfs(k, visited, adj, v, ignore, group);
            }
        }
    }
}
def optCost(freq, i, j):
    if j < i:
        return 0
    if j == i:
        return freq[i]
    
    fsum = Sum(freq, i, j)
    Min = 999999999999
    
    for r in range(i, j + 1):
        cost = (optCost(freq, i, r - 1) +
                optCost(freq, r + 1, j))
        if cost < Min:
            Min = cost
    
    return Min + fsum

def optimalSearchTree(keys, freq, n):
    return optCost(freq, 0, n - 1)

def Sum(freq, i, j):
    s = 0
    for k in range(i, j + 1):
        s += freq[k]
    return s

if __name__ == '__main__':
    n = int(input("Enter the number of keys: "))
    
    keys = []
    freq = []
    
    for i in range(n):
        key = int(input(f"Enter key {i + 1}: "))
        frequency = int(input(f"Enter frequency for key {key}: "))
        keys.append(key)
        freq.append(frequency)
    
    print("Cost of Optimal BST is", optimalSearchTree(keys, freq, n))
class Item:
    def __init__(self, value, weight):
        self.value = value
        self.weight = weight
        self.ratio = value / weight

def fractional_knapsack(items, capacity):
    items.sort(key=lambda item: item.ratio, reverse=True)
    total_value = 0.0
    for item in items:
        if capacity >= item.weight:
            capacity -= item.weight
            total_value += item.value
        else:
            total_value += item.ratio * capacity
            break
    return total_value

n = int(input("Enter the number of items: "))
items = []

for i in range(n):
    value = float(input(f"Enter value of item {i+1}: "))
    weight = float(input(f"Enter weight of item {i+1}: "))
    items.append(Item(value, weight))

capacity = float(input("Enter the capacity of the knapsack: "))
max_value = fractional_knapsack(items, capacity)
print(f"Maximum value in the knapsack: {max_value}")
import java.util.Scanner;

public class OptimalBinarySearchTree {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input number of keys
        System.out.print("Enter the number of keys: ");
        int n = scanner.nextInt();

        // Input keys
        int[] keys = new int[n];
        System.out.println("Enter the keys:");
        for (int i = 0; i < n; i++) {
            keys[i] = scanner.nextInt();
        }

        // Input probabilities for each key
        double[] probabilities = new double[n];
        System.out.println("Enter the probabilities for each key:");
        for (int i = 0; i < n; i++) {
            probabilities[i] = scanner.nextDouble();
        }

        // Calculate minimum cost of Optimal BST
        double minCost = optimalBST(keys, probabilities, n);

        System.out.println("Minimum cost of Optimal BST: " + minCost);

        scanner.close();
    }

    public static double optimalBST(int[] keys, double[] probabilities, int n) {
        double[][] cost = new double[n + 1][n + 1];
        double[][] sumProb = new double[n + 1][n + 1];

        // Initialize the cost for a single key
        for (int i = 0; i < n; i++) {
            cost[i][i] = probabilities[i];
            sumProb[i][i] = probabilities[i];
        }

        // Fill cost and sumProb matrices for increasing chain lengths
        for (int length = 2; length <= n; length++) {
            for (int i = 0; i <= n - length; i++) {
                int j = i + length - 1;
                cost[i][j] = Double.MAX_VALUE;
                sumProb[i][j] = sumProb[i][j - 1] + probabilities[j];

                // Find the minimum cost with different roots
                for (int r = i; r <= j; r++) {
                    double c = (r > i ? cost[i][r - 1] : 0) +
                               (r < j ? cost[r + 1][j] : 0) +
                               sumProb[i][j];
                    if (c < cost[i][j]) {
                        cost[i][j] = c;
                    }
                }
            }
        }

        return cost[0][n - 1];
    }
}
// Returns addition of two numbers exports.add = function (a, b) { return a+b;
};
// Returns difference of two numbers exports.subtract = function (a, b) { return a-b;
};
// Returns product of two numbers exports.multiply = function (a, b) { return a*b;
};
moduleExample.js
var calculator = require('./calculator'); var a=10, b=5;
console.log("Addition : "+calculator.add(a,b)); console.log("Subtraction : "+calculator.subtract(a,b)); console.log("Multiplication : "+calculator.multiply(a,b));\

import java.util.*;

class Graph {
    private final int vertices;
    private final List<List<Node>> adjList;

    static class Node implements Comparable<Node> {
        int vertex, weight;

        Node(int vertex, int weight) {
            this.vertex = vertex;
            this.weight = weight;
        }

        @Override
        public int compareTo(Node other) {
            return Integer.compare(this.weight, other.weight);
        }
    }

    public Graph(int vertices) {
        this.vertices = vertices;
        adjList = new ArrayList<>(vertices);
        for (int i = 0; i < vertices; i++) {
            adjList.add(new ArrayList<>());
        }
    }

    public void addEdge(int src, int dest, int weight) {
        adjList.get(src).add(new Node(dest, weight));
        adjList.get(dest).add(new Node(src, weight)); // For undirected graph; remove if directed
    }

    public void dijkstra(int source) {
        int[] dist = new int[vertices];
        Arrays.fill(dist, Integer.MAX_VALUE);
        dist[source] = 0;

        PriorityQueue<Node> priorityQueue = new PriorityQueue<>();
        priorityQueue.add(new Node(source, 0));

        while (!priorityQueue.isEmpty()) {
            Node current = priorityQueue.poll();
            int u = current.vertex;

            for (Node neighbor : adjList.get(u)) {
                int v = neighbor.vertex;
                int weight = neighbor.weight;

                if (dist[u] + weight < dist[v]) {
                    dist[v] = dist[u] + weight;
                    priorityQueue.add(new Node(v, dist[v]));
                }
            }
        }

        printSolution(dist, source);
    }

    private void printSolution(int[] dist, int source) {
        System.out.println("Vertex\t\tDistance from Source " + source);
        for (int i = 0; i < vertices; i++) {
            System.out.println(i + "\t\t" + dist[i]);
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input number of vertices and edges
        System.out.print("Enter the number of vertices: ");
        int vertices = scanner.nextInt();
        System.out.print("Enter the number of edges: ");
        int edges = scanner.nextInt();

        Graph graph = new Graph(vertices);

        // Input edges
        System.out.println("Enter each edge (source, destination, weight):");
        for (int i = 0; i < edges; i++) {
            int src = scanner.nextInt();
            int dest = scanner.nextInt();
            int weight = scanner.nextInt();
            graph.addEdge(src, dest, weight);
        }

        // Input the source vertex
        System.out.print("Enter the source vertex: ");
        int source = scanner.nextInt();

        // Run Dijkstra's algorithm
        graph.dijkstra(source);

        scanner.close();
    }
}
import heapq

def tree(V, E, edges):
    adj = [[] for _ in range(V)]
    for i in range(E):
        u, v, wt = edges[i]
        adj[u].append((v, wt))
        adj[v].append((u, wt))
        
    pq = []
    visited = [False] * V
    res = 0
    heapq.heappush(pq, (0, 0))
    
    while pq:
        wt, u = heapq.heappop(pq)
        if visited[u]:
            continue
        res += wt
        visited[u] = True
        for v, weight in adj[u]:
            if not visited[v]:
                heapq.heappush(pq, (weight, v))
                
    return res

# Take user input
V = int(input("Enter the number of vertices: "))
E = int(input("Enter the number of edges: "))
edges = []

for i in range(E):
    u, v, wt = map(int, input(f"Enter edge {i + 1} (u v weight): ").split())
    edges.append([u, v, wt])

# Function call and result output
print("Sum of weights of the Minimum Spanning Tree:", tree(V, E, edges))
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

class Job {
    int id;     // Job ID
    int profit; // Profit if job is completed
    int deadline; // Deadline by which job should be completed

    Job(int id, int profit, int deadline) {
        this.id = id;
        this.profit = profit;
        this.deadline = deadline;
    }
}

public class JobSequencing {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input the number of jobs
        System.out.print("Enter the number of jobs: ");
        int n = scanner.nextInt();
        Job[] jobs = new Job[n];

        // Input each job's ID, profit, and deadline
        for (int i = 0; i < n; i++) {
            System.out.print("Enter job ID, profit, and deadline for job " + (i + 1) + ": ");
            int id = scanner.nextInt();
            int profit = scanner.nextInt();
            int deadline = scanner.nextInt();
            jobs[i] = new Job(id, profit, deadline);
        }

        // Calculate the maximum profit and print the job sequence
        int totalProfit = jobSequencing(jobs, n);

        System.out.println("Total Profit: " + totalProfit);
        
        scanner.close();
    }

    public static int jobSequencing(Job[] jobs, int n) {
        // Sort jobs by profit in descending order
        Arrays.sort(jobs, Comparator.comparingInt((Job job) -> job.profit).reversed());

        // Find the maximum deadline to create the job schedule array
        int maxDeadline = 0;
        for (Job job : jobs) {
            maxDeadline = Math.max(maxDeadline, job.deadline);
        }

        // Array to keep track of the free time slots
        int[] result = new int[maxDeadline + 1]; // 1-based index
        Arrays.fill(result, -1); // Initialize all time slots to -1 (indicating free)

        int totalProfit = 0;

        System.out.println("\nSelected Jobs:");
        System.out.println("Job ID | Profit | Deadline");

        // Iterate over each job
        for (Job job : jobs) {
            // Find a free time slot for this job (latest possible slot before deadline)
            for (int j = job.deadline; j > 0; j--) {
                if (result[j] == -1) { // If slot j is free
                    result[j] = job.id; // Assign job to this slot
                    totalProfit += job.profit;
                    System.out.println("   " + job.id + "    |   " + job.profit + "  |    " + job.deadline);
                    break;
                }
            }
        }

        return totalProfit;
    }
}
connection to a database:
var mysql = require('mysql');
var con =mysql.createConnection({ host:"localhost",
user:"root", password:"123456", database:"emp"
});
con.connect(function(err) { if (err) throw err;
con.query("SELECT *FROM employ",function(err,result,fields){ if (err) throw err; console.log(result);
});
});
OUTPUT:
 

Step-2:
Creating a table:
var mysql = require('mysql');
var con =mysql.createConnection({ host:"localhost",
user:"root", password:"123456", database:"emp"
});
con.connect(function(err) { if (err) throw err; console.log("Connected!");
var sql="CREATE TABLE employ (name VARCHAR(255),address VARCHAR(255))"; con.query(sql,function(err,result) {
if (err) throw err; console.log("Table created");
});
});
Output:

Step-3:
Inserting into table:
var mysql = require('mysql');
var con =mysql.createConnection({ host:"localhost",
 
user:"root", password:"123456", database:"emp"
});
con.connect(function(err) { if (err) throw err; console.log("Connected!");
var sql="INSERT INTO employ (name,address)VALUES('PAVAN','SKP')";
con.query(sql,function(err,result){ if (err) throw err;
console.log("1 record inserted");
});
});
Output:

Step-4:
Displaying the data:
var mysql = require('mysql');
var con =mysql.createConnection({ host:"localhost",
user:"root", password:"123456", database:"emp"
});
con.connect(function(err) { if (err) throw err;
con.query("SELECT *FROM employ",function(err,result,fields){ if (err) throw err; console.log(result);
});
});
Output:

import java.util.Scanner;

public class Knapsack01 {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input the number of items
        System.out.print("Enter the number of items: ");
        int n = scanner.nextInt();

        // Input weights and values of items
        int[] weights = new int[n];
        int[] values = new int[n];
        
        System.out.println("Enter the weights of the items:");
        for (int i = 0; i < n; i++) {
            weights[i] = scanner.nextInt();
        }

        System.out.println("Enter the values of the items:");
        for (int i = 0; i < n; i++) {
            values[i] = scanner.nextInt();
        }

        // Input the capacity of the knapsack
        System.out.print("Enter the capacity of the knapsack: ");
        int capacity = scanner.nextInt();

        // Solve the 0/1 Knapsack problem
        int maxProfit = knapsack(weights, values, capacity, n);

        System.out.println("Maximum profit: " + maxProfit);
        
        scanner.close();
    }

    public static int knapsack(int[] weights, int[] values, int capacity, int n) {
        int[][] dp = new int[n + 1][capacity + 1];

        // Fill the DP table
        for (int i = 1; i <= n; i++) {
            for (int w = 1; w <= capacity; w++) {
                if (weights[i - 1] <= w) {
                    // Include the item and maximize the profit
                    dp[i][w] = Math.max(values[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i - 1][w]);
                } else {
                    // Exclude the item
                    dp[i][w] = dp[i - 1][w];
                }
            }
        }

        // Backtrack to find the items that are included
        int[] solution = new int[n];
        int w = capacity;
        
        for (int i = n; i > 0 && w > 0; i--) {
            // If the item is included in the optimal solution
            if (dp[i][w] != dp[i - 1][w]) {
                solution[i - 1] = 1; // Mark as included
                w -= weights[i - 1];
            } else {
                solution[i - 1] = 0; // Mark as not included
            }
        }

        // Print the solution array
        System.out.print("Solution array (1 means included, 0 means not included): ");
        for (int i = 0; i < n; i++) {
            System.out.print(solution[i] + " ");
        }
        System.out.println();

        return dp[n][capacity];
    }
}
A)	Angular Js data binding.
PROGRAM:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div data-ng-app="" data-ng- init="quantity=1;price=20"> <h2>Cost Calculator</h2> Quantity: <input type="number" ng-model="quantity"> Price: <input type="number" ng-model="price">
<p><b>Total in rupees:</b> {{quantity * price}}</p>
</div>
</body>
</html>

B)	Angular JS directives and Events.
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="myFunction()">Click me!</button> <p>{{ count }}</p>
</div>
<script>
var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) {
$scope.count = 0;
$scope.myFunction = function() {
$scope.count++;
}
});
</script>

C)	Using angular Js fetching data from MySQL.
1.	Table structure
I am using users table in the tutorial example. CREATE TABLE `users` (
`id` int(11) NOT NULL PRIMARY KEY
AUTO_INCREMENT, `fname` varchar(80) NOT NULL,
`lname` varchar(80) NOT NULL,
`username` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT
CHARSET=latin1; 2. Configuration
Create a new config.php file for database configuration. Completed Code
<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
3.	HTML
You can either download and include angular.min.js in the page or use CDN.
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js'></script> Define <body ng-app='myapp'> and <div ng-controller='userCtrl'> on the page.
 
For displaying data create a <table> layout and specify ng-repeat directive on a row. Which loop through all available
data in users Array. Completed Code
<!doctype html>
<html>
<head>
<title>How to get data from MySQL with AngularJS - PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
</head>
<body ng-app='myapp'>
<div ng-controller="userCtrl">
<table >
<tr>
<th>First name</th>
<th>Last name</th>
<th>Username</th>
</tr>
<!-- Display records -->
<tr ng-repeat="user in users">
<td>{{user.fname}}</td>
<td>{{user.lname}}</td>
<td>{{user.username}}</td>
</tr>
</table>
</div>
</body>
</html>
4.	PHP
Create a getData.php file.
From here return JSON Array which has user details (fname, lname, and username). Completed Code
<?php
include 'config.php';
$sel = mysqli_query($con,"select * from users");
$data = array();
while ($row = mysqli_fetch_array($sel)) {
$data[] = array("fname"=>$row['fname'],"lname"=>$row['lname'],"username"=>$row['username']);
}
echo json_encode($data);
5.	Script
Create new module and setup AJAX request in controller ( userCtrl ). Path – Passing file name getData.php in url and set method to get.
Success – AJAX successfully callback handle by then where store reponse.data to $scope.users. At HTML end display data using ng-repeat directive.
Completed Code
<script>
var fetch = angular.module('myapp', []);
fetch.controller('userCtrl', ['$scope', '$http', function ($scope, $http) {
$http({ method: 'get',
url: 'getData.php'
}).then(function successCallback(response) {
// Store response data
$scope.users = response.data;
});
}]);
</script>
MainActivity.kt:
package com.cscorner.myapplication

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.cscorner.myapplication.ui.theme.MyApplicationTheme

class MainActivity : ComponentActivity() {
    private lateinit var userET:EditText
    private lateinit var passET: EditText
    //private lateinit var resetBtn: Button
    lateinit var loginBtn: Button
    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)


        enableEdgeToEdge()
        setContentView(R.layout.activity_main)

        userET = findViewById(R.id.editTextText3)
        passET = findViewById(R.id.editTextText4)
        loginBtn =findViewById(R.id.button3)
        loginBtn.setOnClickListener {

            if(userET.text.toString()=="cvr" && passET.text.toString()=="cvr123")
            {
                val intent= Intent(this,MainActivity2::class.java)
                intent.putExtra("Username",userET.text.toString())
                intent.putExtra("Password",passET.text.toString())
                startActivity(intent)
                Toast.makeText(this,"login success",Toast.LENGTH_LONG).show()
            }
            else
            {
                Toast.makeText(this,"error login ",Toast.LENGTH_LONG).show()
            }
        }



    }
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <EditText
            android:id="@+id/editTextText3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPersonName"
            android:minHeight="48dp"
            android:text="Enter Name"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.497"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.276" />

        <EditText
            android:id="@+id/editTextText4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPassword"
            android:minHeight="48dp"
            android:text="Password"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.497"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.377" />

        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Dengu"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.5" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
MainActivity2.kt:
package com.cscorner.myapplication

import android.os.Bundle
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import android .content.Intent
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity2 : AppCompatActivity() {
    private lateinit var resultTV:TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main2)

        resultTV=findViewById(R.id.textView)
        val intent: Intent =intent
        var user=intent.getStringExtra("Username")
        var pass=intent.getStringExtra("Password")
        resultTV.text=user+" " +pass
    }
}
activity_main2.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity2">

    <TextView
        android:id="@+id/textView"
        android:layout_width="201dp"
        android:layout_height="31dp"
        android:text="Welcome"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5" />
</androidx.constraintlayout.widget.ConstraintLayout>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.Light"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity2"/>
    </application>

</manifest>
var express=require("express");
var bodyParser=require("body-parser"); const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/tutorialsPoint'); var db=mongoose.connection;
db.on('error', console.log.bind(console, "connection error")); db.once('open', function(callback){ console.log("connection succeeded"); })
var app=express() app.use(bodyParser.json()); app.use(express.static('public')); app.use(bodyParser.urlencoded({ extended: true
}));
app.post('/sign_up', function(req,res){ var name = req.body.name;
var email =req.body.email; var pass = req.body.password; var phone =req.body.phone; var data = {
"name": name, "email":email, "password":pass, "phone":phone
}
db.collection('details').insertOne(data,function(err, collection){ if (err) throw err; console.log("Record inserted Successfully");
});
return res.redirect('success.html');
})
app.get('/',function(req,res){ res.set({
'Access-control-Allow-Origin': '*'
});
return res.redirect('index.html');
}).listen(3000)
console.log("server listening at port 3000"); index.html
<!DOCTYPE html>
<html>
<head>
<title> Signup Form</title>
<link rel="stylesheet" href=
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css integrity=
"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<br>
<br>
<br>
<div class="container" >
<div class="row">
 
</div>
<div class="main">
<form action="/sign_up" method="post">
<h1>Welcome to Tutorials Point - SignUp</h1>
<input class="box" type="text" name="name" id="name" placeholder="Name" required /><br> <input class="box" type="email" name="email" id="email" placeholder="E-Mail " required /><br>
<input class="box" type="password" name="password" id="password" placeholder="Password " required/><br>
<input class="box" type="text" name="phone" id="phone" placeholder="Phone Number " required/><br> <br>
<input type="submit" id="submitDetails" name="submitDetails" class="registerbtn" value="Submit" />
<br> </form>
</div>
<div class="">
</div>
</div>
</div>
</body>
</html> success.html
<!DOCTYPE html>
<html>
<head>
<title> Signup Form</title>
<link rel="stylesheet" href=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity=
"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<br>
<br>
<br>
<div class="container" >
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6 main">
<h1> Signup Successful</h1>
</div>
<div class="col-md-3">
</div>
</div>
</div>
</body>
</html> style.css
.main{ padding:20px;
font-family: 'Helvetica', serif;
box-shadow: 5px 5px 7px 5px #888888;
}
.main h1{
font-size: 40px; text-align:center;
font-family: 'Helvetica', serif;
}
input{
 
font-family: 'Helvetica', serif; width: 100%;
font-size: 20px; padding: 12px 20px; margin: 8px 0; border: none;
border-bottom: 2px solid #4CAF50;
}
input[type=submit] {
font-family: 'Helvetica', serif; width: 100%;
background-color: #4CAF50; border: none;
color: white; padding: 16px 32px; margin: 4px 2px; border-radius: 10px;
}
.registerbtn {
background-color: #4CAF50; color: white;
padding: 16px 20px; margin: 8px 0; border: none; cursor: pointer; width: 100%;
opacity: 0.9;
}
demofile1.html
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.
</p> </body>
</html>
Create a Node.js file that reads the HTML file, and return the content:
Example
var http = require('http'); var fs = require('fs'); http.createServer(function (req, res) { fs.readFile('demofile1.html', function(err, data) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data);

return res.end(); });


}).listen(8080);


OUTPUT:


Create Files:
The File System module has methods for creating new files: fs.appendFile()
fs.open() fs.writeFile()

fs.appendFile() :
The fs.appendFile() method appends specified content to a file. If the file does not exist, the file will be created:
Example:
Create a new file using the appendFile() method:
var fs = require('fs');
fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) { if (err) throw err;
console.log('Saved!');
});


OUTPUT:






fs.open() :
The fs.open() method takes a "flag" as the second argument, if the flag is "w" for "writing", the specified file is opened for writing. If the file does not exist, an empty file is created:
Example:
Create a new, empty file using the open() method: var fs = require('fs');
fs.open('mynewfile2.txt', 'w', function (err, file) { if (err) throw err;
console.log('Saved!');
});

OUTPUT:




fs.writeFile() :
The fs.writeFile() method replaces the specified file and content if it exists. If the file does not exist, a new file, containing the specified content, will be created:
Example:
Create a new file using the writeFile() method: var fs = require('fs');
fs.writeFile('mynewfile3.txt', 'Hello content!', function (err) { if (err) throw err;
console.log('Saved!');
});
OUTPUT:

Update Files:
The File System module has methods for updating files:

fs.appendFile() fs.writeFile() fs.appendFile():
The fs.appendFile() method appends the specified content at the end of the specified file:
Example:
Append "This is my text." to the end of the file "mynewfile1.txt": var fs = require('fs');
fs.appendFile('mynewfile1.txt', ' This is my text.', function (err) { if (err) throw err;
console.log('Updated!');
});


OUTPUT:





fs.writeFile() :
The fs.writeFile() method replaces the specified file and content:
Example:
Replace the content of the file "mynewfile3.txt": var fs = require('fs');
fs.writeFile('mynewfile3.txt', 'This is my text', function (err) { if (err) throw err;
console.log('Replaced!');
});
OUTPUT:




Delete Files:
To delete a file with the File System module, use the fs.unlink() method. The fs.unlink() method deletes the specified file:
Example:
Delete "mynewfile2.txt":
var fs = require('fs'); fs.unlink('mynewfile2.txt', function (err) { if (err) throw err;
console.log('File deleted!');
});
OUTPUT:
MainActivity:
package com.cscorner.myapplication2

import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)


        val button: Button=findViewById(R.id.button)
        button.setOnClickListener{
            rollDice()
        }
    }
    private fun rollDice(){
        val dice=Dice(6)
        val diceRoll=dice.roll()
        val img :ImageView=findViewById(R.id.imageView)
        val drawableResource = when(diceRoll){
            1->R.drawable.dice1
            2->R.drawable.dice2
            3->R.drawable.dice3
            4->R.drawable.dice4
            5->R.drawable.dice5
            else->R.drawable.dice5
        }
        img.setImageResource(drawableResource)
    }
}
class Dice(private val numsides:Int){
    fun roll():Int{
        return (1..numsides).random()
    }
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5"
        tools:srcCompat="@drawable/dice_1" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Roll"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.775" />
</androidx.constraintlayout.widget.ConstraintLayout>
import java.util.Scanner;

public class MergeSort {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of elements in the array: ");
        int n = scanner.nextInt();
        int[] array = new int[n];

        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < n; i++) {
            array[i] = scanner.nextInt();
        }

        System.out.println("Unsorted Array:");
        printArray(array);

        mergeSort(array, 0, array.length - 1);

        System.out.println("\nSorted Array:");
        printArray(array);

        scanner.close();
    }

    public static void mergeSort(int[] array, int left, int right) {
        if (left < right) {
            int mid = (left + right) / 2;

            // Sort first and second halves
            mergeSort(array, left, mid);
            mergeSort(array, mid + 1, right);

            // Merge the sorted halves
            merge(array, left, mid, right);
        }
    }

    public static void merge(int[] array, int left, int mid, int right) {
        int n1 = mid - left + 1;
        int n2 = right - mid;

        // Temporary arrays
        int[] leftArray = new int[n1];
        int[] rightArray = new int[n2];

        // Copy data to temporary arrays
        System.arraycopy(array, left, leftArray, 0, n1);
        System.arraycopy(array, mid + 1, rightArray, 0, n2);

        int i = 0, j = 0;
        int k = left;

        // Merge the temporary arrays back into array
        while (i < n1 && j < n2) {
            if (leftArray[i] <= rightArray[j]) {
                array[k] = leftArray[i];
                i++;
            } else {
                array[k] = rightArray[j];
                j++;
            }
            k++;
        }

        // Copy remaining elements of leftArray
        while (i < n1) {
            array[k] = leftArray[i];
            i++;
            k++;
        }

        // Copy remaining elements of rightArray
        while (j < n2) {
            array[k] = rightArray[j];
            j++;
            k++;
        }
    }

    public static void printArray(int[] array) {
        for (int num : array) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}
MainActivity.kt
package com.cscorner.myapplication3

import android.annotation.SuppressLint
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {
    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        Toast.makeText(applicationContext,"ONCREATE() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onStart() {
        super.onStart()
        Toast.makeText(applicationContext,"ONSTART() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onRestart() {
        super.onRestart()
        Toast.makeText(applicationContext,"ONRESTART() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onResume() {
        super.onResume()
        Toast.makeText(applicationContext,"ONRESUME() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onPause() {
        super.onPause()
        Toast.makeText(applicationContext,"ONPAUSE() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onStop() {
        super.onStop()
        Toast.makeText(applicationContext,"ONSTOP() CALLED",Toast.LENGTH_SHORT).show()
    }
    override fun onDestroy() {
        super.onDestroy()
        Toast.makeText(applicationContext,"ONDESTROY() CALLED",Toast.LENGTH_SHORT).show()
    }
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Hello World!"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintTop_toTopOf="parent" />

  </androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt
package com.cscorner.myapplication4

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.cscorner.myapplication4.databinding.ActivityMainBinding
import kotlin.math.ceil

class MainActivity : AppCompatActivity() {
    lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.button.setOnClickListener() {
            calculateTip()
        }
    }
    fun calculateTip()
    {
        val cost =(binding.cost.text.toString()).toDouble()
        val selected =binding.RG.checkedRadioButtonId
        val tipPercent=when(selected)
        {
            R.id.radioButton ->15
            R.id.radioButton2 ->18
            else -> 20
        }
        var tip=tipPercent*cost
        if(binding.switch2.isChecked)
        {
            tip= ceil(tip)
        }
        binding.textView7.text=tip.toString()
    }
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/cost"
        android:layout_width="241dp"
        android:layout_height="55dp"
        android:ems="10"
        android:inputType="text"
        android:text="Cost"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.119" />

    <RadioGroup
        android:id="@+id/RG"
        android:layout_width="253dp"
        android:layout_height="154dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5"
        tools:ignore="UnknownId">

        <RadioButton
            android:id="@+id/radioButton"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:text="Excelent" />

        <RadioButton
            android:id="@+id/radioButton2"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:text="Very Good" />

        <RadioButton
            android:id="@+id/radioButton3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="48dp"
            android:text="Bad" />

    </RadioGroup>

    <Switch
        android:id="@+id/switch2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="48dp"
        android:text="Switch"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.672"
        tools:ignore="UnknownId,UseSwitchCompatOrMaterialXml" />

    <Button
        android:id="@+id/button"
        android:layout_width="166dp"
        android:layout_height="48dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.79"
        tools:ignore="UnknownId" />

    <TextView
        android:id="@+id/textView7"
        android:layout_width="182dp"
        android:layout_height="30dp"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.91"
        tools:ignore="UnknownId" />

</androidx.constraintlayout.widget.ConstraintLayout>
Build katle
plugins {
    alias(libs.plugins.android.application)
    alias(libs.plugins.jetbrains.kotlin.android)
}

android {
    namespace = "com.cscorner.myapplication4"
    compileSdk = 35

    defaultConfig {
        applicationId = "com.cscorner.myapplication4"
        minSdk = 24
        targetSdk = 34
        versionCode = 1
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            isMinifyEnabled = false
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
    buildFeatures{
        viewBinding= true
    }
}

dependencies {



    implementation(libs.material)
    implementation(libs.androidx.activity)


    androidTestImplementation(libs.androidx.junit)

    implementation ("androidx.core:core-ktx:1.7.0")
    implementation ("androidx.appcompat:appcompat:1.6.1")
    implementation ("com.google.android.material:material:1.9.0")
    implementation ("androidx.constraintlayout:constraintlayout:2.1.4")
    testImplementation ("junit:junit:4.13.2")
    androidTestImplementation ("androidx.test.ext:junit:1.1.5")
    androidTestImplementation ("androidx.test.espresso:espresso-core:3.5.1")
}
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<input ng-model="name">
<h1> My name is {{name}} </h1>
</div>
<script>
var app = angular.module('myApp', []); app.controller('myCtrl',function($scope){
$scope.name = "John Doe";
});
</script>
<p>When you change the name in the input field, the changes will affect the model, and it will also affect the name property in the controller.</p>
</body>
</html>
1.	Start by launching a text editor of your choice.
2.	Next, type the following into the text editor you’ve just opened:
var http = require('http'); http.createServer(function (req, res) res.writeHead(200, {'Content-Type': 'text/html'}); res.end('Hello World!');
}). listen (8080);
3.	Save the file, then exit. Open the PowerShell, and enter the following: node \users\<your_username>\myprogram.js
It will look like nothing has happened. In reality, your script is running in the background. You may see a Windows Defender notice about allowing traffic – for now, click Allow.
4.	Next, open a web browser, and enter the following into the address bar: http://localhost:8080
In the very upper-left corner, you should see the text Hello World!
Right now, your computer is acting like a server. Any other computer that tries to access your system on port 8080 will see the Hello World notice.
To turn off the program, switch back to PowerShell and press Ctrl+C. The system will switch back to a command prompt. You can close this window whenever you are ready.
import java.util.Arrays;
import java.util.Scanner;

public class QuickSortProgram {
    public static void quickSort(int[] arr, int low, int high) {
        if (low < high) {
            int pivotIndex = partition(arr, low, high);
            System.out.println("Pivot selected: " + arr[pivotIndex]);
            System.out.println("Array after partition: " + Arrays.toString(arr));

            quickSort(arr, low, pivotIndex - 1);  // Sort left of pivot
            quickSort(arr, pivotIndex + 1, high); // Sort right of pivot
        }
    }

    private static int partition(int[] arr, int low, int high) {
        int pivot = arr[high];
        int i = low - 1;

        for (int j = low; j < high; j++) {
            if (arr[j] <= pivot) {
                i++;
                swap(arr, i, j);
            }
        }
        swap(arr, i + 1, high);
        return i + 1;
    }

    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of elements in the array: ");
        int n = scanner.nextInt();
        int[] arr = new int[n];

        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < n; i++) {
            arr[i] = scanner.nextInt();
        }

        System.out.println("Initial Array: " + Arrays.toString(arr));
        quickSort(arr, 0, arr.length - 1);
        System.out.println("Sorted Array: " + Arrays.toString(arr));
        
        scanner.close();
    }
}
1.	// getter and setter properties

class CSE {
    var name: String = " "
        get() = field        // getter
        set(value) {         // setter
            field = value
        }
}
fun main(args: Array<String>) {
    val c = CSE()
    c.name = "WELCOME TO CSE-B"   // access setter
    println(c.name)               // access getter
}

Output:
WELCOME TO CSE-B
******************************************************************************************
2.   //DWELLINGS PROGRAM
 /**
* Program that implements classes for different kinds of dwellings.
* Shows how to:
* Create class hierarchy, variables and functions with inheritance,
* abstract class, overriding, and private vs. public variables.
*/

import kotlin.math.PI
import kotlin.math.sqrt

fun main() {
   val squareCabin = SquareCabin(6, 50.0)
   val roundHut = RoundHut(3, 10.0)
   val roundTower = RoundTower(4, 15.5)

   with(squareCabin) {
       println("\nSquare Cabin\n============")
       println("Capacity: ${capacity}")
       println("Material: ${buildingMaterial}")
       println("Floor area: ${floorArea()}")
   }

   with(roundHut) {
       println("\nRound Hut\n=========")
       println("Material: ${buildingMaterial}")
       println("Capacity: ${capacity}")
       println("Floor area: ${floorArea()}")
       println("Has room? ${hasRoom()}")
       getRoom()
       println("Has room? ${hasRoom()}")
       getRoom()
       println("Carpet size: ${calculateMaxCarpetLength()}")
   }

   with(roundTower) {
       println("\nRound Tower\n==========")
       println("Material: ${buildingMaterial}")
       println("Capacity: ${capacity}")
       println("Floor area: ${floorArea()}")
       println("Carpet Length: ${calculateMaxCarpetLength()}")
   }
}


/**
* Defines properties common to all dwellings.
* All dwellings have floorspace,
* but its calculation is specific to the subclass.
* Checking and getting a room are implemented here
* because they are the same for all Dwelling subclasses.
*
* @param residents Current number of residents
*/
abstract class Dwelling(private var residents: Int) {
   abstract val buildingMaterial: String
   abstract val capacity: Int

   /**
    * Calculates the floor area of the dwelling.
    * Implemented by subclasses where shape is determined.
    *
    * @return floor area
    */
   abstract fun floorArea(): Double

   /**
    * Checks whether there is room for another resident.
    *
    * @return true if room available, false otherwise
    */
   fun hasRoom(): Boolean {
       return residents < capacity
   }

   /**
    * Compares the capacity to the number of residents and
    * if capacity is larger than number of residents,
    * add resident by increasing the number of residents.
    * Print the result.
    */
   fun getRoom() {
       if (capacity > residents) {
           residents++
           println("You got a room!")
       } else {
           println("Sorry, at capacity and no rooms left.")
       }
   }

   }

/**
* A square cabin dwelling.
*
*  @param residents Current number of residents
*  @param length Length
*/
class SquareCabin(residents: Int, val length: Double) : Dwelling(residents) {
   override val buildingMaterial = "Wood"
   override val capacity = 6

   /**
    * Calculates floor area for a square dwelling.
    *
    * @return floor area
    */
   override fun floorArea(): Double {
       return length * length
   }

}

/**
* Dwelling with a circular floorspace
*
* @param residents Current number of residents
* @param radius Radius
*/
open class RoundHut(
       residents: Int, val radius: Double) : Dwelling(residents) {

   override val buildingMaterial = "Straw"
   override val capacity = 4

   /**
    * Calculates floor area for a round dwelling.
    *
    * @return floor area
    */
   override fun floorArea(): Double {
       return PI * radius * radius
   }

   /**
    *  Calculates the max length for a square carpet
    *  that fits the circular floor.
    *
    * @return length of square carpet
    */
    fun calculateMaxCarpetLength(): Double {
        return sqrt(2.0) * radius
    }
}

/**
* Round tower with multiple stories.
*
* @param residents Current number of residents
* @param radius Radius
* @param floors Number of stories
*/
class RoundTower(
       residents: Int,
       radius: Double,
       val floors: Int = 2) : RoundHut(residents, radius) {

   override val buildingMaterial = "Stone"

   // Capacity depends on the number of floors.
   override val capacity = floors * 4

   /**
    * Calculates the total floor area for a tower dwelling
    * with multiple stories.
    *
    * @return floor area
    */
   override fun floorArea(): Double {
       return super.floorArea() * floors
   }
}

Output:
Square Cabin
============
Capacity: 6
Material: Wood
Floor area: 2500.0

Round Hut
=========
Material: Straw
Capacity: 4
Floor area: 314.1592653589793
Has room? true
You got a room!
Has room? false
Sorry, at capacity and no rooms left.
Carpet size: 14.142135623730951

Round Tower
==========
Material: Stone
Capacity: 8
Floor area: 1509.5352700498956
Carpet Length: 21.920310216782976
******************************************************************************************
3.4.5.6.	// companion object
class CSE {
    companion object Test  {                 //companion object name Test
        fun section_b() = println("WELCOME TO CSE-B MAD LAB")
    }
}
fun main(args: Array<String>) {
    CSE.section_b()   // method accessing using class name
}
Output:
WELCOME TO CSE-B MAD LAB
******************************************************************************************
7.	// anonymous function 

// anonymous function  with body as an expression
val anonymous1 = fun(x: Int, y: Int): Int = x + y
// anonymous function with body as a block
val anonymous2 = fun(a: Int, b: Int): Int 
{
			val mul = a * b
			return mul
}
fun main(args: Array<String>) 
{
	//invoking functions
	val sum = anonymous1(3,5)
	val mul = anonymous2(3,5)
	println("The sum of two numbers is: $sum")
	println("The multiply of two numbers is: $mul")
}

Output:
The sum of two numbers is: 8
The multiply of two numbers is: 15
******************************************************************************************
8.   //WHEN DEMONSTRATION
fun main() {  
  val day = 4
  val result = when (day) {
  1 -> "Monday"
  2 -> "Tuesday"
  3 -> "Wednesday"
  4 -> "Thursday"
  5 -> "Friday"
  6 -> "Saturday"
  7 -> "Sunday"
  else -> "Invalid day."
}
println(result)         // DISPLAYS OUTPUT AS "Thursday"
}

Output:
Thursday
******************************************************************************************
9.//DICE ROLLER PROGRAM USING CLASSES
// Random() is an abstract class which generates random numbers with the given conditions. It can be accessed after importing Kotlin.random.Random.
//IntRange is another data type, and it represents a range of integer numbers from a starting point to an endpoint. 
//IntRange is a suitable data type for representing the possible values a dice roll can produce.
class Dice {
    var sides = 6
    fun roll(): Int {
        //random() function to generate random numbers. 
        //random() takes a series of numbers as an input and it returns a random Int as an output.
        val randomNumber = (1..sides).random()  
        return randomNumber
    }
}
fun main() {
    val myFirstDice = Dice()
    val diceRoll = myFirstDice.roll()
    println("Your ${myFirstDice.sides} sided dice rolled ${diceRoll}!")

    myFirstDice.sides = 20
    println("Your ${myFirstDice.sides} sided dice rolled ${myFirstDice.roll()}!")
}

Output:
Your 6 sided dice rolled 4!
Your 20 sided dice rolled 1!
 ******************************************************************************************
10.   //  DATA TYPE demonstration
fun main()
{
    val a: Int = 5                // Int
    val b: Double = 5.99        // Double
    val c: Char = 'v'          // Char
    val d: Boolean = true     // Boolean
    val e: String = "CSE B"      // String
    val f: Float = 100.00f      // float
    println("a value is:" +a)
    println("b value is:" +b)
    println("c value is:" +c)
    println("d value is:" +d)
    println("e value is:" +e) 
    println("f value is:" +f)
}

Output:
a value is:5
b value is:5.99
c value is:v
d value is:true
e value is:CSE B
f value is:100.0
******************************************************************************************
11.loops and arrays of
// WHILE Loop demonstration
fun main() {  
  var i = 0
while (i < 5) {
  println(i)
  i++
} 
}
16.	// DO WHILE LOOP  demonstration
fun main() { 
    var i=0
 do {
  println(i)
  i++
  }
while (i < 5) 
}



17.	// FOR  LOOP  demonstration
fun main() { 
    val cse = arrayOf("CSE A", "CSE B", "CSE C", "CSE D")
for (x in cse) {
  println(x)
} 
}


18.	// BREAK  demonstration
fun main() { 
   var i = 0
while (i < 10) {
  println(i)
  i++
  if (i == 4) {
    break
  }
}



19.	//CONTINUE  demonstration
fun main() { 
  var i = 0
while (i < 10) 
    {
  if (i == 4) 
    {
    i++
    continue   
  }
  println(i)
  i++
}  
}



20.	//RANGE  demonstration
fun main() { 
for (n in 5..15) {
  println(n)
} 
}



21.	//ARRAY  demonstration
 fun main() { 
val  cse = arrayOf("CSE A", "CSE B", "CSE C", "CSE D")
println(cse.size)  // check array length or size
for (x in cse) 
{
  println(x)          
 }
println(cse[0])    // You can access an array element by referring to the index number, inside square brackets

if ("CSE B" in cse) 
{
  println("It exists!") 
} 
    else 
{
  println("It does not exist.")  
 }    
 }
******************************************************************************************
12.	//  ARTHIMETIC OPERATOR demonstration
fun main()
{
    var sum1 = 100 + 50       // 150 (100 + 50)
var sum2 = sum1 + 250     // 400 (150 + 250)
var sum3 = sum2 + sum2    // 800 (400 + 400)
println(sum3)
}

  Output:
  800
 ******************************************************************************************
13.8.	//primary constructor
fun main(args: Array<String>)
{
	val add = Add(5, 6)
	println("The Sum of numbers 5 and 6 is: ${add.c}")
}
class Add constructor(a: Int,b:Int)
{
	var c = a+b;
}

Output:
The Sum of numbers 5 and 6 is 11


******************************************************************************************
15.arrayOf() functoin , android app using intent 
 
fun main() 
{ 
  val  n:IntArray = intArrayOf(1, 2, 3, 4, 5) 
 println("Value at 3rd position : " + n[2]) 
}
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

class Job {
    String id;
    int deadline, profit;

    Job(String id, int deadline, int profit) {
        this.id = id;
        this.deadline = deadline;
        this.profit = profit;
    }
}

public class JobScheduling {

    public static void printJobScheduling(Job[] arr, int t) {
        int n = arr.length;

        Arrays.sort(arr, (a, b) -> b.profit - a.profit);

        boolean[] result = new boolean[t];
        String[] job = new String[t];
        Arrays.fill(job, "-1");

        for (int i = 0; i < n; i++) {
            for (int j = Math.min(t - 1, arr[i].deadline - 1); j >= 0; j--) {
                if (!result[j]) {
                    result[j] = true;
                    job[j] = arr[i].id;
                    break;
                }
            }
        }

        System.out.println("Job sequence for maximum profit:");
        for (String j : job) {
            if (!j.equals("-1")) {
                System.out.print(j + " ");
            }
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the number of jobs: ");
        int n = sc.nextInt();
        Job[] arr = new Job[n];

        for (int i = 0; i < n; i++) {
            System.out.print("Enter job ID for job " + (i + 1) + ": ");
            String jobId = sc.next();
            System.out.print("Enter deadline for job " + (i + 1) + ": ");
            int deadline = sc.nextInt();
            System.out.print("Enter profit for job " + (i + 1) + ": ");
            int profit = sc.nextInt();
            arr[i] = new Job(jobId, deadline, profit);
        }

        System.out.print("Enter the maximum number of time slots available: ");
        int t = sc.nextInt();

        printJobScheduling(arr, t);
        sc.close();
    }
}
def dfs(adj, V, vis, i, curr):
    vis[curr] = 1
    for x in adj[curr]:
        if x != i and not vis[x]:
            dfs(adj, V, vis, i, x)

def AP(adj, V):
    for i in range(1, V + 1):
        components = 0
        vis = [0] * (V + 1)
        for j in range(1, V + 1):
            if j != i:
                if not vis[j]:
                    components += 1
                    dfs(adj, V, vis, i, j)
        if components > 1:
            print(i)

def addEdge(adj, u, v):
    adj[u].append(v)
    adj[v].append(u)

V = int(input("Enter the number of vertices: "))
E = int(input("Enter the number of edges: "))
adj = [[] for _ in range(V + 1)]

for _ in range(E):
    u, v = map(int, input("Enter edge (u v): ").split())
    addEdge(adj, u, v)

print("Articulation points in the graph:")
AP(adj, V)
[_ROWNUMBER] = MIN(SELECT(JetSkies[_ROWNUMBER], AND([Program] = [_THISROW].[Program], ISNOTBLANK([Program]))))
import java.util.*;
public class FractionalKnapSnack {

    private static double calculateMaxP(Item[] ar,int w,Map<Integer,Double> hm) {
       
Arrays.sort(ar,( a,  b)->{
    double d1=(double)(a.profit/a.weight);
    double d2=(double)(b.profit/b.weight);

    if(d1<d2){
        return 1;
    }
    return -1;

});
double res=0;
for(int i=0;i<ar.length;i++){

        if(w-ar[i].weight>=0){
            w=w-ar[i].weight;
            res+=ar[i].profit;
            hm.put(ar[i].no,1D);
            
        }else{
res+=((w*1.0d)/ar[i].weight)*ar[i].profit;   
hm.put(ar[i].no,(w*1.0d)/ar[i].weight) ;
break;  
  }


}

 



        return res;
    }


    public static void main(String[] args) {
        Scanner  sc=new Scanner(System.in);
        System.out.println("enter no of objects");
        int n=sc.nextInt();
        System.out.println("enter the total weight of the knapsnack");
        int w=sc.nextInt();
        Item [] ar=new Item[n];
        for(int i=0;i<n;i++){
           System.out.println("enter profit for item :"+(i+1)); 
           int p=sc.nextInt();
           System.out.println("enter weight for item :"+(i+1)); 
           int wi=sc.nextInt(); 
            Item it=new Item(p, wi,i+1);
            ar[i]=it;

        }
        Map<Integer,Double> sol=new LinkedHashMap<>();
        double res=calculateMaxP(ar,w,sol);
        System.out.println(res);
        System.out.println(sol);
        
            }
        
           
}
public class Item{
    int profit;
    int weight;
    int no;
    Item(int p,int w,int no){
        profit=p;
        weight=w;
        this.no=no;
    }
}
"models": {
			"customer": {
				"type": "sap.ui.model.json.JSONModel",
				"uri": "model/customers.json"
			}
		},
          
          items="{path:'customer>/customers', templateShareable: false}"
import java.util.*;

class Main{
    static final int INF = Integer.MAX_VALUE;
   
    
    int minDistance(int[] dist,Boolean[] sptSet,int V){
        int min= INF ,min_index = -1;
        
        for(int v=0;v<V;v++){
            if(!sptSet[v] && dist[v] <= min){
                min = dist[v];
                min_index = v;
            }
        }
        return min_index;
    }
    
    void dijkistra(int[][] graph,int src,int V){
        int dist[] = new int[V];
        Boolean[] sptSet = new Boolean[V];
        
        Arrays.fill(dist,INF);
        Arrays.fill(sptSet,false);
        
        dist[src] = 0;
        
        for(int cnt=0;cnt<V-1;cnt++){
            int u= minDistance(dist,sptSet,V);
            sptSet[u] = true;
            for(int v=0;v<V;v++){
                if(!sptSet[v]&&graph[u][v]!=0&&dist[u]!=INF && dist[u]+graph[u][v]<dist[v]){
                    dist[v] = dist[u] + graph[u][v];
                }
            }
        }
        printSolution(dist,V);
    }
    void printSolution(int[] dist,int V){
        System.out.println("Vertex \t Distance fromSource");
        for(int i=0;i<V;i++){
            System.out.println(i+"\t"+dist[i]);
        }
    }
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        
        System.out.println("Enter the number of vertices:");
        int n =sc.nextInt();
        
        System.out.println("Enter the adjacancy matrix");
        int[][] graph = new int[n][n];
        
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                graph[i][j] = sc.nextInt();
            }
        }
        
        System.out.println("Enter the source:");
        int src=sc.nextInt();
        Main obj = new Main();
        obj.dijkistra(graph,src,n);
    }
}
star

Wed Nov 06 2024 17:48:40 GMT+0000 (Coordinated Universal Time)

@login123

star

Wed Nov 06 2024 17:48:08 GMT+0000 (Coordinated Universal Time)

@login123

star

Wed Nov 06 2024 17:37:30 GMT+0000 (Coordinated Universal Time)

@login123

star

Wed Nov 06 2024 17:35:48 GMT+0000 (Coordinated Universal Time)

@login123

star

Wed Nov 06 2024 17:33:17 GMT+0000 (Coordinated Universal Time)

@login123

star

Wed Nov 06 2024 17:31:56 GMT+0000 (Coordinated Universal Time)

@signin

star

Wed Nov 06 2024 17:31:55 GMT+0000 (Coordinated Universal Time)

@masangare33 #eventelysium

star

Wed Nov 06 2024 17:31:20 GMT+0000 (Coordinated Universal Time)

@login123

star

Wed Nov 06 2024 17:30:58 GMT+0000 (Coordinated Universal Time)

@login123

star

Wed Nov 06 2024 17:26:38 GMT+0000 (Coordinated Universal Time)

@signin

star

Wed Nov 06 2024 17:23:40 GMT+0000 (Coordinated Universal Time)

@signin

star

Wed Nov 06 2024 17:19:51 GMT+0000 (Coordinated Universal Time)

@varuntej #kotlin

star

Wed Nov 06 2024 17:19:41 GMT+0000 (Coordinated Universal Time)

@signin

star

Wed Nov 06 2024 17:19:29 GMT+0000 (Coordinated Universal Time)

@signin

star

Wed Nov 06 2024 17:13:09 GMT+0000 (Coordinated Universal Time)

@signin

star

Wed Nov 06 2024 17:11:48 GMT+0000 (Coordinated Universal Time)

@signin

star

Wed Nov 06 2024 17:09:17 GMT+0000 (Coordinated Universal Time)

@signin

star

Wed Nov 06 2024 17:07:41 GMT+0000 (Coordinated Universal Time)

@varuntej #kotlin

star

Wed Nov 06 2024 16:53:23 GMT+0000 (Coordinated Universal Time)

@varuntej #kotlin

star

Wed Nov 06 2024 16:45:38 GMT+0000 (Coordinated Universal Time)

@signin

star

Wed Nov 06 2024 16:44:39 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Wed Nov 06 2024 16:44:07 GMT+0000 (Coordinated Universal Time)

@signin

star

Wed Nov 06 2024 16:43:36 GMT+0000 (Coordinated Universal Time)

@sagar123

star

Wed Nov 06 2024 16:41:52 GMT+0000 (Coordinated Universal Time)

@sagar123

star

Wed Nov 06 2024 16:41:01 GMT+0000 (Coordinated Universal Time)

@signin

star

Wed Nov 06 2024 16:40:42 GMT+0000 (Coordinated Universal Time)

@freefire

star

Wed Nov 06 2024 16:39:37 GMT+0000 (Coordinated Universal Time)

@signin

star

Wed Nov 06 2024 16:38:00 GMT+0000 (Coordinated Universal Time)

@sagar123

star

Wed Nov 06 2024 16:36:28 GMT+0000 (Coordinated Universal Time)

@signin

star

Wed Nov 06 2024 16:35:32 GMT+0000 (Coordinated Universal Time)

@freefire

star

Wed Nov 06 2024 16:31:57 GMT+0000 (Coordinated Universal Time)

@signin

star

Wed Nov 06 2024 16:31:23 GMT+0000 (Coordinated Universal Time)

@freefire

star

Wed Nov 06 2024 16:31:13 GMT+0000 (Coordinated Universal Time)

@varuntej #kotlin

star

Wed Nov 06 2024 16:28:41 GMT+0000 (Coordinated Universal Time)

@freefire

star

Wed Nov 06 2024 16:27:11 GMT+0000 (Coordinated Universal Time)

@freefire

star

Wed Nov 06 2024 16:25:15 GMT+0000 (Coordinated Universal Time)

@varuntej #kotlin

star

Wed Nov 06 2024 16:24:08 GMT+0000 (Coordinated Universal Time)

@signin

star

Wed Nov 06 2024 16:23:06 GMT+0000 (Coordinated Universal Time)

@varuntej #kotlin

star

Wed Nov 06 2024 16:20:10 GMT+0000 (Coordinated Universal Time)

@varuntej #kotlin

star

Wed Nov 06 2024 16:19:59 GMT+0000 (Coordinated Universal Time)

@freefire

star

Wed Nov 06 2024 16:18:47 GMT+0000 (Coordinated Universal Time)

@freefire

star

Wed Nov 06 2024 16:18:07 GMT+0000 (Coordinated Universal Time)

@signin

star

Wed Nov 06 2024 16:17:57 GMT+0000 (Coordinated Universal Time)

@varuntej #kotlin

star

Wed Nov 06 2024 16:04:21 GMT+0000 (Coordinated Universal Time)

@sagar123

star

Wed Nov 06 2024 15:35:13 GMT+0000 (Coordinated Universal Time)

@sagar123

star

Wed Nov 06 2024 14:59:37 GMT+0000 (Coordinated Universal Time) https://codepen.io/finnhvman/pen/jLXKJw

@ibrahimst #undefined

star

Wed Nov 06 2024 14:15:25 GMT+0000 (Coordinated Universal Time)

@Wittinunt

star

Wed Nov 06 2024 14:03:11 GMT+0000 (Coordinated Universal Time)

@signup1

star

Wed Nov 06 2024 13:50:17 GMT+0000 (Coordinated Universal Time)

@deepaksingh

star

Wed Nov 06 2024 12:44:48 GMT+0000 (Coordinated Universal Time)

@signup1

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension