Snippets Collections
lambda=0.3;
ht100=100;
ht30=30;
ht2=2;
hr=2;
axis=[];
p100=[];
p30=[];
p2=[];
pfs1=[];
for i=1000:5000
    d=10^(i/1000);
    axis=[axis d];
    fspower=(lambda/(4*3.1415*d))^2;
    power100=fspower*4*(sin(2*3.1415*hr*ht100/(lambda*d)))^2;
    power30=fspower*4*(sin(2*3.1415*hr*ht30/(lambda*d)))^2;
    power2=fspower*4*(sin(2*3.1415*hr*ht2/(lambda*d)))^2;
    p100=[p100,10*log10(power100)];
    p30=[p30,10*log10(power30)];
    p2=[p2,10*log10(power2)];
    pfs1=[pfs1,10*log10(fspower)];
end
text('FontSize',18);
semilogx(axis,p100,'g-',axis,p30,'b-',axis,p2,'r',axis,pfs1,'y-');
xlabel('distance in m');
ylabel('pathloss');
text(1000,-66,'blue: hr=30m');
text(1000,-74,'red: hr=2m');
text(1000,-58,'green: hr=100m');
text(1000,-50,'yellow:freespace');
text(50,-180,'lambda=0.30m');
text(50,-190,'hr=2m');
//@version=5
indicator("LMR with Flat Candles and Rising/Falling Band Logic", overlay=true)

// --- Input for Donchian Channel Period ---
donchianPeriod = input.int(20, title="Donchian Channel Period", minval=1)
flatCandleCount = input.int(3, title="Number of Flat Candles", minval=1)  // Number of candles to check for flatness

// --- Donchian Channel Calculations ---
donchianHigh = ta.highest(high, donchianPeriod)
donchianLow = ta.lowest(low, donchianPeriod)
donchianMid = (donchianHigh + donchianLow) / 2

// --- Plot Donchian Channel ---
plot(donchianHigh, color=color.new(color.blue, 0), title="Donchian High")
plot(donchianLow, color=color.new(color.red, 0), title="Donchian Low")
plot(donchianMid, color=color.new(color.gray, 0), title="Donchian Midline", linewidth=1)

// --- Flat Candle Detection (Checking multiple candles for flatness) ---
isFlatCandle(candleIndex) =>
    math.abs(close[candleIndex] - close[candleIndex-1]) < (high[candleIndex] - low[candleIndex]) * 0.2  // Price change is small compared to range

flatCandles = true
for i = 1 to flatCandleCount
    flatCandles := flatCandles and isFlatCandle(i)  // All previous candles must be flat

// --- Current Band Movement Detection ---
isUpperBandRising = donchianHigh > donchianHigh[1]  // Upper band is rising in the current candle
isUpperBandFlat = donchianHigh == donchianHigh[1]  // Upper band is flat in the current candle
isLowerBandFalling = donchianLow < donchianLow[1]  // Lower band is falling in the current candle

// --- Debugging: Plot the band changes to visualize them ---
plotshape(isUpperBandRising, title="Upper Band Rising", location=location.abovebar, color=color.green, style=shape.triangledown, size=size.small)
plotshape(isUpperBandFlat, title="Upper Band Flat", location=location.abovebar, color=color.blue, style=shape.triangledown, size=size.small)
plotshape(isLowerBandFalling, title="Lower Band Falling", location=location.belowbar, color=color.red, style=shape.triangleup, size=size.small)

// --- Long Condition (Flat candles + Rising Upper Band) ---
longCondition = flatCandles and isUpperBandRising  // Flat candles and upper band rising in current candle

// --- Short Condition (Flat candles + Falling Lower Band + Upper Band Flat) ---
shortCondition = flatCandles and isUpperBandFlat and isLowerBandFalling  // Flat candles and upper band flat + lower band falling

// --- Plot Background Colors for Signals ---
bgcolor(longCondition ? color.new(color.green, 90) : na, title="Long Condition Signal")
bgcolor(shortCondition ? color.new(color.red, 90) : na, title="Short Condition Signal")

// --- Plot Arrows for Signals ---
plotshape(longCondition, title="Long Signal Arrow", location=location.belowbar, color=color.green, style=shape.arrowup, size=size.small)
plotshape(shortCondition, title="Short Signal Arrow", location=location.abovebar, color=color.red, style=shape.arrowdown, size=size.small)

// --- Alerts ---
alertcondition(longCondition, title="Long Signal Alert", message="Flat candles detected, and upper band is rising.")
alertcondition(shortCondition, title="Short Signal Alert", message="Flat candles detected, and upper band is flat and lower band is falling.")

import java.util.Scanner;

public class QuickSort {
    
    public static void quickSort(int[] a, int lb, int ub) {
        if (lb < ub) {
            int pivotIndex = partition(a, lb, ub);
            quickSort(a, lb, pivotIndex - 1);
            quickSort(a, pivotIndex + 1, ub);
        }
    }

    public static int partition(int[] a, int lb, int ub) {
        int pivot = a[lb];
        int start = lb;
        int end = ub;
        while (start < end) {
            while (start <= ub && a[start] <= pivot) {
                start++;
            }
            while (a[end] > pivot) {
                end--;
            }
            if (start < end) {
                int temp = a[start];
                a[start] = a[end];
                a[end] = temp;
            }
        }
        int temp = a[end];
        a[end] = a[lb];
        a[lb] = temp;
        return end;
    }

    public static void display(int[] a) {
        System.out.println("Sorted array:");
        for (int i : a) {
            System.out.print(i + "\t");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter array size:");
        int n = sc.nextInt();
        int[] a = new int[n];
        
        System.out.println("Enter elements into array:");
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
        }
        
        quickSort(a, 0, n - 1);
        display(a);
        
        sc.close();
    }
}

import matplotlib.pyplot as plt
import numpy as np

n = np.linspace(1, 1000, 100)
best_case = n * np.log2(n) 
average_case = n * np.log2(n)  
worst_case = n ** 2  

plt.figure(figsize=(10, 6))
plt.plot(n, best_case, label='Best Case (O(n log n))', color='green')
plt.plot(n, average_case, label='Average Case (O(n log n))', color='blue')
plt.plot(n, worst_case, label='Worst Case (O(n^2))', color='red')

plt.title('Quick Sort Time Complexity')
plt.xlabel('Input Size (n)')
plt.ylabel('Number of Operations')
plt.legend()
plt.grid(True)
plt.show()

% Parameters
bitStream = [1 0 1 1 0 1];  % Example bit stream
chipSequence = [1 -1 1 -1]; % Example chip sequence
 
% DSSS Encoding (Spreading)
spreadSignal = dsss_spread(bitStream, chipSequence);
 
% DSSS Decoding (Despreading)
recoveredBits = dsss_despread(spreadSignal, chipSequence);
 
% Display results
disp('Original bit stream:');
disp(bitStream);
disp('Spread signal:');
disp(spreadSignal);
disp('Recovered bit stream:');
disp(recoveredBits);
 
 
% Function for DSSS Spreading(dsss_spread.m)
function spreadSignal = dsss_spread(bitStream, chipSequence)
    numBits = length(bitStream);
    numChips = length(chipSequence);
    spreadSignal = zeros(1, numBits * numChips);
    
    idx = 1;
    for bit = bitStream
        % Encode each bit with the chip sequence
        if bit == 0
            spreadSignal(idx:idx+numChips-1) = -chipSequence;
        else
            spreadSignal(idx:idx+numChips-1) = chipSequence;
        end
        idx = idx + numChips;
    end
end

% Function for DSSS Despreading(dsss_despread.m)
function recoveredBits = dsss_despread(spreadSignal, chipSequence)
    numChips = length(chipSequence);
    numBits = length(spreadSignal) / numChips;
    recoveredBits = zeros(1, numBits);
    
    for i = 1:numBits
        % Extract the corresponding chips
        chipValues = spreadSignal((i-1)*numChips + :i*numChips);
        
        % Perform correlation with the chip sequence
        correlation = dot(chipValues, chipSequence);
        
        % Decision logic based on correlation
        if correlation > 0
            recoveredBits(i) = 1;
        else
            recoveredBits(i) = 0;
        end
    end
end
import java.util.*; 
 
public class ShortestPath { 
    public static void main(String[] args) { 
        Scanner sc = new Scanner(System.in); 
        System.out.println("Enter number of vertices: "); 
        int n = sc.nextInt(); 
        System.out.println("Enter the adjacency matrix: "); 
        int[][] g = new int[n][n]; 
        for (int i = 0; i < n; i++) { 
            for (int j = 0; j < n; j++) { 
                g[i][j] = sc.nextInt(); 
            } 
        } 
 
        System.out.println("Enter source vertex: "); 
        int v = sc.nextInt(); 
        dijkstras(v, g, n); 
    } 
 
