// BFS DFS ::
#include <bits/stdc++.h>
using namespace std;
class Edge{
public:
int src;
int dest;
};
class Graph
{
public:
vector<vector<int>> adjList;
Graph(vector<Edge> &edges, int v)
{
adjList.resize(v);
for(auto &edge: edges)
{
adjList[edge.src].push_back(edge.dest);
adjList[edge.dest].push_back(edge.src);
}
}
};
void recursiveBFS(Graph &graph, queue<int> &q, vector<bool> &discovered)
{
if(q.empty())
{
return;
}
int v = q.front();
q.pop();
cout<<v<<" ";
for(int u: graph.adjList[v])
{
if(!discovered[u])
{
discovered[u] = true;
q.push(u);
}
}
recursiveBFS(graph, q, discovered);
}
void DFS(Graph &graph, int v, vector<bool> &discovered)
{
discovered[v] = true;
cout<<v<<" ";
for(int u: graph.adjList[v])
{
if(!discovered[u])
{
DFS(graph, u, discovered);
}
}
}
int main()
{
vector<Edge> edge;
int v,e;
int source;
int destination;
cout<<"Enter the number of vertices and edges in graph : ";
while(true)
{
if(cin>>v>>e)
{
break;
}
cin.clear();
cin.ignore(1000, '\n');
cout<<"Enter again!"<<endl;
}
cout<<"Enter the source and destination of the edges : "<<endl;
for(int i=0 ; i<e ; i++)
{
if(cin>>source>>destination && source<v+1 && destination<v+1)
{
// if(source<v && destination<v)
// {
edge.push_back({source,destination});
// break;
}
else{
cin.clear();
cin.ignore(1000, '\n');
cout<<"This vertex not present !";
i--;
}
// }
}
Graph graph(edge,v+1);
vector<bool> discovered1(v+1,false);
vector<bool> discovered2(v+1,false);
queue<int> q;
int stratnode;
cout<<"Enter the starting node : ";
cin>>stratnode;
q.push(stratnode);
discovered1[stratnode] = true;
cout<<"BFS : "<<endl;
recursiveBFS(graph,q,discovered1);
cout<<endl;
cout<<"DFS : "<<endl;
if(discovered2[stratnode] == false){
DFS(graph, stratnode, discovered2);}
}
// N QUEEN ::
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isSafe1(int row, int col, vector < string > board, int n) {
// check upper element
int duprow = row;
int dupcol = col;
while (row >= 0 && col >= 0) {
if (board[row][col] == 'Q')
return false;
row--;
col--;
}
col = dupcol;
row = duprow;
while (col >= 0) {
if (board[row][col] == 'Q')
return false;
col--;
}
row = duprow;
col = dupcol;
while (row < n && col >= 0) {
if (board[row][col] == 'Q')
return false;
row++;
col--;
}
return true;
}
public:
void solve(int col, vector < string > & board, vector < vector < string >> & ans, int n) {
if (col == n) {
ans.push_back(board);
return;
}
for (int row = 0; row < n; row++) {
if (isSafe1(row, col, board, n)) {
board[row][col] = 'Q';
solve(col + 1, board, ans, n);
board[row][col] = '.';
}
}
}
public:
vector < vector < string >> solveNQueens(int n) {
vector < vector < string >> ans;
vector < string > board(n);
string s(n, '.');
for (int i = 0; i < n; i++) {
board[i] = s;
}
solve(0, board, ans, n);
return ans;
}
};
int main() {
int n = 4; // we are taking 4*4 grid and 4 queens
Solution obj;
vector < vector < string >> ans = obj.solveNQueens(n);
for (int i = 0; i < ans.size(); i++) {
cout << "Arrangement " << i + 1 << "\n";
for (int j = 0; j < ans[0].size(); j++) {
cout << ans[i][j];
cout << endl;
}
cout << endl;
}
return 0;
}
// A* ::
#include<iostream>
#include<cmath>
#include<limits.h>
using namespace std;
//A* alogrithm to solve 8 puzzle problem
int g = 0;
void Print(int puzzle[]){
for(int i = 0; i < 9; i++){
if(i % 3 == 0) cout << '\n';
if(puzzle[i] == -1) cout << "_ ";
else cout << puzzle[i] << " ";
}
cout << "\n\n";
}
void moveLeft(int start[], int position){
swap(start[position], start[position - 1]);
}
void moveRight(int start[], int position){
swap(start[position], start[position + 1]);
}
void moveUp(int start[], int position){
swap(start[position], start[position - 3]);
}
void moveDown(int start[], int position){
swap(start[position], start[position + 3]);
}
void Copy(int temp[], int real[]){
for(int i = 0; i < 9; i++) temp[i] = real[i];
}
/*
For every number find difference in position in goal state and inital state
Difference in vertical + difference in horizontal
*/
int heuristic(int start[], int goal[]){
int h = 0;
for(int i = 0; i < 9; i++){
for(int j = 0; j < 9; j++){
if (start[i] == goal[j] && start[i] != -1){
h += abs((j - i) / 3) + abs((j - i) % 3);
}
}
}
return h + g;
}
void moveTile(int start[], int goal[]){
int emptyAt = 0;
for(int i = 0; i < 9; i++){
if(start[i] == -1){
emptyAt = i;
break;
}
}
int t1[9],t2[9],t3[9],t4[9],f1 = INT_MAX,f2 = INT_MAX,f3 = INT_MAX,f4 = INT_MAX;
Copy(t1, start);
Copy(t2, start);
Copy(t3, start);
Copy(t4, start);
int row = emptyAt / 3;
int col = emptyAt % 3;
if(col - 1 >= 0){
moveLeft(t1, emptyAt);
f1 = heuristic(t1, goal);
}
if(col + 1 < 3){
moveRight(t2, emptyAt);
f2 = heuristic(t2, goal);
}
if(row + 1 < 3){
moveDown(t3, emptyAt);
f3 = heuristic(t3, goal);
}
if(row - 1 >= 0){
moveUp(t4, emptyAt);
f4 = heuristic(t4, goal);
}
//Find Least Heuristic State and Make the Move
if(f1 <= f2 && f1 <= f3 && f1 <= f4 ){
moveLeft(start, emptyAt);
}
else if(f2 <= f1 && f2 <= f3 && f2 <= f4 ){
moveRight(start, emptyAt);
}
else if(f3 <= f1 && f3 <= f2 && f3 <= f4 ){
moveDown(start, emptyAt);
}
else{
moveUp(start, emptyAt);
}
}
void solveEight(int start[], int goal[]){
g++;
//Move Tile
if(g>10){
cout<<"Not possible solution"<<endl;
return;
}
moveTile(start, goal);
//Get Heuristic Value
int f = heuristic(start, goal);
if(f == g){
cout << "Solved in " << f << " moves\n";
return;
}
solveEight(start, goal);
}
// bool solvable(int start[]){
// int invrs = 0;
// for(int i = 0; i < 9; i++){
// if(start[i] <= 1) continue;
// for(int j = i + 1; j < 9; j++){
// if(start[j] == -1) continue;
// if(start[i] > start[j]) invrs++;
// }
// }
// return invrs & 1 ? false : true;
// }
int main(){
int start[9];
int goal[9];
cout << "Enter the start state:(Enter -1 for empty):";
for(int i = 0; i < 9; i++){
cin >> start[i];
}
cout << "Enter the goal state:(Enter -1 for empty):";
for(int i = 0; i < 9; i++){
cin >> goal[i];
}
Print(start);
Print(goal);
// verify if possible to solve
solveEight(start,goal);
return 0;
}
//Job scheduling ::
// C++ code for the above approach
#include <algorithm>
#include <iostream>
using namespace std;
// A structure to represent a job
struct Job {
char id; // Job Id
int dead; // Deadline of job
int profit; // Profit if job is over before or on
// deadline
};
// Comparator function for sorting jobs
bool comparison(Job a, Job b)
{
return (a.profit > b.profit);
}
// Returns maximum profit from jobs
void printJobScheduling(Job arr[], int n)
{
// Sort all jobs according to decreasing order of profit
sort(arr, arr + n, comparison);
int result[n]; // To store result (Sequence of jobs)
bool slot[n]; // To keep track of free time slots
// Initialize all slots to be free
for (int i = 0; i < n; i++)
slot[i] = false;
// Iterate through all given jobs
for (int i = 0; i < n; i++) {
// Find a free slot for this job (Note that we start
// from the last possible slot)
for (int j = min(n, arr[i].dead) - 1; j >= 0; j--) {
// Free slot found
if (slot[j] == false) {
result[j] = i; // Add this job to result
slot[j] = true; // Make this slot occupied
break;
}
}
}
// Print the result
for (int i = 0; i < n; i++)
if (slot[i])
cout << arr[result[i]].id << " ";
}
// Driver's code
int main()
{
Job arr[] = { { 'a', 2, 100 },
{ 'b', 1, 19 },
{ 'c', 2, 27 },
{ 'd', 1, 25 },
{ 'e', 3, 15 } };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Following is maximum profit sequence of jobs "
"\n";
// Function call
printJobScheduling(arr, n);
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
// Chatbot ::
import random
# Define the chatbot responses
greetings = ['Hello!', 'Hi!', 'Hey there!', 'Greetings!', 'Nice to see you!']
goodbyes = ['Goodbye!', 'See you later!', 'Farewell!', 'Bye!', 'Take care!']
help_responses = ['How may I assist you?', 'What can I do for you?', 'How can I help?']
problem_responses = ['I\'m sorry to hear that. Can you please tell me more about the problem?', 'Let me see if I can help. What seems to be the issue?', 'I\'ll do my best to help you. What\'s the problem?']
thankyou_responses = ['You are welcome!', 'No problem!', 'It was my pleasure!', 'Glad to help!']
# Define the chatbot function
def chatbot():
print('Chatbot: ' + random.choice(greetings))
while True:
user_input = input('User: ')
if 'hello' in user_input.lower() or 'hi' in user_input.lower() or 'hey' in user_input.lower():
print('Chatbot: ' + random.choice(greetings))
elif 'bye' in user_input.lower() or 'goodbye' in user_input.lower() or 'see you' in user_input.lower():
print('Chatbot: ' + random.choice(goodbyes))
break
elif 'help' in user_input.lower() or 'support' in user_input.lower():
print('Chatbot: ' + random.choice(help_responses))
elif 'problem' in user_input.lower() or 'issue' in user_input.lower() or 'error' in user_input.lower():
print('Chatbot: ' + random.choice(problem_responses))
elif 'thank you' in user_input.lower() or 'thanks' in user_input.lower() or 'thankyou' in user_input.lower():
print('Chatbot: ' + random.choice(thankyou_responses))
else:
print('Chatbot: I\'m sorry, I don\'t understand. Can you please rephrase your request?')
# Test the chatbot
chatbot()
// currency apex class ::
public class currencyConverter {
public String currency1 {get;set;}
public String currency2 {get;set;}
public double value1 {get;set;}
public double value2 {get;set;}
public void convert() {
if(currency1 == currency2) {
value2 = value1;
}
else if(currency1 == 'Rupee' && currency2 == 'Dollar') {
value2 = value1/(82.23);
}
else if(currency1 == 'Dollar' && currency2 == 'Rupee') {
value2 = 82.23*(value1);
}
else if(currency1 == 'Pound' && currency2 == 'Rupee') {
value2 = 101.68*(value1);
}
else if(currency1 == 'Rupee' && currency2 == 'Pound') {
value2 = value1/(101.68);
}
else if(currency1 == 'Dollar' && currency2 == 'Pound') {
value2 = value1/(1.24);
}
else if(currency1 == 'Pound' && currency2 == 'Dollar') {
value2 = 1.24*(value1);
}
}
}
// currency vfp.txt
<apex:page controller="currencyConverter">
<apex:form>
<apex:outputText value="Currency Converter" style="font-weight: bold; font-size: 20px;"/><br/><br/>
<apex:outputLabel value="From: "/>
<apex:selectList value="{!currency1}">
<apex:selectOption itemLabel="Rupee" itemValue="Rupee"/>
<apex:selectOption itemLabel="Dollar" itemValue="Dollar"/>
<apex:selectOption itemLabel="Pound" itemValue="Pound"/>
</apex:selectList><br/><br/>
<apex:outputLabel value="To: "/>
<apex:selectList value="{!currency2}">
<apex:selectOption itemLabel="Rupee" itemValue="Rupee"/>
<apex:selectOption itemLabel="Dollar" itemValue="Dollar"/>
<apex:selectOption itemLabel="Pound" itemValue="Pound"/>
</apex:selectList><br/><br/>
<apex:outputLabel value="Value: "/>
<apex:inputText value="{!value1}"/><br/><br/>
<apex:commandButton value="Convert" action="{!convert}" rerender="result"/>
<br/><br/>
<apex:outputPanel id="result">
<apex:outputText value="Converted Value: {!value2}"/>
</apex:outputPanel>
</apex:form>
</apex:page>
//calci apex ::
public class Calculator {
public double n1 {get; set;}
public double n2 {get; set;}
public double res {get; set;}
public string v1 {get; set;}
public string v2 {get; set;}
public string vres {get; set;}
public void add() {
try {
n1 = double.valueOf(v1);
n2 = double.valueOf(v2);
res = n1 + n2;
vres = string.valueOf(res);
} catch (Exception e) {
vres = 'Enter Valid Input!';
}
}
public void subtract() {
try {
n1 = double.valueOf(v1);
n2 = double.valueOf(v2);
res = n1 - n2;
vres = string.valueOf(res);
} catch (Exception e) {
vres = 'Enter Valid Input!';
}
}
public void multiply() {
try {
n1 = double.valueOf(v1);
n2 = double.valueOf(v2);
res = n1 * n2;
vres = string.valueOf(res);
} catch (Exception e) {
vres = 'Enter Valid Input!';
}
}
public void divide() {
try {
n1 = double.valueOf(v1);
n2 = double.valueOf(v2);
if (n2 == 0) {
vres = 'Cannot Divide By Zero!';
return;
}
res = n1 / n2;
vres = string.valueOf(res);
} catch (Exception e) {
vres = 'Enter Valid Input!';
}
}
public void x_to_y() {
try {
n1 = double.valueOf(v1);
n2 = double.valueOf(v2);
res = Math.pow(n1, n2);
vres = string.valueOf(res);
} catch (Exception e) {
vres = 'Enter Valid Input!';
}
}
public void clear() {
v1 = '';
v2 = '';
vres = '0.0';
}
public void sin() {
try {
n1 = double.valueOf(v1);
res = Math.sin(n1);
vres = string.valueOf(res);
} catch (Exception e) {
vres = 'Enter Valid Input!';
}
}
public void cos() {
try {
n1 = double.valueOf(v1);
res = Math.cos(n1);
vres = string.valueOf(res);
} catch (Exception e) {
vres = 'Enter Valid Input!';
}
}
public void tan() {
try {
n1 = double.valueOf(v1);
res = Math.tan(n1);
vres = string.valueOf(res);
} catch (Exception e) {
vres = 'Enter Valid Input!';
}
}
}
//calci vfp
<apex:page controller="Calculator">
<apex:form>
<apex:outputText value="Calculator" style="font-weight: bold; font-size: 20px;"/><br/><br/>
<apex:outputLabel value="Number 1: "/>
<apex:inputText value="{!v1}"/><br/><br/>
<apex:outputLabel value="Number 2: "/>
<apex:inputText value="{!v2}"/><br/><br/>
<apex:commandButton value="+" action="{!add}" rerender="result"/>
<apex:commandButton value="-" action="{!subtract}" rerender="result"/>
<apex:commandButton value="*" action="{!multiply}" rerender="result"/>
<apex:commandButton value="/" action="{!divide}" rerender="result"/>
<apex:commandButton value="^" action="{!x_to_y}" rerender="result"/>
<apex:commandButton value="sin" action="{!sin}" rerender="result"/>
<apex:commandButton value="cos" action="{!cos}" rerender="result"/>
<apex:commandButton value="tan" action="{!tan}" rerender="result"/>
<apex:commandButton value="Clear" action="{!clear}" rerender="result"/>
<br/><br/>
<apex:outputPanel id="result">
<apex:outputText value="Result: {!vres}"/>
</apex:outputPanel>
</apex:form>
</apex:page>
//expert system (Ayush code)::
# Define the rules
def rule1(symptoms):
if 'fever' in symptoms and 'cough' in symptoms and 'fatigue' in symptoms:
return 'You may have the flu.'
return None
def rule2(symptoms):
if 'fever' in symptoms and 'rash' in symptoms and 'headache' in symptoms:
return 'You may have meningitis.'
return None
def rule3(symptoms):
if 'pain' in symptoms and 'swelling' in symptoms and 'bruising' in symptoms:
return 'You may have a fracture.'
return None
def rule4(symptoms):
if 'abdominal pain' in symptoms and 'diarrhea' in symptoms and 'nausea' in symptoms:
return 'You may have food poisoning.'
return None
def rule5(symptoms):
if 'shortness of breath' in symptoms and 'chest pain' in symptoms and 'dizziness' in symptoms:
return 'You may be having a heart attack. Please seek medical attention immediately.'
return None
# Define the expert system
def diagnose(symptoms):
rules = [rule1, rule2, rule3, rule4, rule5]
results = []
for rule in rules:
result = rule(symptoms)
if result:
results.append(result)
if len(results) == 0:
return 'Sorry, we could not diagnose your condition.'
elif len(results) == 1:
return results[0]
else:
return 'You may have multiple conditions: ' + ', '.join(results)
# Test the expert system
symptoms = ['fever', 'rash', 'headache']
result = diagnose(symptoms)
print(result) # Output: You may have the flu.