BFS::
#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);}
}
NQUEEN::
#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; // we are taking 4*4 grid and 4 queens
cin>>n;
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;
}
JOBSCHEDULING::
#include<bits/stdc++.h>
using namespace std;
struct Job{
public:
int jobid, deadline, profit;
};
class Solution
{
public:
bool static comparison(Job a, Job b)
{
return(a.profit>b.profit);
}
pair <int,int> jobScheduling(Job jobs[], int n)
{
sort(jobs,jobs+n,comparison);
int maxdead = jobs[0].deadline;
for(int i=1;i<n;i++)
{
maxdead = max(maxdead,jobs[i].deadline);
}
int slot[maxdead+1];
for(int i=0;i<maxdead;i++)
{
slot[i] = -1;
}
int countjobs = 0, jobProfit = 0;
for(int i=0;i<n;i++)
{
for(int j=jobs[i].deadline;j>0;j--)
{
if(slot[j]==-1)
{
// slot[j] = jobs[i].jobid;
slot[j] = i;
countjobs++;
jobProfit = jobProfit + jobs[i].profit;
break;
}
}
}
return make_pair(countjobs,jobProfit);
}
};
int main()
{
int n = 4;
Job jobs[n] = {{1,4,20},{2,1,10},{3,2,40},{4,2,30}};
Solution obj;
pair<int,int> ans = obj.jobScheduling(jobs,n);
cout<<ans.first<<","<<ans.second<<endl;
}
ASTAR::
class Coord:
def __init__(self, x, y):
self.x = x
self.y = y
class Node:
def __init__(self, parent, coord, g, h):
self.Coord = coord
self.parent = parent
self.g = g
self.h = h
self.f = self.g + self.h
def a_star(game, start, end):
# initialization
print("Solving....")
open = []
close = []
start_node = Node(None, Coord(start.x, start.y), 0, 0)
goal_node = Node(None, Coord(end.x, end.y), 0, 0)
open.append(start_node)
found = False
# loop condition
while(len(open)!=0):
curr = open[0]
curr_index = 0
# finding least f(n) node in open list
for index, item in enumerate(open):
if(item.f < curr.f):
curr = item
curr_index = index
close.append(curr.Coord)
# print(close)
open.pop(curr_index)
# print(open)
# checking for solution goal node
if(curr.Coord.x == goal_node.Coord.x and curr.Coord.y == goal_node.Coord.y):
found = True
solution = []
while(curr is not None):
solution.append(curr.Coord)
curr = curr.parent
return solution[::-1]
# exploration
for new_pos in [(0, -1), (0, 1), (-1, 0), (1, 0)]:
new_coord = Coord(curr.Coord.x + new_pos[0], curr.Coord.y + new_pos[1])
# print(new_coord.x, new_coord.y)
visited = False
# if new_coord not in close:
for node_i in close:
if(new_coord.x == node_i.x and new_coord.y == node_i.y):
# print("Nope1")
visited = True
continue
if(not visited and new_coord.x <= (len(game) - 1) and new_coord.x >= 0 and new_coord.y <= (len(game[0]) -1) and new_coord.y >= 0):
if(game[new_coord.x][new_coord.y] == 0):
hrt = (new_coord.x - goal_node.Coord.x)**2 + (new_coord.y - goal_node.Coord.y)**2
new_node = Node(curr, new_coord, curr.g + 1, hrt)
# game[new_coord.x][new_coord.y] = 'V'
open.append(new_node)
return []
def main():
game = [
[0,0,0,0,0,0],
[0,0,1,0,0,0],
[0,0,1,0,0,0],
[0,0,1,1,1,0],
[0,1,0,0,0,0],
[0,0,0,0,1,0],
]
while True:
try:
startx = int(input("Enter start x: "))
starty = int(input("Enter start y: "))
break
except ValueError:
print("Wrong input!")
start = Coord(startx,starty)
end = Coord(5,5)
solution = a_star(game, start, end)
if(len(solution)==0):
print("Problem cannot be solved!")
# insert print logic
else:
print("Solution found!")
for i in range(len(solution)):
# print(solution[i].x, solution[i].y)
game[solution[i].x][solution[i].y] = '*'
for i in range(len(game)):
print(end="|")
for elem in game[i]:
print(elem, end="|")
print()
# print(game[i])
main()
CHATBOT::
import re
import random
# Define the chatbot's rules and responses
rules = {
'greeting': {
'patterns': [r'hello', r'hi', r'hey'],
'responses': ['Hello! Welcome to our food ordering service.', 'Hi there! How can I assist you with your order?']
},
'menu': {
'patterns': [r'menu', r'options'],
'responses': ['Sure! Here is our menu: ...\n 1.Pav Bhaji \n 2.Vada Pav \n 3.Maggi \n 4.Chai'],
},
'food items' : {
'patterns' : [r'Vada Pav',r'Pav Bhaji',r'Chai',r'Maggi' ],
'responses' : ['Do you want to confirm your order??'],
},
'order': {
'patterns': [r'order', r'I want to order'],
'responses': ['Great! Please let me know what items you would like to order.'],
},
'customization': {
'patterns': [r'customize', r'special request'],
'responses': ['Certainly! Let me know your specific requirements or any dietary restrictions.'],
},
'confirm_order': {
'patterns': [r'confirm', r'place order'],
'responses': ['Perfect! Your order has been placed. The estimated delivery time is approximately 30 minutes.'],
},
'gratitude' : {
'patterns' : [r'thank you'],
'responses' : ['My pleasure']
},
'cancel_order': {
'patterns': [r'cancel', r'change', r'update'],
'responses': ['I apologize for the inconvenience. Please contact our customer support for order modifications.'],
},
'goodbye': {
'patterns': [r'bye', r'goodbye', r'see you'],
'responses': ['Thank you for choosing our food ordering service. Ab nikal BC yaha se', 'Goodbye!'],
},
'default': {
'responses': ['Im sorry, I didnt understand that. Can you please rephrase?']
}
}
# Function to match user input with patterns
def match_patterns(user_input, patterns):
for pattern in patterns:
match = re.search(pattern, user_input, re.IGNORECASE)
if match:
return True
return False
# Function to get chatbot's response
def get_response(user_input):
for intent, data in rules.items():
patterns = data.get('patterns')
if patterns and match_patterns(user_input, patterns):
responses = data.get('responses')
return random.choice(responses)
return random.choice(rules['default']['responses'])
# Main conversation loop
def chat():
print("Chatbot: Hello! Welcome to our food ordering service.")
while True:
user_input = input("User: ")
response = get_response(user_input)
print("Chatbot:", response)
# Exit the loop if the user says goodbye
if any(re.search(pattern, user_input) for pattern in rules['goodbye']['patterns']):
break
# Start the chatbot
chat()
EXPERT::
# 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','cough','fatigue']
result = diagnose(symptoms)
print(result) # Output: You may have the flu.
CHANGECOLOR::
public Renderer cubeRendere;
public GameObject cube;
[SerializeField] private Color newColor;
[SerializeField] private Color[] colors;
// start
cubeRendere = cube.GetComponent<Renderer>();
public void ChangeMaterial()
{
newColor = Random.ColorHSV();
cubeRendere.material.color = newColor;
}