    public static void dijkstras(int v, int[][] cost, int n) { 
        boolean[] s = new boolean[n]; 
        int[] dist = new int[n]; 
        for (int i = 0; i < n; i++) { 
            dist[i] = cost[v][i] == 0 ? Integer.MAX_VALUE : cost[v][i]; 
            s[i] = false; 
        } 
 
        s[v] = true; 
        dist[v] = 0; 
 
        for (int i = 1; i < n - 1; i++) { 
            int u = minDist(dist, s); 
            s[u] = true; 
 
            for (int w = 0; w < n; w++) { 
                if (!s[w] && cost[u][w] != 0) { 
                    if (dist[w] > dist[u] + cost[u][w]) { 
                        dist[w] = dist[u] + cost[u][w]; 
                    } 
                } 
            } 
        } 
 
        System.out.println("Shortest distances from source " + v + " :"); 
        for (int i = 0; i < n; i++) { 
            System.out.println("To node " + i + " - Distance : " + dist[i]); 
        } 
    } 
 
    private static int minDist(int[] dis, boolean[] s) { 
        int min = Integer.MAX_VALUE, idx = -1; 
 
        for (int i = 0; i < dis.length; i++) { 
            if (!s[i] && dis[i] <= min) { 
                min = dis[i]; 
                idx = i; 
            } 
        } 
        return idx; 
    } 
}
import java.util.*; 
 
public class OBST { 
    public static void bst(double[] p, double[] q, int n) { 
        double[][] w = new double[n + 1][n + 1]; 
        double[][] c = new double[n + 1][n + 1]; 
        int[][] r = new int[n + 1][n + 1]; 
 
        for (int i = 0; i <= n; i++) { 
            w[i][i] = q[i]; 
            c[i][i] = 0; 
            r[i][i] = 0; 
        } 
 
        for (int m = 1; 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]; 
                double mincost = Double.MAX_VALUE; 
                int root = -1; 
 
                for (int k = (i < j - 1 ? r[i][j - 1] : i); k <= (j > i + 1 ? r[i + 1][j] : j); k++) { 
                    double cost = (i <= k - 1 ? c[i][k - 1] : 0) + (k <= j ? c[k][j] : 0) + w[i][j]; 
                    if (cost < mincost) { 
                        mincost = cost; 
                        root = k; 
                    } 
                } 
 
                c[i][j] = mincost; 
                r[i][j] = root; 
            } 
        } 
 
        System.out.println("Minimum cost: " + c[0][n]); 
        System.out.println("Weight : " + w[0][n]); 
    } 
 
    public static void main(String[] args) { 
        Scanner sc = new Scanner(System.in); 
        System.out.print("Enter the number of keys: "); 
        int n = sc.nextInt(); 
 
        double[] p = new double[n + 1]; 
        double[] q = new double[n + 1]; 
 
        System.out.println("Enter probabilities for the keys:"); 
        for (int i = 1; i <= n; i++) { 
            System.out.print("p[" + i + "]: "); 
            p[i] = sc.nextDouble(); 
        } 
 
        System.out.println("Enter probabilities for the dummy keys:"); 
        for (int i = 0; i <= n; i++) { 
            System.out.print("q[" + i + "]: "); 
            q[i] = sc.nextDouble(); 
        } 
 
        bst(p, q, n); 
    } 
}
% Clear workspace, close figures, clear command window
clear all;
close all;
clc;

% Parameters
n = 10;              % Number of symbols
m = 4;               % QPSK has 4 symbols (0, 1, 2, 3)
snr = 20;            % Signal-to-Noise Ratio (dB)
bit_rate = 10^3;     % Bit rate in bits per second
f = bit_rate;        % Carrier frequency
tb = 1 / bit_rate;   % Bit duration
t = 0:(tb/1000):tb;  % Time vector for one symbol

% Generate random data
data = randi([0 m-1], 1, n); % Random symbols (0, 1, 2, 3)

% Perform QPSK modulation
s = exp(1j * (2 * pi * data / m + pi/4)); % QPSK symbols with phase offset of pi/4

% Generate the transmitted QPSK signal
txsig = []; % Initialize transmitted signal
for l = 1:length(data)
    % Modulate using I and Q components
    tx = real(s(l)) * cos(2 * pi * f * t) - imag(s(l)) * sin(2 * pi * f * t);
    txsig = [txsig tx]; % Append the modulated signal for the current symbol
end

% Add noise to the transmitted signal (Noisy QPSK signal)
rxsig = txsig + sqrt(0.5 / (10^(snr/10))) * randn(size(txsig)); % Add noise to the real part

% Add noise to QPSK symbols for constellation diagram
r = s + sqrt(0.5 / (10^(snr/10))) * (randn(size(s)) + 1j * randn(size(s)));

% Plot results
figure;

% Plot message signal (original symbols)
subplot(3, 1, 1);
stairs(data, 'LineWidth', 1.5); % Staircase plot for message symbols
grid minor;
ylim([-0.5, m-0.5]); 
xlim([0, n]);
title('Message Signal (Symbols)');
xlabel('Symbol Index');
ylabel('Symbol Value');

% Plot QPSK modulated signal
subplot(3, 1, 2);
plot(txsig, 'LineWidth', 1.5);
grid minor;
title('QPSK Modulated Signal');
xlabel('Time (samples)');
ylabel('Amplitude');
ylim([-1.5, 1.5]);
xlim([0, length(txsig)]);

% Plot noisy QPSK modulated signal
subplot(3, 1, 3);
plot(rxsig, 'LineWidth', 1.5);
grid minor;
title('Noisy QPSK Signal (AWGN Added)');
xlabel('Time (samples)');
ylabel('Amplitude');
xlim([0, length(rxsig)]);

% Constellation diagram
figure;
scatter(real(r), imag(r), 'filled'); % Scatter plot of noisy received symbols
grid minor;
title('Constellation Diagram of QPSK');
xlabel('In-phase (I)');
ylabel('Quadrature (Q)');
axis([-2 2 -2 2]); % Set axis limits for clarity
import java.util.*; 
 
class Job { 
    private int id; 
    private int deadline; 
    private int profit; 
 
    Job(int id, int deadline, int profit) { 
        this.id = id; 
        this.deadline = deadline; 
        this.profit = profit; 
    } 
 
    public int getId() { 
        return id; 
    } 
 
    public int getDeadline() { 
        return deadline; 
    } 
 
    public int getProfit() { 
        return profit; 
    } 
} 
 
public class JobSeq { 
    public static void main(String[] args) { 
        Scanner scan = new Scanner(System.in); 
        System.out.println("enter no of jobs"); 
        int n = scan.nextInt(); 
        Job[] jobs = new Job[n]; 
        System.out.println("emter job id,deadline,profit"); 
        for (int i = 0; i < n; i++) { 
            jobs[i] = new Job(scan.nextInt(), scan.nextInt(), scan.nextInt()); 
        } 
        js(jobs); 
    } 
 
    public static void js(Job[] jobs) { 
        Arrays.sort(jobs, new Comparator<Job>() { 
            public int compare(Job j1, Job j2) { 
                return j2.getProfit() - j1.getProfit(); 
            } 
        }); 
 
        int maxDeadline = 0; 
        for (Job job : jobs) { 
            if (job.getDeadline() > maxDeadline) { 
                maxDeadline = job.getDeadline(); 
            } 
        } 
 
        Job[] result = new Job[maxDeadline]; 
        boolean[] slot = new boolean[maxDeadline]; 
 
        for (Job job : jobs) { 
            for (int j = Math.min(maxDeadline, job.getDeadline()) - 1; j >= 0; j--) { 
                if (!slot[j]) { // If the slot is free 
                    result[j] = job; 
                    slot[j] = true; 
                    break; 
                } 
            } 
        } 
 
        int totalProfit = 0; 
        System.out.println("Scheduled jobs:"); 
        for (Job job : result) { 
            if (job != null) { 
                System.out.println("Job ID: " + job.getId() + ", Profit: " + job.getProfit()); 
                totalProfit += job.getProfit(); 
            } 
        } 
        System.out.println("Total profit: " + totalProfit); 
    } 
 
} 
import java.util.*; 
 
public class Knapsack { 
    public static double greedyKnapSack(ItemValue[] arr, int capacity) { 
        Arrays.sort(arr, new Comparator<ItemValue>() { 
            public int compare(ItemValue item1, ItemValue item2) { 
                double cpr1 = (double) item1.profit / item1.weight; 
                double cpr2 = (double) item2.profit / item2.weight; 
 
                if (cpr1 < cpr2) 
                    return 1; 
                else 
                    return -1; 
 
            } 
        }); 
 
        double total = 0; 
 
        for (ItemValue i : arr) { 
            if ((capacity - i.weight) >= 0) { 
                capacity -= i.weight; 
                total += i.profit; 
            } else { 
                double fract = (double) capacity / (double) i.weight; 
                total += fract * (i.profit); 
                capacity = 0; 
                break; 
            } 
        } 
        return total; 
    } 
 
    public static void main(String[] args) { 
        Scanner sc = new Scanner(System.in); 
        System.out.println("Enter the number of items: "); 
        int n = sc.nextInt(); 
        ItemValue[] arr = new ItemValue[n]; 
        System.out.println("Enter weight, profit of each item: "); 
        for (int i = 0; i < n; i++) { 
            arr[i] = new ItemValue(sc.nextInt(), sc.nextInt()); 
        } 
        System.out.println("Enter capacity :"); 
        int m = sc.nextInt(); 
 
        double pro = greedyKnapSack(arr, m); 
        System.out.println(pro); 
    } 
 
} 
 
class ItemValue { 
    public int weight; 
    public int profit; 
 
    public ItemValue(int weight, int profit) { 
        this.weight = weight; 
        this.profit = profit; 
    } 
 
} 
#include<stdio.h>

void merge(int a[],int b[],int low,int mid,int high){
    int h = low;
    int j = mid+1;
    int i = low;
    while(h<=mid && j<=high){
        if(a[h]<=a[j]){
            b[i] = a[h];
            h += 1;
        }
        else{
            b[i] = a[j];
            j += 1;
        }
        i += 1;
    }
    if(h>mid){
        for(int k=j;k<=high;k++){
            b[i] = a[k];
            i += 1;
        }
    }
    else{
        for(int k=h;k<=mid;k++){
            b[i] = a[k];
            i += 1;
        }
    }
    for(int k=low;k<=high;k++){
        a[k] = b[k];
    }
}

void mergeSort(int a[],int b[] , int low,int high){
    if(low<high){
        int mid = (low+high)/2;
        mergeSort(a,b,low,mid);
        mergeSort(a,b,mid+1,high);
        merge(a,b,low,mid,high);
    }
}

int main(){
    int n;
    printf("\n Enter size:");
    scanf("%d",&n);
    int a[n],b[n];
    printf("\n Enter elements:");
    for(int i = 0 ;i<n;i++){
        scanf("%d",&a[i]);
    }
    mergeSort(a,b,0,n-1);
    printf("\n Sorted Elements:");
    for(int i=0;i<n;i++){
        printf("%d \t",a[i]);
    }
    printf("\n");
    return 0;
}
#include<stdio.h>

void interchange(int a[],int i,int j){
    int temp = a[i];
    a[i] = a[j];
    a[j] = temp;
}

int partition(int a[],int p, int q){
    int v = a[p];
    int i = p,j = q+1;
    do{
        do{
            i = i+1;
        }while(a[i]<v &&  i<=q);
        
        do{
            j = j-1;
        }while(a[j]>v && j>=p);
        
        if(i<j){
            interchange(a,i,j);
        }
    }while(i<j);
    
    interchange(a,p,j);
    return j;
}

void quickSort(int a[] ,int p, int q){
    if(p<q){
        int j = partition(a,p,q);
        quickSort(a,p,j-1);
        quickSort(a,j+1,q);
    }
}

int main(){
    int n;
    printf("\n Enter size:");
    scanf("%d",&n);
    int a[n];
    printf("Enter elements:");
    for(int i=0;i<n;i++){
        scanf("%d",&a[i]);
    }
    quickSort(a,0,n-1);
    printf("\n Sorted Array:");
    for(int i=0;i<n;i++){
        printf("%d \t",a[i]);
    }
    printf("\n");
    return 0;
}

import pandas as pd
from sklearn.preprocessing import MinMaxScaler

data = {'Age': [20, 25, 30, 35, 40],
 'Salary': [20000, 25000, 30000, 35000, 40000]}

df = pd.DataFrame(data)

scaler = MinMaxScaler()


df[['Age_minmax', 'Salary_minmax']] = scaler.fit_transform(df[['Age', 'Salary']])
print(df)
from sklearn.preprocessing import StandardScaler
import pandas as pd

data = {'Age': [20, 25, 30, 35, 40],
 'Salary': [20000, 25000, 30000, 35000, 40000]}

df = pd.DataFrame(data)

scaler = StandardScaler()

df[['Age_scaled', 'Salary_scaled']] = scaler.fit_transform(df[['Age', 'Salary']])
print(df)
from sklearn.preprocessing import OrdinalEncoder

data = {'Size': ['Small', 'Medium', 'Large', 'Medium']}
df = pd.DataFrame(data)

encoder = OrdinalEncoder(categories=[['Small', 'Medium', 'Large']])

df['Size_encoded'] = encoder.fit_transform(df[['Size']])
print(df)
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
data = {
  'City': ['New York', 'Los Angeles', 'Chicago']
		}

df = pd.DataFrame(data)
df_encoded = OneHotEncoder()
df_encoded = pd.get_dummies(df, columns=['City'])
print(df_encoded)
import pandas as pd
from sklearn.preprocessing import LabelEncoder
# Sample DataFrame
data = {'City': ['New York', 'Los Angeles', 'Chicago', 'New York']}
df = pd.DataFrame(data)
# Initialize the label encoder
label_encoder = LabelEncoder()
# Fit and transform the 'City' column
df['City_encoded'] = label_encoder.fit_transform(df['City'])
print(df)
SumOfSub(s, k, r)
{
    // Generate left child
    x[k] = 1
    if (s + w[k] == m) then
        write(x[1 : k]) // Subset found
    else if (s + w[k] + w[k + 1] <= m) then
        SumOfSub(s + w[k], k + 1, r - w[k])

    // Generate right child and evaluate conditions
    if ((s + r - w[k] >= m) and (s + w[k + 1] <= m)) then
    {
        x[k] = 0
        SumOfSub(s, k + 1, r - w[k])
    }
}
ShortestPaths(v, cost, dist, n)
{
    for i = 1 to n do
    {
        S[i] = false
        dist[i] = cost[v, i]
    }
    S[v] = true
    dist[v] = 0.0

    for num = 2 to n - 1 do
    {
        Choose u from vertices not in S such that dist[u] is minimum
        S[u] = true

        for each w adjacent to u with S[w] = false do
        {
            if (dist[w] > dist[u] + cost[u, w]) then
                dist[w] = dist[u] + cost[u, w]
        }
    }
}
{"a":1,"b":2,"c":3,"d":4,"name":["harry","jerry"]}
#Get all pods
kubectl get pods

#Get logs 
kubectl logs atlasai-control-plane-api-549dfcd85b-677zv 

#Delete pod
kubectl delete deployment atlasai-control-plane-api

#Applly local deployment 
kubectl apply -f local_deploy/atlasai-control-plane-api-deployment.yaml
import java.util.Scanner;

public class Main {

    public static int prim(int[][] cost, int n) {
        int[] near = new int[n]; // Tracks the nearest vertices
        int[][] t = new int[n - 1][2]; // Array to store the edges of the minimum spanning tree
        int minCost = 0;

        // Step 1: Find the edge with minimum cost
        int k = -1, l = -1;
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (cost[i][j] < min) {
                    min = cost[i][j];
                    k = i;
                    l = j;
                }
            }
        }

        // Initialize the minimum cost and the first edge of the MST
        minCost += min;
        t[0][0] = k;
        t[0][1] = l;

        // Initialize the near array
        for (int i = 0; i < n; i++) {
            near[i] = (cost[i][l] < cost[i][k]) ? l : k;
        }
        near[k] = near[l] = -1; // Mark these vertices as part of the MST

        // Step 2: Find n - 2 edges to complete the MST
        for (int i = 1; i < n - 1; i++) {
            min = Integer.MAX_VALUE;
            int j = -1;

            // Find the vertex j with the minimum cost to add to the MST
            for (int m = 0; m < n; m++) {
                if (near[m] != -1 && cost[m][near[m]] < min) {
                    min = cost[m][near[m]];
                    j = m;
                }
            }

            // Add the edge to the MST
            t[i][0] = j;
            t[i][1] = near[j];
            minCost += cost[j][near[j]];
            near[j] = -1; // Mark j as included in the MST

            // Update the near array
            for (int m = 0; m < n; m++) {
                if (near[m] != -1 && cost[m][near[m]] > cost[m][j]) {
                    near[m] = j;
                }
            }
        }

        // Print the MST edges
        System.out.println("Edges in the Minimum Spanning Tree:");
        for (int i = 0; i < n - 1; i++) {
            System.out.println("(" + t[i][0] + ", " + t[i][1] + ")");
        }

        return minCost;
    }

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

        // Take the number of vertices as input
        System.out.print("Enter the number of vertices: ");
        int n = sc.nextInt();

        // Create the adjacency matrix (cost) based on user input
        int[][] cost = new int[n][n];
        System.out.println("Enter the adjacency matrix (-1 for no edge):");

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (i == j) {
                    cost[i][j] = Integer.MAX_VALUE; // No self-loops
                } else {
                    System.out.print("Cost of edge between " + i + " and " + j + ": ");
                    int input = sc.nextInt();
                    cost[i][j] = (input == -1) ? Integer.MAX_VALUE : input;
                }
            }
        }

        // Calculate the minimum spanning tree
        int minCost = prim(cost, n);

        // Output the minimum cost of the MST
        System.out.println("Minimum Cost of the MST: " + minCost);
        sc.close();
    }
}

/*
Enter the number of vertices: 4
Enter the adjacency matrix (-1 for no edge):
Cost of edge between 0 and 1: 1
Cost of edge between 0 and 2: 3
Cost of edge between 0 and 3: -1
Cost of edge between 1 and 2: 1
Cost of edge between 1 and 3: 4
Cost of edge between 2 and 3: 2
Edges in the Minimum Spanning Tree:
(0, 1)
(1, 2)
(2, 3)
Minimum Cost of the MST: 4*/




 
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.Arrays;
import java.util.Scanner;

// Job class to hold information about each job.
class Job {
    int id;       // Job ID
    int profit;   // Profit of the job
    int deadline; // Deadline of the job
    
    // Constructor to initialize job details
    public Job(int id, int profit, int deadline) {
        this.id = id;
        this.profit = profit;
        this.deadline = deadline;
    }
}

// Comparator to sort jobs based on profit in descending order
class JobComparator implements java.util.Comparator<Job> {
    @Override
    public int compare(Job job1, Job job2) {
        return job2.profit - job1.profit; // Sorting in descending order of profit
    }
}

public class Main {

    // Function to perform Job Sequencing with Deadlines
    public static void jobSequencing(Job[] jobs, int n) {
        // Sort the jobs based on profit in descending order
        Arrays.sort(jobs, new JobComparator());
        
        // Find the maximum deadline to determine the size of the result array
        int maxDeadline = 0;
        for (int i = 0; i < n; i++) {
            if (jobs[i].deadline > maxDeadline) {
                maxDeadline = jobs[i].deadline;
            }
        }
        
        // Array to store the result (sequenced jobs)
        int[] result = new int[maxDeadline];
        
        // Initialize all slots as empty (-1 means no job is scheduled)
        Arrays.fill(result, -1);
        
        // Variable to track total profit
        int totalProfit = 0;
        
        // Iterate over all jobs
        for (int i = 0; i < n; i++) {
            // Find a free slot for the job (starting from the latest available slot)
            for (int j = jobs[i].deadline - 1; j >= 0; j--) {
                if (result[j] == -1) { // If the slot is free
                    result[j] = jobs[i].id; // Schedule the job
                    totalProfit += jobs[i].profit; // Add profit
                    break;
                }
            }
        }
        
        // Print the scheduled jobs and total profit
        System.out.println("Jobs scheduled in the sequence are:");
        for (int i = 0; i < maxDeadline; i++) {
            if (result[i] != -1) {
                System.out.print("Job " + result[i] + " ");
            }
        }
        System.out.println();
        System.out.println("Total Profit = " + totalProfit);
    }

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

        // Take input for number of jobs
        System.out.print("Enter number of jobs: ");
        int n = scanner.nextInt();

        // Create an array of jobs
        Job[] jobs = new Job[n];

        // Take input for jobs (id, profit, deadline)
        System.out.println("Enter job details (ID Profit Deadline):");
        for (int i = 0; i < n; i++) {
            System.out.print("Job " + (i + 1) + ": ");
            int id = scanner.nextInt();
            int profit = scanner.nextInt();
            int deadline = scanner.nextInt();
            jobs[i] = new Job(id, profit, deadline);
        }

        // Call the job sequencing function
        jobSequencing(jobs, n);

        scanner.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;
}
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.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of keys (n):");
        int n = sc.nextInt();
        double[] p = new double[n+1];
        double[] q = new double[n+1];
        
       System.out.println("Enter probabilities of successful searches for keys (p):");
        for(int i=1;i<=n;i++){
            p[i] = sc.nextDouble();
        }
        
       System.out.println("Enter probabilities of unsuccessful searches (q):");
        for(int i=0;i<=n;i++){
            q[i] = sc.nextDouble();
        }
        obst(p,q,n);
    }
    public static void obst(double[] p,double[] q,int n){
        double[][] w = new double[n+1][n+1];
        double[][] c = new double[n+1][n+1];
        int[][] r = new int[n+1][n+1];
        for(int i=0;i<=n;i++){
            w[i][i] = q[i];
            c[i][i] = 0;
            r[i][i] = 0;
        }
        for(int m = 1;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];
                double mincost = Double.MAX_VALUE;
                int root = -1;
                for(int k=i+1;k<=j;k++){
                    double cost = c[i][k-1]+c[k][j]+w[i][j];
                    if(cost < mincost){
                        mincost = cost;
                        root = k;
                    }
                }
                c[i][j] = mincost;
                r[i][j] = root;
            }
        }
        System.out.println("Cost = "+c[0][n]);
        System.out.println("Weight = "+w[0][n]);
    }
}






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.Scanner;

public class QuickSort {
    
    // Method to swap two elements in an array
    public static void interchange(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
    
    // Partition method to select the pivot and arrange the array
    public static int partition(int[] a, int p, int q) {
        int v = a[p];  // pivot element
        int i = p, j = q + 1;
        
        do {
            // Move i to the right as long as the element is less than the pivot
            do {
                i = i + 1;
            } while (i <= q && a[i] < v);
            
            // Move j to the left as long as the element is greater than the pivot
            do {
                j = j - 1;
            } while (a[j] > v && j >= p);
            
            // If i < j, swap the elements
            if (i < j) {
                interchange(a, i, j);
            }
        } while (i < j);
        
        // Swap the pivot with the element at j
        interchange(a, p, j);
        
        return j;  // Return the index of the pivot element
    }
    
    // QuickSort method to recursively sort the subarrays
    public static void quickSort(int[] a, int p, int q) {
        if (p < q) {
            int j = partition(a, p, q);  // Partition the array
            quickSort(a, p, j - 1);       // Sort the left subarray
            quickSort(a, j + 1, q);       // Sort the right subarray
        }
    }

    // Main method to accept input and run the quickSort
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Input size of the array
        System.out.print("Enter Size: ");
        int n = scanner.nextInt();
        
        int[] a = new int[n];  // Array initialization
        
        // Input array elements
        System.out.println("Enter elements: ");
        for (int i = 0; i < n; i++) {
            a[i] = scanner.nextInt();
        }
        
        // Perform QuickSort
        quickSort(a, 0, n - 1);
        
        // Output the sorted array
        System.out.print("Sorted Array: ");
        for (int i = 0; i < n; i++) {
            System.out.print(a[i] + " ");
        }
        System.out.println();
        
        scanner.close();  // Close the scanner to avoid memory leaks
    }
}




 
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.
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)

if __name__ == "__main__":
    V = int(input("Enter the number of vertices: "))
    E = int(input("Enter the number of edges: "))
    adj = [[] for _ in range(V + 1)]
    print("Enter each edge as 'u v' (space-separated):")
    for _ in range(E):
        u, v = map(int, input().split())
        addEdge(adj, u, v)
    print("Articulation points in the graph:")
    AP(adj, V)
class Job:
    def __init__(self, id, profit, deadline):
        self.id = id
        self.profit = profit
        self.deadline = deadline

def job_sequencing(jobs, n):
    jobs.sort(key=lambda x: x.profit, reverse=True)
    result = [None] * n
    slot = [False] * n
    total_profit = 0

    for job in jobs:
        for j in range(min(n, job.deadline) - 1, -1, -1):
            if not slot[j]:
                result[j] = job.id
                slot[j] = True
                total_profit += job.profit
                break

    print("Job sequence:", result)
    print("Total profit:", total_profit)

if __name__ == "__main__":
    n = int(input("Enter number of jobs: "))
    jobs = []
    for _ in range(n):
        id, profit, deadline = map(int, input("Enter id, profit, deadline: ").split())
        jobs.append(Job(id, profit, deadline))
    
    job_sequencing(jobs, n)
class Item:
    def __init__(self, cost, weight):
        self.cost = cost
        self.weight = weight
        self.ratio = cost / weight

def fractional_knapsack(capacity, items):
    items.sort(key=lambda item: item.ratio, reverse=True)

    total_cost = 0
    for item in items:
        if capacity <= 0:
            break

        if item.weight <= capacity:
            total_cost += item.cost
            capacity -= item.weight
        else:
            total_cost += item.cost * (capacity / item.weight)
            capacity = 0

    return total_cost

if __name__ == "__main__":
    n = int(input("Enter the number of items: "))
    capacity = int(input("Enter the capacity of the knapsack: "))
    
    items = []
    for _ in range(n):
        cost, weight = map(int, input("Enter cost and weight of item (cost weight): ").split())
        items.append(Item(cost, weight))
    
    result = fractional_knapsack(capacity, items)
    print(f"The maximum cost that can be obtained: {result}")
import heapq

def dijkstra(V, edges, start):
    adj = [[] for _ in range(V)]
    for u, v, wt in edges:
        adj[u].append((v, wt))
        adj[v].append((u, wt))

    pq = []
    distances = [float('inf')] * V
    visited = [False] * V

    distances[start] = 0
    heapq.heappush(pq, (0, start))

    while pq:
        current_distance, u = heapq.heappop(pq)
        if visited[u]:
            continue
        visited[u] = True

        for v, weight in adj[u]:
            if not visited[v] and current_distance + weight < distances[v]:
                distances[v] = current_distance + weight
                heapq.heappush(pq, (distances[v], v))

    return distances

if __name__ == "__main__":
    V = int(input("Enter the number of vertices: "))
    E = int(input("Enter the number of edges: "))
    edges = []

    print("Enter each edge as 'u v weight':")
    for _ in range(E):
        u, v, wt = map(int, input().split())
        edges.append((u, v, wt))

    start = int(input("Enter the starting vertex: "))
    result = dijkstra(V, edges, start)
    print("The shortest distances from the starting vertex are:")
    for i, d in enumerate(result):
        print(f"Vertex {i}: {d}")
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

if __name__ == "__main__":
    V = int(input("Enter the number of vertices: "))
    E = int(input("Enter the number of edges: "))
    edges = []

    print("Enter each edge as 'u v weight':")
    for _ in range(E):
        u, v, wt = map(int, input().split())
        edges.append([u, v, wt])

    result = tree(V, E, edges)
    print("The total weight of the Minimum Spanning Tree is:", result)
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
# Sample data
data = {
 'Feature1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
 'Feature2': [5, 10, 15, 20, 25, 30, 35, 40, 45, 50],
 'Target': [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
}
df = pd.DataFrame(data)
# Split data into features and target
X = df[['Feature1', 'Feature2']]
y = df['Target']
# Split dataset
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Initialize and fit model
rf = RandomForestClassifier(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)
# Make predictions
y_pred = rf.predict(X_test)
# Evaluate model
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:.2f}')
print('Confusion Matrix:')
print(conf_matrix)
print('Classification Report:')
print(class_report)
Partition(a, m, 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


Interchange(a, i, j)
    temp = a[i]
    a[i] = a[j]
    a[j] = temp


QuickSort(a, p, q)
    if p < q then
        j = Partition(a, p, q + 1)
        QuickSort(a, p, j - 1)
        QuickSort(a, j + 1, q)
MERGE-SORT(A, low, high)
If low < high
    mid = (low + high) / 2
    MERGE-SORT(A, low, mid)       // Sort first half
    MERGE-SORT(A, mid + 1, high)  // Sort second half
    MERGE(A, low, mid, high)      // Merge the sorted halves










MERGE(low, mid, high)
{
    h = low        // Pointer for the first subarray (a[low : mid])
    i = low        // Pointer for the auxiliary array (b[])
    j = mid + 1    // Pointer for the second subarray (a[mid + 1 : high])

    // Merge the two sorted subarrays into b[]
    while (h <= mid) and (j <= high) do
    {
        if (a[h] <= a[j]) then
        {
            b[i] = a[h]
            h = h + 1
        }
        else
        {
            b[i] = a[j]
            j = j + 1
        }
        i = i + 1
    }

    // Copy remaining elements from the first subarray, if any
    if (h > mid) then
        for k = j to high do
        {
            b[i] = a[k]
            i = i + 1
        }
    else
        for k = h to mid do
        {
            b[i] = a[k]
            i = i + 1
        }

    // Copy merged elements back to the original array
    for k = low to high do
        a[k] = b[k]
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://fh-kit.com/buttons/v2/?color=8B4514" type="text/css" media="screen" />
<script type="text/javascript">
  jQuery(document).ready(function($){
    fhScript= document.createElement('script');
    fhScript.src = "https://fareharbor.com/embeds/api/v1/?autolightframe=yes";
    $('body').append(fhScript);
    $('body').append('<a href="https://fareharbor.com/embeds/book/cuevalafaraona/?full-items=yes" style="font-weight: bold !important; font-family:Montserrat, sans-serif !important; box-shadow:none !important; padding: .2em 2em !important; "class="fh-hide--mobile fh-button-true-flat-color fh-shape--round fh-fixed--bottom fh-icon--cal">Reserva</a>');
    $('body').append('<a href="https://fareharbor.com/embeds/book/cuevalafaraona/?full-items=yes" style="font-size: 1.2em !important; font-weight: bold !important; font-family:Montserrat, sans-serif !important; box-shadow:none !important;" class="fh-hide--desktop fh-size--small fh-button-true-flat-color fh-shape--round fh-fixed--bottom fh-icon--cal">Reserva</a>');
  });
</script>
#include <stdio.h>

void printSolutionVector(int* x, int k) {
    printf("Solution Vector: ");
    for (int i = 0; i <= k; i++) {
        printf("%d ", x[i]);
    }
    printf("\n");
}

void sumOfSub(int* weights, int* x, int s, int k, int r, int m, int n) {
    // Include the current element
    x[k] = 1;
    if (s + weights[k] == m) {
        // If the sum matches the target, print the solution vector
        printSolutionVector(x, k);
    } 
    // Check if including the current element and the next one keeps the sum within bounds
    else if (k + 1 < n && s + weights[k] + weights[k + 1] <= m) {
        sumOfSub(weights, x, s + weights[k], k + 1, r - weights[k], m, n);
    }

    // Exclude the current element and check if further exploration is valid
    if ((s + r - weights[k] >= m) && (k + 1 < n && s + weights[k + 1] <= m)) {
        x[k] = 0;
        sumOfSub(weights, x, s, k + 1, r - weights[k], m, n);
    }
}

int main() {
    int n;
    printf("Enter the number of elements in the set: ");
    scanf("%d", &n);

    int weights[n];
    printf("Enter the elements of the set (in non-decreasing order): ");
    for (int i = 0; i < n; i++) {
        scanf("%d", &weights[i]);
    }

    int m;
    printf("Enter the target sum (m): ");
    scanf("%d", &m);

    int x[n];
    int r = 0;
    for (int i = 0; i < n; i++) {
        r += weights[i];
    }

    printf("Solution Vectors with sum %d:\n", m);
    sumOfSub(weights, x, 0, 0, r, m, n);

    return 0;
}
import java.util.Scanner;

public class MergeSort {

    // Global array `a` and auxiliary array `b`
    private static int[] a;
    private static int[] b;

    // MergeSort function
    public static void mergeSort(int low, int high) {
        if (low < high) {
            // Divide step: find the midpoint
            int mid = (low + high) / 2;

            // Solve subproblems by recursively calling mergeSort on each half
            mergeSort(low, mid);
            mergeSort(mid + 1, high);

            // Combine step: merge the two halves
            merge(low, mid, high);
        }
    }

    // Merge function to combine two sorted subarrays a[low:mid] and a[mid+1:high]
    public static void merge(int low, int mid, int high) {
        int h = low;  // Start index for first subarray
        int i = low;  // Index to place merged elements in the auxiliary array
        int j = mid + 1;  // Start index for second subarray

        // Copy the elements to the auxiliary array `b`
        b = new int[a.length];
        
        // Merge the two subarrays
        while (h <= mid && j <= high) {
            if (a[h] <= a[j]) {
                b[i] = a[h];
                h++;
            } else {
                b[i] = a[j];
                j++;
            }
            i++;
        }

        // Copy remaining elements of the first subarray (if any)
        while (h <= mid) {
            b[i] = a[h];
            h++;
            i++;
        }

        // Copy remaining elements of the second subarray (if any)
        while (j <= high) {
            b[i] = a[j];
            j++;
            i++;
        }

        // Copy the sorted elements back to the original array
        for (int k = low; k <= high; k++) {
            a[k] = b[k];
        }
    }

    // Helper method to print the array
    public static void printArray() {
        for (int element : a) {
            System.out.print(element + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        // Create a scanner object for taking input from the user
        Scanner scanner = new Scanner(System.in);

        // Ask the user for the size of the array
        System.out.println("Enter the number of elements in the array:");
        int n = scanner.nextInt();

        // Initialize the global array `a` with the user-provided size
        a = new int[n];

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

        // Display the original array
        System.out.println("Original array:");
        printArray();

        // Sort the array using mergeSort
        mergeSort(0, a.length - 1);

        // Display the sorted array
        System.out.println("Sorted array:");
        printArray();

        // Close the scanner
        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;  
}
 
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 
import java.util.Scanner;

public class NQueens {

    static void printSolution(int[][] board, int n) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print((board[i][j] == 1 ? "Q " : ". "));
            }
            System.out.println();
        }
        System.out.println();
    }

    static boolean isSafe(int[][] board, int row, int col, int n) {
        for (int i = 0; i < row; i++) {
            if (board[i][col] == 1) return false;
        }
        for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
            if (board[i][j] == 1) return false;
        }
        for (int i = row, j = col; i >= 0 && j < n; i--, j++) {
            if (board[i][j] == 1) return false;
        }
        return true;
    }

    static boolean solveNQueens(int[][] board, int row, int n) {
        if (row == n) {
            printSolution(board, n);
            return true;
        }

        boolean result = false;
        for (int col = 0; col < n; col++) {
            if (isSafe(board, row, col, n)) {
                board[row][col] = 1;
                result = solveNQueens(board, row + 1, n) || result;
                board[row][col] = 0;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the value of N: ");
        int n = sc.nextInt();

        int[][] board = new int[n][n];
        System.out.println("Solutions to the " + n + "-Queens problem:");
        if (!solveNQueens(board, 0, n)) {
            System.out.println("No solution exists.");
        }
    }
}
import pandas as pd

# Sample DataFrame
data = {
    'Name': ['Alice', 'Bob', None, 'David'],
    'Age': [24, None, 32, 28],
    'City': ['New York', 'Los Angeles', 'Chicago', None]
}
df = pd.DataFrame(data)

# Checking for missing values
print(df.isnull())  # True where there are missing values
print(df.isnull().sum())  # Total number of missing values per column

# Drop rows with any missing values
df_dropped_rows = df.dropna()
print("Rows with missing values dropped:\n", df_dropped_rows)

# Drop columns with any missing values
df_dropped_cols = df.dropna(axis=1)
print("Columns with missing values dropped:\n", df_dropped_cols)

# Fill with a specific value (e.g., 0)
df_filled_zeros = df.fillna(0)
print("Missing values filled with 0:\n", df_filled_zeros)

# Fill with the mean (useful for numeric data)
df['Age'] = df['Age'].fillna(df['Age'].mean())
print("Age column with missing values filled by mean:\n", df)

# Fill with the median
df['Age'] = df['Age'].fillna(df['Age'].median())
print("Age column with missing values filled by median:\n", df)

# Fill with the mode (useful for categorical data)
df['City'] = df['City'].fillna(df['City'].mode()[0])
print("City column with missing values filled by mode:\n", df)

# Forward fill (fills using the last valid observation)
df_ffill = df.ffill()
print("Forward fill (missing values filled using last valid observation):\n", df_ffill)

# Backward fill (fills using the next valid observation)
df_bfill = df.bfill()
print("Backward fill (missing values filled using next valid observation):\n", df_bfill)
import pandas as pd
import matplotlib.pyplot as plt

# Create the DataFrame
data = {
    'Feature1': [10, 20, 30, 40, 50],
    'Feature2': [100, 200, 300, 400, 500]
}
df = pd.DataFrame(data)

# Calculate the sum of each feature for pie chart visualization
sizes = [df['Feature1'].sum(), df['Feature2'].sum()]

# Labels for the pie chart
labels = ['Feature1', 'Feature2']

# Plotting the Pie Chart
plt.pie(sizes, labels=labels)
plt.title("Proportion of Feature1 and Feature2")
plt.show()
import pandas as pd

# Step 1.1: Convert the dictionary to a DataFrame
data = {
    'Category': ['A', 'B', 'A', 'C', 'B']
}
df = pd.DataFrame(data)

# Step 1.2: Apply One-Hot Encoding
df_encoded = pd.get_dummies(df, columns=['Category'])

# Step 1.3: Print the DataFrame with One-Hot Encoding
print(df_encoded)
import pandas as pd
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# Step 1.1: Convert dictionary to DataFrame
data = {
    'Feature1': [1, 2, np.nan, 4, 5],
    'Feature2': [5, np.nan, np.nan, 8, 9]
}

df = pd.DataFrame(data)


df['Feature1'].fillna(df['Feature1'].mean(), inplace=True)

# Step 1.4: Fill missing values in 'Feature2' with median
df['Feature2'].fillna(df['Feature2'].median(), inplace=True)





df['Target'] = [0, 1, 0, 1, 0]  # Example target values for classification


X = df.drop(columns=['Target'])  # Features (without 'Target')
y = df['Target']  # Target variable

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Step 3: Load Decision Tree Classifier
clf = DecisionTreeClassifier(random_state=42)

# Step 4: Train the model
clf.fit(X_train, y_train)

# Step 5: Make predictions
y_pred = clf.predict(X_test)

# Step 6: Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
print(f"\nDecision Tree Classifier Accuracy: {accuracy * 100:.2f}%")

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
 
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score,confusion_matrix
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
 
# Load the Iris dataset
iris = pd.read_csv('/content/iris.csv')
X = iris.drop(columns=["Species"]) # Features
y = iris["Species"]  # Labels
 
 
 
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
 
# Train the SVC model with a linear kernel
model = SVC(kernel='linear', random_state=42)
model.fit(X_train, y_train)
 
# Make predictions
y_pred = model.predict(X_test)
 
# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
print(f"Model Accuracy: {accuracy:.2f}")
 
conf_matrix = confusion_matrix(y_test, y_pred)
print('Confusion Matrix:')
print(conf_matrix)
import java.util.Scanner;

public class GFG 
{
    static int optCost(int freq[], int i, int j)
    {
       if (j < i)
         return 0;
       if (j == i)
         return freq[i];
      
       int fsum = sum(freq, i, j);
       int min = Integer.MAX_VALUE;
      
       for (int r = i; r <= j; ++r)
       {
           int cost = optCost(freq, i, r-1) + 
                          optCost(freq, r+1, j);
           if (cost < min)
              min = cost;
       }
       return min + fsum;
    }

    static int optimalSearchTree(int keys[], int freq[], int n)
    {
         return optCost(freq, 0, n-1);
    }

    static int sum(int freq[], int i, int j)
    {
        int s = 0;
        for (int k = i; k <= j; k++)
           s += freq[k];
        return s;
    }

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

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

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

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

        // Calculating and printing the cost of Optimal BST
        System.out.println("Cost of Optimal BST is " +
                           optimalSearchTree(keys, freq, n));
    }
}
import java.util.*;

public class Knapsack {
    public static double greedyKnapSack(ItemValue[] arr, int capacity) {
        // Sort items based on their profit-to-weight ratio in descending order
        Arrays.sort(arr, new Comparator<ItemValue>() {
            public int compare(ItemValue item1, ItemValue item2) {
                double cpr1 = (double) item1.profit / item1.weight;
                double cpr2 = (double) item2.profit / item2.weight;
                if (cpr1 < cpr2)
                    return 1;
                else
                    return -1;
            }
        });

        double total = 0;

        for (ItemValue i : arr) {
            if ((capacity - i.weight) >= 0) {
                // If the item can be fully taken
                capacity -= i.weight;
                total += i.profit;
            } else {
                // Take the fraction of the item
                double fract = (double) capacity / (double) i.weight;
                total += fract * (i.profit);
                capacity = 0;
                break;
            }
        }

        return total;
    }

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

        System.out.println("Enter the number of items: ");
        int n = sc.nextInt();
        ItemValue[] arr = new ItemValue[n];

        System.out.println("Enter weight, profit of each item: ");
        for (int i = 0; i < n; i++) {
            arr[i] = new ItemValue(sc.nextInt(), sc.nextInt());
        }

        System.out.println("Enter capacity: ");
        int m = sc.nextInt();

        double pro = greedyKnapSack(arr, m);
        System.out.println("Maximum profit: " + pro);
    }
}

class ItemValue {
    public int weight;
    public int profit;

    public ItemValue(int weight, int profit) {
        this.weight = weight;
        this.profit = profit;
    }
}



Procedure GREEDY_KNAPSACK (P, W, M, X, n):

 and  contain the profits and weights respectively of the  objects arranged so that .

 is the knapsack size, and  is the solution vector.


real P(1:n), W(1:n), X(1:n), M, cu;  
integer i, n;  

X ← 0  // Initialize solution to zero  
cu ← M  // cu = remaining knapsack capacity  

for i ← 1 to n do  
    if W(i) > cu then exit endif  
    X(i) ← 1  
    cu ← cu - W(i)  
repeat  

if i ≤ n then X(i) ← cu/W(i) endif  

end GREEDY_KNAPSACK
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of keys (n):");
        int n = sc.nextInt();
        double[] p = new double[n+1];
        double[] q = new double[n+1];
        
       System.out.println("Enter probabilities of successful searches for keys (p):");
        for(int i=1;i<=n;i++){
            p[i] = sc.nextDouble();
        }
        
       System.out.println("Enter probabilities of unsuccessful searches (q):");
        for(int i=0;i<=n;i++){
            q[i] = sc.nextDouble();
        }
        obst(p,q,n);
    }
    public static void obst(double[] p,double[] q,int n){
        double[][] w = new double[n+1][n+1];
        double[][] c = new double[n+1][n+1];
        int[][] r = new int[n+1][n+1];
        for(int i=0;i<=n;i++){
            w[i][i] = q[i];
            c[i][i] = 0;
            r[i][i] = 0;
        }
        for(int m = 1;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];
                double mincost = Double.MAX_VALUE;
                int root = -1;
                for(int k=i+1;k<=j;k++){
                    double cost = c[i][k-1]+c[k][j]+w[i][j];
                    if(cost < mincost){
                        mincost = cost;
                        root = k;
                    }
                }
                c[i][j] = mincost;
                r[i][j] = root;
            }
        }
        System.out.println("Cost = "+c[0][n]);
        System.out.println("Weight = "+w[0][n]);
    }
}
# Import necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

# Sample Dataset (replace this with your actual dataset)
# Let's assume we have a dataset with features: 'height', 'weight', and 'experience'
data = {
    'height': [150, 160, 170, 180, 190],
    'weight': [50, 60, 70, 80, 90],
    'experience': [2, 3, 4, 5, 6],
    'age': [25, 28, 30, 35, 40]  # This is the target variable
}

# Create a DataFrame
df = pd.DataFrame(data)



# Step 2: Data Preprocessing
# Define features (X) and target (y)
X = df[['height', 'weight', 'experience']]  # Independent variables
y = df['age']  # Dependent variable (age)

# Step 3: Train-Test Split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Step 4: Train the Regression Model (Linear Regression)
model = LinearRegression()
model.fit(X_train, y_train)

# Step 5: Make Predictions
y_pred = model.predict(X_test)

# Step 6: Model Evaluation
# Calculate Mean Squared Error (MSE)
mse = mean_squared_error(y_test, y_pred)
print(f"Mean Squared Error: {mse}")

# Calculate R-squared (R²) value
r2 = r2_score(y_test, y_pred)
print(f"R-squared value: {r2}")

# Import necessary libraries
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score, classification_report

# Step 1: Load the dataset
df = pd.read_csv('Iris.csv')  # Replace with the correct path if needed

# Step 1.1: Data Exploration
print("Dataset Preview:")
print(df.head())

# Data Overview
print("\nDataset Information:")
print(df.info())

# Step 1.2: Verify Missing Values
print("\nMissing Values:")
print(df.isnull().sum())

# Step 1.3: Verify Duplicates
print("\nDuplicate Rows:")
print(df.duplicated().sum())

# Step 1.4: Detect and Remove Outliers using IQR method
# IQR method to detect outliers
Q1 = df.select_dtypes(include=[np.number]).quantile(0.25)
Q3 = df.select_dtypes(include=[np.number]).quantile(0.75)
IQR = Q3 - Q1

# Outliers are those outside the range (Q1 - 1.5*IQR) and (Q3 + 1.5*IQR)
outliers_iqr = ((df.select_dtypes(include=[np.number]) < (Q1 - 1.5 * IQR)) | 
                (df.select_dtypes(include=[np.number]) > (Q3 + 1.5 * IQR))).any(axis=1)

# Removing outliers
df_no_outliers_iqr = df[~outliers_iqr]
print(f"\nShape after removing outliers: {df_no_outliers_iqr.shape}")

# Step 1.5: Split Dataset and Perform Naive Bayes Classification
# Define features (X) and target (y)
X = df_no_outliers_iqr.drop(['Id', 'Species'], axis=1)  # Drop 'Id' and 'Species'
y = df_no_outliers_iqr['Species']

# Split the data into training and testing sets (70% training, 30% testing)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Initialize Naive Bayes classifier (GaussianNB for continuous data)
nb_classifier = GaussianNB()

# Train the model
nb_classifier.fit(X_train, y_train)

# Make predictions on the test set
y_pred = nb_classifier.predict(X_test)

# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
print(f"\nAccuracy of the Naive Bayes model: {accuracy * 100:.2f}%")
print("\nClassification Report:")
print(classification_report(y_test, y_pred))

# Optional: Visualize the distribution of data and outliers
plt.figure(figsize=(10, 6))
sns.boxplot(data=df_no_outliers_iqr.drop(['Id', 'Species'], axis=1))
plt.title('Boxplot to Visualize Outliers After Removal')
plt.show()
import React, { useContext } from "react";
import Link from "next/link";
import { ChevronRightIcon } from "@heroicons/react/24/outline";
import { AuthContext } from "@/context/AuthContext";
import { CurrentObjectContext } from "@/context/CurrentObjectContext";

export const getPreviousPaths = (index: number, pathname: string): string => {
  return index === 0
    ? "/dashboard"
    : pathname
        .split("/")
        .filter((_, idx) => idx <= index)
        .join("/");
};

const hasDatePattern = (str: string): boolean => {
  if (typeof str !== "string" || str.length < 11) return false;
  const pattern = /\s\d{4}\s\d{2}\s\d{2}$/; // " #### ## ##" # = digit
  return pattern.test(str);
};

const removeDatePattern = (str: string): string => {
  if (hasDatePattern(str)) {
    return str.slice(0, -11);
  }
  return str;
};

export default function BreadCrumbs({
  pathname,
  breadcrumbs,
}: {
  pathname: string;
  breadcrumbs: string[];
}) {
  const { isSuperAdmin } = useContext(AuthContext);
  const { object } = useContext(CurrentObjectContext);

  const handleIdNumber = (
    pathname: string,
    id: string | number
  ): string | number => {
    const split = pathname.split("/").filter((str) => str !== "");

    // if date pattern exists at the end of the string, remove it
    if (typeof id === "string") {
      id = removeDatePattern(id);
    }
    if (
      split.length === 3 &&
      (split[1] === "organizations" ||
        split[1] === "my-competitions" ||
        split[1] === "competitions")
    ) {
      return object.hasOwnProperty("name") && object.name;
    }
    if (object && split.length === 3 && split[1] === "users") {
      return object.first_name + " " + object.last_name || id;
    }
    return id;
  };

  const handleIdOnThird = (
    pathname: string,
    id: string | number
  ): string | number => {
    const split = pathname.split("/").filter((str) => str !== "");
    // if date pattern exists at the end of the string, remove it
    if (typeof id === "string") {
      id = removeDatePattern(id);
    }

    if (
      split.length === 4 &&
      (split[1] === "organizations" ||
        split[1] === "my-competitions" ||
        split[1] === "competitions")
    ) {
      return object.hasOwnProperty("name") && object.name;
    }
    if (object && split.length === 3 && split[1] === "users") {
      return object.first_name + " " + object.last_name || id;
    }
    return id;
  };

  return (
    <nav className="flex p-4" aria-label="Breadcrumb">
      <ol role="list" className="flex items-center space-x-4">
        {pathname === "/dashboard/" ? (
          <li key={1} className="flex items-center">
            <p className="text-xs font-medium text-gray-400">Dashboard</p>
          </li>
        ) : breadcrumbs.length > 1 ? (
          breadcrumbs.map((crumb, index) =>
            index < breadcrumbs.length - 1 ? (
              <li key={crumb} className="flex items-center">
                {crumb === "Organizations" ? (
                  <Link
                    className="text-xs font-medium text-gray-400 hover:text-gray-200"
                    href={getPreviousPaths(index + 1, pathname)}
                  >
                    {crumb === "Organizations" ? "Clubs" : crumb}
                  </Link>
                ) : crumb === "Organization" && !isSuperAdmin ? (
                  <li
                    key={crumb}
                    className="flex items-center text-xs font-medium text-gray-400"
                  >
                    {crumb}
                  </li>
                ) : index === breadcrumbs.length - 2 &&
                  breadcrumbs.length > 3 ? (
                  <Link
                    key={crumb}
                    className={`flex items-center text-xs font-medium text-gray-400 hover:text-gray-200 ${
                      pathname.split("/").filter((p) => p !== "")[1] !== "users"
                        ? "capitalize"
                        : ""
                    }`}
                    href={pathname.split("/").splice(0, 4).join("/")}
                  >
                    {handleIdOnThird(pathname, crumb)}
                  </Link>
                ) : (
                  <Link
                    className="text-xs font-medium text-gray-400 hover:text-gray-200"
                    href={getPreviousPaths(index + 1, pathname)}
                  >
                    {crumb}
                  </Link>
                )}
                <ChevronRightIcon
                  className="w-4 ml-4 text-gray-500"
                  aria-hidden="true"
                />
              </li>
            ) : (
              <Link
                key={crumb}
                className={`flex items-center text-xs font-medium text-gray-400 hover:text-gray-200 ${
                  pathname.split("/").filter((p) => p !== "")[1] !== "users"
                    ? "capitalize"
                    : ""
                }`}
                href={pathname}
              >
                {handleIdNumber(
                  pathname,
                  crumb === "Organizations" ? "Clubs" : crumb
                )}
              </Link>
            )
          )
        ) : (
          <li
            key={1}
            className="flex items-center text-xs font-medium text-gray-400"
          >
            Dashboard
          </li>
        )}
      </ol>
    </nav>
  );
}
# Import necessary libraries
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

# Step 1: Create a dataset (sample data for house rentals)
data = {
    'Size (sq ft)': [850, 900, 1200, 1500, 1800, 2000, 2300, 2500, 2700, 3000],
    'Bedrooms': [2, 2, 3, 3, 4, 4, 5, 5, 5, 6],
    'Age (years)': [5, 10, 3, 20, 15, 10, 8, 12, 30, 20],
    'Location Score': [8, 7, 9, 6, 8, 8, 9, 9, 7, 6],
    'Rental Price (USD)': [1500, 1700, 2500, 3000, 3500, 3700, 4200, 4500, 4700, 5000]
}

df = pd.DataFrame(data)

# Step 2: Split the data into features (X) and target (y)
X = df[['Size (sq ft)', 'Bedrooms', 'Age (years)', 'Location Score']]
y = df['Rental Price (USD)']

# Step 3: Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Step 4: Train the Multiple Linear Regression model
model = LinearRegression()
model.fit(X_train, y_train)

# Step 5: Make predictions on the test set
y_pred = model.predict(X_test)

# Step 6: Evaluate the model
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)

print("Model Evaluation:")
print(f"Mean Squared Error (MSE): {mse:.2f}")
print(f"R² Score: {r2:.2f}")
# Import necessary libraries
import pandas as pd
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer
import matplotlib.pyplot as plt

# Step 1: Create the DataFrame
data = {
    'name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Frank', 'Grace', 'Hannah', 'Ian', 'Jane'],
    'score': [85, 92, 88, 74, 95, 67, 78, 81, 89, 90],
    'sport': ['Basketball', 'Soccer', 'Tennis', 'Cricket', 'Baseball', 'Swimming', 'Soccer', 'Basketball', 'Tennis', 'Cricket'],
    'sex': ['F', 'M', 'M', 'M', 'F', 'M', 'F', 'F', 'M', 'F']
}

df = pd.DataFrame(data)
print("Original DataFrame:\n", df)

# Step 2: Add extra columns (gender and age)
df['gender'] = df['sex'].map({'F': 'Female', 'M': 'Male'})  # Map 'F' to 'Female' and 'M' to 'Male'
df['age'] = [20, 22, 19, 21, 23, 18, 22, 20, 24, 21]  # Adding age column
print("\nDataFrame after adding gender and age columns:\n", df)

# Step 3: Create custom index
df.index = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]
print("\nDataFrame with custom index:\n", df)

# Step 4: Apply Label Encoding on 'gender' column
label_encoder = LabelEncoder()
df['gender_encoded'] = label_encoder.fit_transform(df['gender'])
print("\nDataFrame after Label Encoding:\n", df)

# Step 5: Apply One Hot Encoding using OneHotEncoder on 'sport' column
one_hot_encoder = OneHotEncoder(sparse_output=False)  # Use sparse=False to get a dense array
sport_encoded = one_hot_encoder.fit_transform(df[['sport']])  # Fit and transform 'sport' column

# Create a DataFrame for the encoded data
sport_encoded_df = pd.DataFrame(sport_encoded, columns=one_hot_encoder.get_feature_names_out(['sport']), index=df.index)

# Combine with the original DataFrame
df = pd.concat([df, sport_encoded_df], axis=1)
print("\nDataFrame after One Hot Encoding using OneHotEncoder:\n", df)

# Step 6: Bar Plot for Categorical Data
# Count the occurrences of each sport
sport_counts = df['sport'].value_counts()

# Plot the bar chart
plt.figure(figsize=(8, 6))
sport_counts.plot(kind='bar', color='skyblue')
plt.title('Frequency of Sports Participation')
plt.xlabel('Sport')
plt.ylabel('Frequency')


plt.show()
star

Mon Nov 18 2024 17:46:48 GMT+0000 (Coordinated Universal Time)

@lord

star

Mon Nov 18 2024 17:38:48 GMT+0000 (Coordinated Universal Time)

@pk20

star

Mon Nov 18 2024 17:34:22 GMT+0000 (Coordinated Universal Time)

@badram123

star

Mon Nov 18 2024 17:32:37 GMT+0000 (Coordinated Universal Time)

@lord

star

Mon Nov 18 2024 17:32:13 GMT+0000 (Coordinated Universal Time)

@hi123

star

Mon Nov 18 2024 17:31:15 GMT+0000 (Coordinated Universal Time)

@hi123

star

Mon Nov 18 2024 17:28:49 GMT+0000 (Coordinated Universal Time)

@lord

star

Mon Nov 18 2024 17:28:37 GMT+0000 (Coordinated Universal Time)

@hi123

star

Mon Nov 18 2024 17:25:43 GMT+0000 (Coordinated Universal Time)

@hi123

star

Mon Nov 18 2024 17:24:39 GMT+0000 (Coordinated Universal Time)

@hi123

star

Mon Nov 18 2024 17:23:21 GMT+0000 (Coordinated Universal Time)

@hi123

star

Mon Nov 18 2024 16:02:00 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 15:59:00 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 15:52:32 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 15:48:11 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 15:41:11 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 15:25:33 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 15:17:34 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 15:14:57 GMT+0000 (Coordinated Universal Time) http://localhost:3000/api

@asadiftekhar10

star

Mon Nov 18 2024 14:14:46 GMT+0000 (Coordinated Universal Time)

@CarlosR

star

Mon Nov 18 2024 14:01:12 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 13:59:25 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 13:56:17 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 13:55:27 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 13:53:23 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 13:44:36 GMT+0000 (Coordinated Universal Time)

@badram123

star

Mon Nov 18 2024 13:40:02 GMT+0000 (Coordinated Universal Time)

@badram123

star

Mon Nov 18 2024 13:37:20 GMT+0000 (Coordinated Universal Time)

@badram123

star

Mon Nov 18 2024 13:22:53 GMT+0000 (Coordinated Universal Time)

@badram123

star

Mon Nov 18 2024 13:09:10 GMT+0000 (Coordinated Universal Time)

@badram123

star

Mon Nov 18 2024 13:00:55 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

Mon Nov 18 2024 13:00:20 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 12:51:23 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 12:38:24 GMT+0000 (Coordinated Universal Time)

@Shira

star

Mon Nov 18 2024 12:27:30 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 12:26:57 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 12:15:59 GMT+0000 (Coordinated Universal Time)

@badram123

star

Mon Nov 18 2024 12:13:41 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 12:02:44 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 11:55:56 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 11:51:25 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 11:47:55 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 11:46:55 GMT+0000 (Coordinated Universal Time)

@badram123

star

Mon Nov 18 2024 11:42:57 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 11:37:37 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 11:32:31 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 11:29:52 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 11:18:31 GMT+0000 (Coordinated Universal Time)

@nick

star

Mon Nov 18 2024 10:35:24 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 10:27:32 GMT+0000 (Coordinated Universal Time)

@wtlab

Save snippets that work with our extensions

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