``` const int N = 1e5;
vector<int> dp(N,-1);
class Solution {
public:
int climbStairs(int n) {

if(n==1)return 1;
if(n==2)return 2;
if(dp[n]!=-1)return dp[n];
return dp[n]=climbStairs(n-1)+climbStairs(n-2);
}
};```
```#include<bits/stdc++.h>
using namespace std;
const int N = 1e5;
vector<int> dp(N,-1);
int fib(int n)
{
if(n==0)return 0;
if(n==1)return 1;
if(dp[n]!=-1)return dp[n];
return dp[n]=fib(n-1)+fib(n-2);
}
int main()
{
int n=6;
cout<<fib(n);
}```
```string reverseWords(string s) {
int n = s.size();
std::string reverse_string = "";
for ( int i = n-1 ; i > -1; --i ){
if (s[i] == ' '){
continue;
}
int count = 0;
while ( i > -1 && s[i] != ' '){
--i; count++;
}
if (reverse_string != ""){
reverse_string.append(" ");
}
reverse_string.append(s.substr(i+1,count));
}
return reverse_string;
}```
```class Solution {
public:
string frequencySort(string s) {
map<char,int> m1;
multimap<int,char> m2;
map<char,int> :: iterator it;
multimap<int,char>::iterator it1;
string str = "";
for(int i=0;i<s.length();++i)
m1[s[i]]++;
for(it=m1.begin();it!=m1.end();++it)
m2.insert({it->second,it->first});
for(it1=m2.begin();it1!=m2.end();++it1)
{
for(int j=it1->first;j>0;--j)
{str.push_back(it1->second);}
}
reverse(str.begin(),str.end());
return str;
}
};```
```class Solution {
public:
bool isIsomorphic(string s, string t) {
string r;
if(s.length()!=t.length())
return false;
map<char,char> m1,m2,m3;
for(int i=0;i<s.length();++i)
{
m1.insert({s[i],t[i]});
m2.insert({t[i],s[i]});
}
if(m1.size()>=m2.size())
{m3=m2;
r=s;}
else
{m3=m1;r=t;}
for(int j=0;j<s.length();++j)
{
if(r[j]==m3[t[j]])
continue;
else
return false;
}
return true;

}
};```
``` string s= "ayush";
sort(s.begin(),s.end());
cout<<s;```
```if(str.find(goal) != string::npos)
{return true;}
else{return false;}```
```if(str.find(goal) != string::npos)
{return true;}
else{return false;}```
```if(n==1)return v[0];
if(v[0]!=v[1])return v[0];
if(v[n-1]!=v[n-2])return v[n-1];
low=1;high=n-2;
while(low<high)
{
mid=high-((high-low)/2);
if(v[mid]!=v[mid-1] && v[mid]!=v[mid+1])return v[mid];
if((mid%2==0 && v[mid-1]==v[mid]) || (mid%2==1 && v[mid+1]==v[mid]))
{
high=mid-1;
}
else if((mid%2==1 && v[mid-1]==v[mid]) || (mid%2==0 && v[mid+1]==v[mid]))
{
low=mid+1;
}
}
```
```#include <iostream>
#include <istream>
#include <string>
#include <vector>

using namespace std;

class Book {
int BookID;
std::string Title;
std::string Author;
double price;
static int numOfBooks;

friend class Library; // Declare Library as a friend class

public:
Book(int BookID, std::string Title, std::string Author, double price){
this->BookID = BookID;
this->Title = Title;
this->Author = Author;
this->price = price;
numOfBooks ++;
}
int getBookID() const {
return BookID;
}

std::string getTitle() const {
return Title;
}
std::string getAuthor() const {
return Author;
}
double getPrice() const {
return price;
}
//Static Function
static int getTotalNumOfBooks(){
return numOfBooks;
};

};

int Book::numOfBooks = 0;

//Class User
class Users{

public:
std::string name;
std::string address;
std::string email;
int phoneNum;

Users(std::string n, std::string addre,std::string em, int pN){
name = n;
address = addre;
email = em;
phoneNum = pN;
}

//Virtual Function & Overiding function
virtual void display(){
}

};
//Derived Class from Base class User
class Student: public Users{

int studentID;
public:
Student(int studentID, std::string name, std::string address, std::string email, int phoneNum):Users(name, address, email, phoneNum){
this->studentID = studentID;
}

int getStudentID() const {
return studentID;
}

//Function Overloading, Same Name but different arguments.
void print(std::string name){
cout<<"student Name: "<<name<<endl;
}
void print(std::string name, int studentID){
cout<<"Student Name: "<<name<<endl;
cout<<"Student ID: "<<studentID<<endl;
}
//Default arguments
void print(std::string name, std::string email, int studentID = 1111){
cout<<"Student Name: "<<name<<endl;
cout<<"Student Email: "<<email<<endl;
cout<<"Student ID: "<<studentID<<endl;
}

void display(){
cout<<"\n__Student Info:_ "<<endl;
cout<<"ID: "<<studentID<<endl;
cout<<"Name: "<<name<<endl;
cout<<"Address: "<<address<<endl;
cout<<"Email: "<<email<<endl;
cout<<"Phone Number: "<<phoneNum<<endl;
}

//Friend Function
friend void globalFunction(Student &stud);
};
class Staff: public Users{
int staffID;
public:
Staff(int staffID, std::string name, std::string address, std::string email, int phoneNum):Users(name, address, email, phoneNum){
this->staffID = staffID;
}
int getStaffID(){
return staffID;
}

void display(){
cout<<"\n___Staff Info:_ "<<endl;
cout<<"ID: "<<staffID<<endl;
cout<<"Name: "<<name<<endl;
cout<<"Address: "<<address<<endl;
cout<<"Email: "<<email<<endl;
cout<<"Phone Number: "<<phoneNum<<endl;
}
friend void globalFunction(Staff &staf);
};

//Friend Function implementation
void globalFunction(Student &stud, Staff &staf){
cout<<"\nAccessing Student ID: "<<stud.getStudentID()<<endl;
cout<<"Accessing Staff ID: "<<staf.getStaffID()<<endl;
}

class Library{

vector<Book*> books; // Declaration of books vector
vector<Student*> students;

Book *book;
std::string name;
std::string address;

public:
Library(std::string name, std::string address){
this->name = name;
this->address = address;
}

void setBook(Book *book){
this->book = book;
}
Book* getBook(){
return book;
}
std::string getName(){
return name;
}
void setName(std::string name){
this->name = name;
}
std::string getAddress(){
return address;
}
void setAddress(std::string address){
this->address = address;
}
void addBook(const std::string& title, const std::string& author, double price) {
int id = books.size() + 1; // Generate ID automatically based on the number of books
books.push_back(new Book(id, title, author, price));
cout << "Book added successfully with ID: " << id << endl;
}
bool deleteBook(int id) {
auto it = find_if(books.begin(), books.end(), [id](const Book* book) {
return book->getBookID() == id;
});
if (it != books.end()) {
books.erase(it);
return true;
}
return false;
}
void editBook(int id, std::string newTitle, std::string newAuthor, double newPrice) {
auto it = find_if(books.begin(), books.end(), [id](const Book* book) {
return book->getBookID() == id;
});
if (it != books.end()) {
(*it)->Title = newTitle;
(*it)->Author = newAuthor;
(*it)->price = newPrice;
}
}
void showBookInfo(int id) {
auto it = std::find_if(books.begin(), books.end(), [id](const Book* book) {
return book->getBookID() == id;
});
if (it != books.end()) {
std::cout << "Book ID: " << (*it)->getBookID() << std::endl;
std::cout << "Book Title: " << (*it)->getTitle() << std::endl;
std::cout << "Book Author: " << (*it)->getAuthor() << std::endl;
std::cout << "Book Price: " << (*it)->getPrice() << std::endl;
}
}

std::vector<Book*>& getBooks() { // Return a reference to the vector of books
return books;
}

void addStudent(const std::string& name, const std::string& address, const std::string& email, int phoneNum) {
int id = students.size() + 1; // Generate ID automatically based on the number of students
students.push_back(new Student(id, name, address, email, phoneNum));
cout << "Student added successfully with ID: " << id << endl;
}

bool deleteStudent(int id) {
auto it = find_if(students.begin(), students.end(), [id](const Student* student) {
return student->getStudentID() == id;
});
if (it != students.end()) {
students.erase(it);
return true;
}
return false;
}

void editStudent(int id, const string& newName, const string& newAddress, const string& newEmail, int newPhoneNum) {
auto it = find_if(students.begin(), students.end(), [id](const Student* student) {
return student->getStudentID() == id;
});
if (it != students.end()) {
(*it)->name = newName;
(*it)->address = newAddress;
(*it)->email = newEmail;
(*it)->phoneNum = newPhoneNum;
}
}

void showStudentInfo(int id) {
auto it = find_if(students.begin(), students.end(), [id](const Student* student) {
return student->getStudentID() == id;
});
if (it != students.end()) {
cout << "Student ID: " << (*it)->getStudentID() << endl;
cout << "Student Name: " << (*it)->name << endl;
cout << "Student Address: " << (*it)->address << endl;
cout << "Student Email: " << (*it)->email << endl;
cout << "Student Phone Number: " << (*it)->phoneNum << endl;
}
}
};

int main() {
Library library("University Library", "Uskudar");

while (true) {
cout << "\nMenu:" << endl;
cout << "1. Manage Books" << endl;
cout << "2. Manage Students" << endl;
cout << "3. Exit" << endl;
cout << "Enter your choice: ";

int choice;
cin >> choice;

switch (choice) {
case 1: {
cout << "\nBooks Menu:" << endl;
cout << "1. Add Book" << endl;
cout << "2. Delete Book" << endl;
cout << "3. Edit Book" << endl;
cout << "4. Show Book Information" << endl;
cout << "5. Book List" << endl;
cout << "Enter your choice: ";

int bookChoice;
cin >> bookChoice;

switch (bookChoice) {
case 1: {
std::string title, author;
double price;
cout << "Enter book title: ";
cin.ignore();
getline(cin, title);
cout << "Enter book author: ";
getline(cin, author);
cout << "Enter book price: ";
cin >> price;
library.addBook(title, author, price);

break;
}
case 2: {
int id;
cout << "Enter ID of the book to delete: ";
cin >> id;
if (library.deleteBook(id)) {
cout << "Book with ID " << id << " deleted successfully." << endl;
}
else {
cout << "Book with ID " << id << " not found." << endl;
}
break;
}
case 3: {
int id;
string newTitle, newAuthor;
double newPrice;
cout << "Enter ID of the book to edit: ";
cin >> id;
cout << "Enter new title: ";
cin.ignore();
getline(cin, newTitle);
cout << "Enter new author: ";
getline(cin, newAuthor);
cout << "Enter new price: ";
cin >> newPrice;
library.editBook(id, newTitle, newAuthor, newPrice);
cout << "Book edited successfully." << endl;
break;
}
case 4: {
int id;
cout << "Enter ID of the book to show information: ";
cin >> id;
library.showBookInfo(id);
break;
}
case 5: {
vector<Book*> books = library.getBooks();
cout << "\nBook List:" << endl;
for (Book* book : books) {
cout << "Book ID: " << book->getBookID() << ", Title: " << book->getTitle() << ", Author: " << book->getAuthor() << ", Price: " << book->getPrice() << endl;
}
break;
}

default:
cout << "Invalid choice." << endl;
}
break;
}
case 2: {
cout << "\nStudents Menu:" << endl;
cout << "1. Add Student" << endl;
cout << "2. Remove Student" << endl;
cout << "3. Edit Student" << endl;
cout << "4. Get Student Info" << endl;
cout << "5. Exit" << endl;
cout << "Enter your choice: ";

int studentChoice;
cin >> studentChoice;

switch (studentChoice) {
case 1: {
std::string name, address, email;
int phoneNum;
cout << "Enter student name: ";
cin.ignore();
getline(cin, name);
cout << "Enter student address: ";
getline(cin, address);
cout << "Enter student email: ";
cin >> email;
cout << "Enter student phone number: ";
cin >> phoneNum;
library.addStudent(name, address, email, phoneNum);

break;
}
case 2: {
int id;
cout << "Enter ID of the student to remove: ";
cin >> id;
if (library.deleteStudent(id)) {
cout << "Student with ID " << id << " removed successfully." << endl;
} else {
cout << "Student with ID " << id << " not found." << endl;
}
break;
}
case 3: {
int id;
string newName, newAddress, newEmail;
int newPhoneNum;
cout << "Enter ID of the student to edit: ";
cin >> id;
cout << "Enter new name: ";
cin.ignore();
getline(cin, newName);
cout << "Enter new address: ";
getline(cin, newAddress);
cout << "Enter new email: ";
cin >> newEmail;
cout << "Enter new phone number: ";
cin >> newPhoneNum;
library.editStudent(id, newName, newAddress, newEmail, newPhoneNum);
cout << "Student edited successfully." << endl;
break;
}
case 4: {
int id;
cout << "Enter ID of the student to get information: ";
cin >> id;
library.showStudentInfo(id);
break;
}
case 5: {
cout << "Exiting students menu..." << endl;
break;
}
default:
cout << "Invalid choice." << endl;
}
break;
}
case 3:
cout << "Exiting..." << endl;
return 0;
default:
cout << "Invalid choice. Please enter a number from 1 to 3." << endl;
}
}

return 0;
}
//OUTPUT:

Menu:
1. Manage Books
2. Manage Students
3. Exit
Enter your choice: 1

Books Menu:
1. Add Book
2. Delete Book
3. Edit Book
4. Show Book Information
5. Book List
Enter your choice: 1
Enter book title: The Power
Enter book author: James
Enter book price: 23
Book added successfully with ID: 1

Menu:
1. Manage Books
2. Manage Students
3. Exit
Enter your choice: 1

Books Menu:
1. Add Book
2. Delete Book
3. Edit Book
4. Show Book Information
5. Book List
Enter your choice: 1
Enter book title: Psychology
Enter book author: Mike
Enter book price: 21
Book added successfully with ID: 2

Menu:
1. Manage Books
2. Manage Students
3. Exit
Enter your choice: 1

Books Menu:
1. Add Book
2. Delete Book
3. Edit Book
4. Show Book Information
5. Book List
Enter your choice: 5

Book List:
Book ID: 1, Title: The Power, Author: James, Price: 23
Book ID: 2, Title: Physcology, Author: Mike, Price: 21

Menu:
1. Manage Books
2. Manage Students
3. Exit
Enter your choice: 1

Books Menu:
1. Add Book
2. Delete Book
3. Edit Book
4. Show Book Information
5. Book List
Enter your choice: 2
Enter ID of the book to delete: 2
Book with ID 2 deleted successfully.

Menu:
1. Manage Books
2. Manage Students
3. Exit
Enter your choice: 1

Books Menu:
1. Add Book
2. Delete Book
3. Edit Book
4. Show Book Information
5. Book List
Enter your choice: 5

Book List:
Book ID: 1, Title: The Power, Author: James, Price: 23

Menu:
1. Manage Books
2. Manage Students
3. Exit
Enter your choice: 2

Students Menu:
1. Add Student
2. Remove Student
3. Edit Student
4. Get Student Info
5. Exit
Enter your choice: 1
Enter student name: Mohamed
Enter student address: Istanbul
Enter student email: moha@gmail.com
Enter student phone number: 5544
Student added successfully with ID: 1

Menu:
1. Manage Books
2. Manage Students
3. Exit
Enter your choice: 2

Students Menu:
1. Add Student
2. Remove Student
3. Edit Student
4. Get Student Info
5. Exit
Enter your choice: 1
Enter student name: Nasir
Enter student address: Istanbul
Enter student email: nasir@gmail.com
Enter student phone number: 1122
Student added successfully with ID: 2

Menu:
1. Manage Books
2. Manage Students
3. Exit
Enter your choice: 2

Students Menu:
1. Add Student
2. Remove Student
3. Edit Student
4. Get Student Info
5. Exit
Enter your choice: 2
Enter ID of the student to remove: 2
Student with ID 2 removed successfully.

Menu:
1. Manage Books
2. Manage Students
3. Exit
Enter your choice: 2

Students Menu:
1. Add Student
2. Remove Student
3. Edit Student
4. Get Student Info
5. Exit
Enter your choice: 4
Enter ID of the student to get information: 2

Menu:
1. Manage Books
2. Manage Students
3. Exit
Enter your choice: 2

Students Menu:
1. Add Student
2. Remove Student
3. Edit Student
4. Get Student Info
5. Exit
Enter your choice: 4
Enter ID of the student to get information: 1
Student ID: 1
Student Name: Mohamed
Student Address: Istanbul
Student Email: moha@gmail.com
Student Phone Number: 5544

Menu:
1. Manage Books
2. Manage Students
3. Exit
Enter your choice: 3
Exiting...

Normal program termination. Exit status: 0```
```#include <iostream>

using namespace std;

class Book{
int BookID;
string Title;
string Author;
double price;
static int numOfBooks;

public:
//Parameter Constructor
Book(int BookID, string Title, string Author, double price){
this->BookID = BookID;
this->Title = Title;
this->Author = Author;
this->price = price;
numOfBooks ++;
}
int getBookID(){
return BookID;
}
string getTitle(){
return Title;
}
string getAuthor(){
return Author;
}
double getPrice(){
return price;
}
//Static Function
static int getTotalNumOfBooks(){
return numOfBooks;
}
};
int Book::numOfBooks = 0;

class Library{
Book *book;
string name;
string address;

public:
Library(string name, string address){
this->name = name;
this->address = address;
}

void setBook(Book *book){
this->book = book;
}
Book* getBook(){
return book;
}
string getName(){
return name;
}
void setName(string name){
this->name = name;
}
string getAddress(){
return address;
}
void setAddress(string address){
this->address = address;
}
};

//Class User
class Users{

public:
string name;
string address;
string email;
int phoneNum;

Users(string n, string addre,string em, int pN){
name = n;
address = addre;
email = em;
phoneNum = pN;
}

//Virtual Function & Overiding function
virtual void display(){
}

};
//Derived Class from Base class User
class Student: public Users{

int studentID;
public:
Student(int studentID, string name, string address, string email, int phoneNum):Users(name, address, email, phoneNum){
this->studentID = studentID;
}

int getStudentID(){
return studentID;
}

//Function Overloading, Same Name but different arguments.
void print(string name){
cout<<"student Name: "<<name<<endl;
}
void print(string name, int studentID){
cout<<"Student Name: "<<name<<endl;
cout<<"Student ID: "<<studentID<<endl;
}
//Default arguments
void print(string name, string email, int studentID = 1111){
cout<<"Student Name: "<<name<<endl;
cout<<"Student Email: "<<email<<endl;
cout<<"Student ID: "<<studentID<<endl;
}

void display(){
cout<<"\n_____Student Info:____ "<<endl;
cout<<"ID: "<<studentID<<endl;
cout<<"Name: "<<name<<endl;
cout<<"Address: "<<address<<endl;
cout<<"Email: "<<email<<endl;
cout<<"Phone Number: "<<phoneNum<<endl;
}

//Friend Function
friend void globalFunction(Student &stud);
};
class Staff: public Users{
int staffID;
public:
Staff(int staffID, string name, string address, string email, int phoneNum):Users(name, address, email, phoneNum){
this->staffID = staffID;
}
int getStaffID(){
return staffID;
}

void display(){
cout<<"\n______Staff Info:____ "<<endl;
cout<<"ID: "<<staffID<<endl;
cout<<"Name: "<<name<<endl;
cout<<"Address: "<<address<<endl;
cout<<"Email: "<<email<<endl;
cout<<"Phone Number: "<<phoneNum<<endl;
}
friend void globalFunction(Staff &staf);
};

//Friend Function implementation
void globalFunction(Student &stud, Staff &staf){
cout<<"\nAccessing Student ID: "<<stud.getStudentID()<<endl;
cout<<"Accessing Staff ID: "<<staf.getStaffID()<<endl;
}

int main() {

cout<<"_____Library Management System._____"<<endl;

Library lib("University Library","Uskudar");
cout<<"\n____Library Info____"<<endl;
cout<<"Name: "<<lib.getName()<<endl;
cout<<"Address: "<<lib.getAddress()<<endl;

lib.setBook(new Book(1, "Java", "James", 20.99));
cout<<"____Book Info____"<<endl;
cout<<"Book ID: "<<lib.getBook()->getBookID()<<endl;
cout<<"Book Title: "<<lib.getBook()->getTitle()<<endl;
cout<<"Book Author: "<<lib.getBook()->getAuthor()<<endl;
cout<<"Book Price: "<<lib.getBook()->getPrice()<<endl;
//Calling static function in the Book class
cout<<"Total Books in the Library are: "<<Book::getTotalNumOfBooks()<<endl;

lib.setBook(new Book(2, "Math", "Mike", 24.99));
cout<<"____Book Info____"<<endl;
cout<<"Book ID: "<<lib.getBook()->getBookID()<<endl;
cout<<"Book Title: "<<lib.getBook()->getTitle()<<endl;
cout<<"Book Author: "<<lib.getBook()->getAuthor()<<endl;
cout<<"Book Price: "<<lib.getBook()->getPrice()<<endl;

cout<<"Total Books in the Library are: "<<Book::getTotalNumOfBooks()<<endl;

Student s1(2023, "Mohamed","Istanbul","Student@gmail.com", 11111);
Users *user;
user = & s1;
user->display();

Staff stff(3034,"Staff1","Istnabul","Staff@gmail.com", 9999);
user = &stff;
user->display();

//Friend Function
globalFunction(s1,stff);

//Calling Overloading Function in the Student class
cout<<"_____"<<endl;
s1.print("Musa");
s1.print("Musa",5555);
//Calling default arguments in the student class
s1.print("Yahya", "yahya@emial.com");

return 0;
}
___________________________________________________________________________
//OUTPUT:

_____Library Management System._____

____Library Info____
Name: University Library
Address: Uskudar
____Book Info____
Book ID: 1
Book Title: Java
Book Author: James
Book Price: 20.99
Total Books in the Library are: 1
____Book Info____
Book ID: 2
Book Title: Math
Book Author: Mike
Book Price: 24.99
Total Books in the Library are: 2

_____Student Info:____
ID: 2023
Name: Mohamed
Address: Istanbul
Email: Student@gmail.com
Phone Number: 11111

______Staff Info:____
ID: 3034
Name: Staff1
Address: Istnabul
Email: Staff@gmail.com
Phone Number: 9999

Accessing Student ID: 2023
Accessing Staff ID: 3034
_____
student Name: Musa
Student Name: Musa
Student ID: 5555
Student Name: Yahya
Student Email: yahya@emial.com
Student ID: 1111
```
```#include <iostream>

using namespace std;

class Base{

public:
virtual void output(){
cout<<"Virtual Function"<<endl;
}
void display(){
cout<<"Display Base Function"<<endl;
}
};

class derived:public Base{

public:
void output(){
cout<<"Function in the derived "<<endl;
}
void display(){
cout<<"Display Derived Function"<<endl;
}
};

int main() {

Base *ptr;
derived d;
ptr = &d;
//Run time binding, it will call output function in the drived class
ptr->output();

//Compile time binding, it will call display function in the base class.
ptr->display();

return 0;
}
//OUTPUT:
Function in the derived
Display Base Function```
```question 1.

#include <iostream>

using namespace std;
//Abstract class becuase it contain ppure virtual function
class Vehicle{

public:
virtual void drive() = 0;
};

class Car: public Vehicle{
public:
void drive(){
cout<<"Driving a car "<<endl;
}
};

class Motorcycle: public Vehicle{
public:
void drive(){
cout<<"Driving a motorcycle"<<endl;
}
};

int main() {
//Abstract class can not be instantiated. but you can write as pointer and
Vehicle *obj;
Car c;
obj = &c;
obj->drive();
Motorcycle m;
obj = &m;
obj->drive();

return 0;
}
//OUTPUT:
Driving a car
Driving a motorcycle
____________________________________________________________

Question 2:
#include <iostream>

using namespace std;

class Shape{

public:
double Area(){
return 0.0;
}

};

class Rectangle: public Shape{
double width;
double length;
public:
Rectangle(double width, double length){
this->width = 10;
this->length = 10;
}
double Area(){
//int area = width * length;
return width * length;
//cout<<"Area of Rectangle = "<<area<<endl;
}

};

class Triangle: public Shape{
double base;
double heigth;
public:
Triangle(double b, double h):base(b),heigth(h){

}
double Area(){
return 0.5 * base * heigth;
}
};

int main() {
Shape *shape;
Rectangle rect(10, 10);
shape = &rect;
shape->Area();

return 0;
}

________________________________________________________________-
Question 3.
#include <iostream>

using namespace std;

class Animal{

protected:
string name;
public:
Animal(string name){
this->name = name;
}
virtual void makeSound(){
cout<<"Animal: "<<endl;
}

};

class Dog: public Animal{
string breed;
public:
Dog(string name, string breed):Animal(name){
this->breed = breed;
}
void makeSound(){
//Animal::makeSound(); to call makeSound function in Animal class
cout<<"Dog makes Sound."<<endl;
}
void display(){
cout<<"Dog Name: "<<name<<endl;
cout<<"Dog Breed: "<<breed<<endl;
}
};

class Cat: public Animal{
string color;

public:
Cat(string name, string color):Animal(name){
this->color = color;
}
void makeSound(){
cout<<"Cat makes Sound."<<endl;
}
void display(){
cout<<"Cat Name: "<<name<<endl;
cout<<"Cat Color "<<color<<endl;
}
};

int main() {

Dog d("Doggy","Male");
d.display();
d.makeSound();
cout<<endl;
Cat c("Catty","Brown");
c.display();
c.makeSound();

return 0;
}
//OUTPUT:
Dog Name: Doggy
Dog Breed: Male
Dog makes Sound.

Cat Name: Catty
Cat Color Brown
Cat makes Sound.```
```#include <iostream>

using namespace std;
//PUre Virtual Function
class Employee{
int code;
string name[20];
public:
virtual void getData();
virtual void Display();
};
class Grade : public Employee{
char grade[20];
float salary;

public:
void getData();
void Display();
};

void Employee::getData(){

}
void Employee::Display(){

}
void Grade::getData(){
cout<<"Enter Employee Grade: "<<endl;
cin>>grade;
cout<<"Enter Employee Salaray: "<<endl;
cin>>salary;
}
void Grade::Display(){
cout<<"Employee Grade is: "<<grade<<endl;
cout<<"Employee Salaray is: "<<salary<<endl;
}

int main() {
Employee *ptr;
Grade obj;
ptr = &obj;
ptr->getData();
ptr->Display();

return 0;
}
//OUTPUT:
Enter Employee Grade:
A
Enter Employee Salaray:
24000
Employee Grade is: A
Employee Salaray is: 24000
```
```#include <iostream>

using namespace std;
//Hierarchical inheritance
class Employee{

protected:
string name;
int employeeID;

public:

void inputEmployeeInfo(){
cout<<"Enter name: "<<endl;
cin>>name;
cout<<"Enter Employee ID: "<<endl;
cin>>employeeID;
}
void displayEmployeeInfo(){
cout<<"Name: "<<name<<endl;
cout<<"Employee ID: "<<employeeID<<endl;
}
};
//Derived Manager Class From Employee Class

class Manager :virtual public Employee{
protected:
int level;
public:
void inputManagerInfo(){
//inputEmployeeInfo();
cout<<"Enter Manager Level: "<<endl;
cin>>level;
}
void displayManagerInfo(){
//displayEmployeeInfo();
cout<<"Manager Level: "<<level<<endl;
}
};
//Derived Developer Class From Employee
class Developer : virtual public Employee{
protected:
int progLang;
public:
void inputDeveloperInfo(){
//inputEmployeeInfo();
cout<<"Enter Programing Language: "<<endl;
cin>>progLang;
}
void displayDeveloperInfo(){
//displayEmployeeInfo();
cout<<"Programing Language: "<<progLang<<endl;
}
};
//DErived class for Teamlead That will display both info manager and developer
class TeamLead : public Manager, public Developer{

public:

void inputInfo(){
inputEmployeeInfo();   // Employee Info
inputManagerInfo();    // Manager Info
inputDeveloperInfo();   //Developer Info
}

void displayInfo(){
cout<<"Team Lead Details: "<<endl;
displayEmployeeInfo(); // Employee Info
displayManagerInfo();  // Manager Info
displayDeveloperInfo();  //Developer Info
}
};

int main() {

TeamLead tl;
tl.inputInfo();
cout<<endl;
tl.displayInfo();

return 0;
}

//OUTPUT:
Enter name:
mohamed
Enter Employee ID:
1222
Enter Manager Level:
7
Enter Programing Language:
java

Team Lead Details:
Name: mohamed
Employee ID: 1222
Manager Level: 7
Programing Language: java
```
```#include <iostream>

using namespace std;
//Hierarchical inheritance
class Shape{

public:
double area(){
return 0.0;
}

void displayShape(){
cout<<"Generic Shape: ";
}
};
//Derived REctangle Class From Shape Class
class Rectangle:public Shape{
double width;
double length;

public:
//You can write like this also:
Rectangle(double w, double l){
width = w;
length = l;
}
//Both of them are same
//Rectangle(double w, double l):width(w),length(l){

//}
double AreaRectangle(){
return width * length;
}
void displayRectangleInfo(){
displayShape();
cout<<"Rectangle: \nLength = "<<length<<"\nwidth = "<<width<<"\nArea of Rectangle = "<<AreaRectangle()<<endl;
}
};
//Second Derived Circle class from Shape class
class Circle:public Shape{

double radius;

public:
Circle(double r):radius(r){

}
double AreaCircle(){
return 3.14 * radius * radius;
}
void displayCircleInfo(){
displayShape();
cout<<"Circle: \nRadius = "<<radius<<"\nArea of Circle = "<<AreaCircle()<<endl;
}
};
//Third Derived class from Shape
class Triangle:public Shape {

double base;
double heigth;

public:
Triangle(double b, double h):base(b),heigth(h){

}
double AreaTriangle(){
return 0.5 * base * heigth;
}
void displayTriangleInfo(){
displayShape();
cout<<"Triangle: \nBase = "<<base<<"\nHeigth = "<<heigth<<"\nArea of Triangle = "<<AreaTriangle()<<endl;
}
};

int main() {
Rectangle rect(10.2, 20.2);
rect.displayRectangleInfo();
cout<<endl;
Circle c(10);
c.displayCircleInfo();
cout<<endl;
Triangle tri(10.2, 10.1);
tri.displayTriangleInfo();

return 0;
}
//OUTPUT:
Generic Shape: Rectangle:
Length = 20.2
width = 10.2
Area of Rectangle = 206.04

Generic Shape: Circle:
Radius = 10
Area of Circle = 314

Generic Shape: Triangle:
Base = 10.2
Heigth = 10.1
Area of Triangle = 51.51
```
```Question 1.
#include <iostream>

using namespace std;

class course
{
protected:
int course_code;
string course_name;
course(int cc, string cn)
{
course_code = cc;
course_name = cn;

}
void displayCourseInfo()
{
cout<<"Course code: "<<course_code<<endl;
cout<<"Course name: "<<course_name<<endl;
}
};
class studentCourse:public course
{
public:
int id;
string grade;
studentCourse(int cc, string cn, int ID, string Grade):course(cc, cn)
{
id = ID;
grade = Grade;

}
void displayStudentInfo()
{
displayCourseInfo();
cout<<"ID: "<<id<<endl;
cout<<"Grade: "<<grade<<endl;
}
};
int main()
{
studentCourse s1(202,"OOP II", 20021212, "A");
s1.displayStudentInfo();

cout<<endl;
studentCourse s2(201, "Software Design", 210209327, "A");
s2.displayStudentInfo();
return 0;
}
//OUTPUT:
Course code: 202
Course name: OOP II
ID: 20021212
Grade: A

Course code: 201
Course name: Software Design
ID: 210209327
Grade: A

Question 2.
#include <iostream>
#include <string>
using namespace std;

class Vehicle
{
public:
int max_speed;
int num_wheels;
Vehicle(int speed, int wheels)
{
max_speed = speed;
num_wheels = wheels;
}
void vehicle_info()
{

cout<<"Vehicle Max Speed: "<<max_speed<<endl;
cout<<"Vehicle Wheels: "<<num_wheels<<endl;

}
};
class Car:public Vehicle
{
public:
string car_name;
string car_model;
Car(int speed, int wheels, string cname, string cmodel): Vehicle(speed, wheels)
{
car_name = cname;
car_model = cmodel;
}
void car_info()
{
vehicle_info();
cout<<"Car Name: "<<car_name<<endl;
cout<<"Car Model: "<<car_model<<endl;
}
};

class Motorcycle:public Vehicle
{
public:
string mcar_name;
string mcar_model;
Motorcycle(int speed, int wheels, string mcname, string mcmodel): Vehicle(speed, wheels)
{
mcar_name = mcname;
mcar_model = mcmodel;
}
void Motorcycle_info()
{
vehicle_info();
cout<<"Motorcycle Name: "<<mcar_name<<endl;
cout<<"Motorcycle Model: "<<mcar_model<<endl;
}
};
class ConvertibleCar: public Car, public Motorcycle
{
public:

ConvertibleCar(int speed, int wheels, string cname, string cmodel, string mcname, string mcmodel):
Car(speed, wheels, cname, cmodel), Motorcycle(speed, wheels, mcname, mcmodel)
{}
void ConvertibleCar_info()
{
car_info();
cout<<endl;
Motorcycle_info();
}
};
int main()
{
Car car(200, 4, "Honda", "Sedan");
Motorcycle bike(180, 2, "Vespa", "Sport");
ConvertibleCar convertible(220, 4, "Convertible Car", "Sport Car", "Convertible Motocycle", "Vespa");

cout << "Car Information:" << endl;
car.car_info();
cout << endl;

cout << "Motorcycle Information:" << endl;
bike.Motorcycle_info();
cout << endl;

cout << "Convertible Car Information:" << endl;
convertible.ConvertibleCar_info();

return 0;
}
//OUTPUT:
Car Information:
Vehicle Max Speed: 200
Vehicle Wheels: 4
Car Name: Honda
Car Model: Sedan

Motorcycle Information:
Vehicle Max Speed: 180
Vehicle Wheels: 2
Motorcycle Name: Vespa
Motorcycle Model: Sport

Convertible Car Information:
Vehicle Max Speed: 220
Vehicle Wheels: 4
Car Name: Convertible Car
Car Model: Sport Car

Vehicle Max Speed: 220
Vehicle Wheels: 4
Motorcycle Name: Convertible Motocycle
Motorcycle Model: Vespa```
```#include <iostream>

using namespace std;

class Father{
int age;
char name[10];

public:
void get();
void show();

};
void Father::get(){
cout<<"Father Name Please: "<<endl;
cin>>name;
cout<<"Father Age Please: "<<endl;
cin>>age;
}
void Father::show(){
cout<<"Father name is: "<<name<<endl;
cout<<"Father Age is: "<<age<<endl;
}

class doughter: public Father{
int age;
char name[10];

public:
void get();
void show();

};
void doughter::get(){
Father::get();
cout<<"doughter name Please: "<<endl;
cin>>name;
cout<<"doughter Age Please: "<<endl;
cin>>age;
}
void doughter::show(){
Father::show();
cout<<"doughter Name is: "<<name<<endl;
cout<<"doughter Age is: "<<age<<endl;
}

class Son: public Father{
int age;
char name[10];

public:
void get();
void show();
};

void Son::get(){
Father::get();
cout<<"Son name Please: "<<endl;
cin>>name;
cout<<"Son Age Please: "<<endl;
cin>>age;

}
void Son::show(){
Father::show();
cout<<"Son name is: "<<name<<endl;
cout<<"Son Age is: "<<age<<endl;
}

int main() {

Son s1;
doughter d1;
s1.get();
d1.get();
s1.show();
d1.show();

return 0;
}
//OUTPUT:
Father Name Please:
ABdi
Father Age Please:
56
Son name Please:
moha
Son Age Please:
23
Father Name Please:
Abdi
Father Age Please:
56
doughter name Please:
aisha
doughter Age Please:
21
Father name is: ABdi
Father Age is: 56
Son name is: moha
Son Age is: 23
Father name is: Abdi
Father Age is: 56
doughter Name is: aisha
doughter Age is: 21```
```#include <iostream>

using namespace std;

class Father{
int age;
char name[10];

public:
void get();
void show();

};
void Father::get(){
cout<<"Father Name Please: "<<endl;
cin>>name;
cout<<"Father Age Please: "<<endl;
cin>>age;
}
void Father::show(){
cout<<"Father name is: "<<name<<endl;
cout<<"Father Age is: "<<age<<endl;
}

class Mother{
int age;
char name[10];

public:
void get();
void show();

};
void Mother::get(){
cout<<"Mother name Please: "<<endl;
cin>>name;
cout<<"Mother Age Please: "<<endl;
cin>>age;
}
void Mother::show(){
cout<<"Mother Name is: "<<name<<endl;
cout<<"Mother Age is: "<<age<<endl;

}

class Son: public Father, public Mother{
int age;
char name[10];

public:
void get();
void show();
};

void Son::get(){
Father::get();
Mother::get();
cout<<"Son name Please: "<<endl;
cin>>name;
cout<<"Son Age Please: "<<endl;
cin>>age;

}
void Son::show(){
Father::show();
Mother::show();
cout<<"Son name is: "<<name<<endl;
cout<<"Son Age is: "<<age<<endl;
}

int main() {

Son s;
s.get();
s.show();

return 0;
}
//OUTPUT:
Father Name Please:
Abdi
Father Age Please:
54
Mother name Please:
Qamar
Mother Age Please:
37
Son name Please:
Moahmed
Son Age Please:
23
Father name is: Abdi
Father Age is: 54
Mother Name is: Qamar
Mother Age is: 37
Son name is: Moahmed
Son Age is: 23```
```#include <iostream>

using namespace std;

class worker{
int age;
char name[10];

public:
void get();
void show();

};
void worker::get(){
cout<<"Your Name Please: "<<endl;
cin>>name;
cout<<"Your Age Please: "<<endl;
cin>>age;
}
void worker::show(){
cout<<"My name is: "<<name<<endl;
cout<<"My Age is: "<<age<<endl;
}

class manager:public worker{
int now;

public:
void get();
void show();

};
void manager::get(){
worker::get();
cout<<"Num of workers are: "<<endl;
cin>>now;
}
void manager::show(){
worker::show();
cout<<"Num of workers are: "<<now<<endl;
}

class ceo: public manager{
int nom;

public:
void get();
void show();
void print();
};

void ceo::get(){
manager::get();
cout<<"Num of managers are: "<<endl;
cin>>nom;
}
void ceo::show(){
manager::show();
cout<<"Num of managers are: "<<nom<<endl;
}

int main() {

worker w1;
manager m1;
ceo c1;
c1.get();
c1.show();

return 0;
}
//OUTPUT:

Your Name Please:
moha
Your Age Please:
45
Num of workers are:
787
Num of managers are:
897
My name is: moha
My Age is: 45
Num of workers are: 787
Num of managers are: 897
```
```#include <iostream>

using namespace std;

class worker{
int age;
char name[10];

public:
void get();
void show();

};
void worker::get(){
cout<<"Your Name Please: "<<endl;
cin>>name;
cout<<"Your Age Please: "<<endl;
cin>>age;
}
void worker::show(){
cout<<"My name is: "<<name<<endl;
cout<<"My Age is: "<<age<<endl;
}

class manager: public worker{
int now;

public:
void get();
void show();

};
void manager::get(){
worker::get();
cout<<"Num of workers are: "<<endl;
cin>>now;
}
void manager::show(){
worker::show();
cout<<"Num of workers are: "<<now<<endl;
}

int main() {

worker w1;
manager m1;
m1.get();
m1.show();

return 0;
}

//Output:
Your Name Please:
moha
Your Age Please:
34
Num of workers are:
67
My name is: moha
My Age is: 34
Num of workers are: 67```
```void ComponentGraphics::UpdateBackground(GLFWwindow* window, Shader shader, ComponentCamera* camera, glm::vec3 difference)
{
if (camera->getlockParallax() == false)
{
if (difference[0] > 0.0001f) //right
{
posX -= backgroundSpeed;
}
if (difference[0] < -0.0001f) //left
{
posX += backgroundSpeed;
}
}
//96.0f / 50.0f, 84.0f / 50.0f
float CurrentCameraX = camera->getCameraPosition().x;
UpdateGraphics(0.0001, window, shader, camera, ConvertTo4x4Affine(AffineScaleMatrix(96.0f / 50.0f, 84.0f / 50.0f) * AffineTranslationMatrix(posX, posY)), "NoCamX");
}

void ComponentGraphics::setBackgroundSpeedFromFile(Stream stream)
{
backgroundSpeed = StreamReadFloat(stream);
}

void ComponentGraphics::setBackgroundSpeed(float speed)
{
backgroundSpeed = speed;
}

void ComponentGraphics::setPosFromFile(Stream stream)
{
posX = StreamReadFloat(stream);
posY = StreamReadFloat(stream);
}```
```//------------------------------------------------------------------------------
/*!
\file	ComponentCamera.cpp
\main author: Mary (m.khuu) Camera movement : Riti
\par	Copyright © 2021 DigiPen (USA) Corporation.
\brief
\reference http://www.opengl-tutorial.org/beginners-tutorials/tutorial-6-keyboard-and-mouse/
*/
//------------------------------------------------------------------------------
#pragma once

//------------------------------------------------------------------------------
// Includes:
//------------------------------------------------------------------------------
#include "ComponentCamera.h"

ComponentCamera::ComponentCamera(void)
{
ModelMatrix = mat4(0.0f);
ViewMatrix = mat4(1.0f);
ProjectionMatrix = mat4(0.0f);
MVPmatrix = mat4(0.0f);

position = glm::vec3(0.0f, 0.0f, 1.0f);

cameraBoundariesMax = glm::vec3(0.0f, 0.0f, 1.0f);
cameraBoundariesMin = glm::vec3(0.0f, 0.0f, 1.0f);
cameraSize = glm::vec3(0.0f, 0.0f, 1.0f);
cameraSpeed = glm::vec3(0.45f, 0.35f, 0.0f);

horizontalAngle = 3.14f;
verticalAngle = 0.0f;

lockParallax = 0;

lastTime = 0;
}

glm::mat4 ComponentCamera::cameraInput(GLFWwindow* window)
{
double currentTime = glfwGetTime();
float deltaTime = float(currentTime - lastTime);

// Direction : Spherical coordinates to Cartesian coordinates conversion
glm::vec3 direction(
cos(verticalAngle) * sin(horizontalAngle),
sin(verticalAngle),
cos(verticalAngle) * cos(horizontalAngle)
);

// Right vector
glm::vec3 right = glm::vec3(
sin(horizontalAngle - 3.14f / 2.0f),
0,
cos(horizontalAngle - 3.14f / 2.0f)
);

// Up vector
glm::vec3 up = glm::cross(right, direction);

//vertical movements currently move diagonally
if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS)
{
position += deltaTime * cameraSpeed[1];
position -= right * deltaTime * cameraSpeed[1];
}
if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS)
{
position -= deltaTime * cameraSpeed[1];
position += right * deltaTime * cameraSpeed[1];
}

if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS)
{
position += right * deltaTime * cameraSpeed[0];
}
if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS)
{
position -= right * deltaTime * cameraSpeed[0];
}

ProjectionMatrix = glm::ortho((-cameraSize.x / 2), (cameraSize.x / 2), -(cameraSize.y / 2), (cameraSize.y / 2), 0.0f, 100.0f);

ViewMatrix = glm::lookAt(position, position + direction, up);
ModelMatrix = glm::mat4(1.0f);

lastTime = currentTime;
MVPmatrix = (ProjectionMatrix * ViewMatrix * ModelMatrix);
return MVPmatrix; //returns MVP matrix
}

glm::mat4 ComponentCamera::tieCameraToPlayer(GLFWwindow* window, glm::vec3 playerPos)
{
setlockParallax(false);
glm::vec3 direction(
cos(verticalAngle) * sin(horizontalAngle),
sin(verticalAngle),
cos(verticalAngle) * cos(horizontalAngle)
);

glm::vec3 right = glm::vec3(
sin(horizontalAngle - 3.14f / 2.0f),
0,
cos(horizontalAngle - 3.14f / 2.0f)
);

glm::vec3 up = glm::cross(right, direction);

ProjectionMatrix = glm::ortho((-cameraSize.x / 2), (cameraSize.x / 2), -(cameraSize.y / 2), (cameraSize.y / 2), 0.0f, 100.0f);

vec3 CamPos = getCameraPosition();
CamPos.x = playerPos.x;
CamPos.y = playerPos.y;

if (CamPos.x  - (cameraSize.x / 2) < cameraBoundariesMin[0])
{
CamPos.x = cameraBoundariesMin[0] + (cameraSize.x / 2);
}
if (CamPos.x + (cameraSize.x / 2) > cameraBoundariesMax[0])
{
CamPos.x = cameraBoundariesMax[0] -(cameraSize.x / 2);
}
if (CamPos.y < cameraBoundariesMin[1])
{
CamPos.y = cameraBoundariesMin[1];
}

//uncommented to always lock the center of camera to player
//when player goes up

if (CamPos.y > cameraBoundariesMax[1])
{
CamPos.y = cameraBoundariesMax[1];
}

setCameraPosition(CamPos);
ViewMatrix = glm::lookAt(position, position + direction, up);

ModelMatrix = glm::mat4(1.0f);

MVPmatrix = (ProjectionMatrix * ViewMatrix * ModelMatrix);
return MVPmatrix; //returns MVP matrix
}

void ComponentCamera::UpdateCamera(GLFWwindow* window, Shader shader, glm::vec3 position)
{
shader.use();
if (position != glm::vec3(0))
{
GLuint MatrixID = glGetUniformLocation(shader.ID, "transformation");
//glm::matddddd4 MVP = cameraInput(window);
glm::mat4 MVP = tieCameraToPlayer(window, position);
glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);
}
}

glm::mat4 ComponentCamera::getModelMatrix()
{
return ModelMatrix;
}

glm::mat4 ComponentCamera::getViewMatrix()
{
return ViewMatrix;
}

glm::mat4 ComponentCamera::getProjectionMatrix()
{
return ProjectionMatrix;
}

glm::mat4 ComponentCamera::getMVPmatrix()
{
return MVPmatrix;
}

glm::vec3 ComponentCamera::getCameraBoundariesMin()
{
return cameraBoundariesMin;
}

glm::vec3 ComponentCamera::getCameraBoundariesMax()
{
return cameraBoundariesMax;
}

glm::vec3 ComponentCamera::getCameraPosition()
{
return position;
}

glm::vec3 ComponentCamera::getCameraSize()
{
return cameraSize;
}

bool ComponentCamera::getlockParallax()
{
return lockParallax;
}

void ComponentCamera::setCameraBoundariesMin(glm::vec3 boundaries)
{
cameraBoundariesMin = boundaries;
}

void ComponentCamera::setCameraBoundariesMax(glm::vec3 boundaries)
{
cameraBoundariesMax = boundaries;
}

void ComponentCamera::setCameraPosition(glm::vec3 P)
{
position = P;
}

void ComponentCamera::setCameraSize(glm::vec3 S)
{
cameraSize = S;
}

void ComponentCamera::setCameraSpeed(float speedX, float speedY)
{
cameraSpeed[0] = speedX;
cameraSpeed[1] = speedY;
}

void ComponentCamera::setCameraSpeedVec(glm::vec3 speed)
{
cameraSpeed = speed;
}

void ComponentCamera::setMVPmatrix(glm::mat4 matrix)
{
MVPmatrix = matrix;
}

void ComponentCamera::setlockParallax(bool value)
{
lockParallax = value;
}```
```// ---------------------------------------------------------------------------
// Project Name		:	Nook
// File Name		:	LevelSelect.c
// Author			:	Mary Khuu
// Creation Date	:	19 Mar 2021
// Purpose			:	Level Select
//
// All content © 2021 DigiPen (USA) Corporation, all rights reserved.
// ---------------------------------------------------------------------------

#include "framework.h"
#include "AEEngine.h"
#include "Audio.h"
#include "GameStateManager.h"
#include "Sprite.h"
#include "object_data.h"

#include "LevelSelect.h"

//------------------------------------------------------------------------------
// Private Constants:
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Private Structures:
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Public Variables:
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Private Variables:
//------------------------------------------------------------------------------

static vec2 backgroundSize = { 1670.0f, 564.0f };
static vec2 buttonSize = { 100.0f, 30.0f };
static vec2 textSize = { 150.0f, 50.0f };
static vec2 iconSize = { 30.0f, 30.0f };
static vec2 menuPos = { 0.0f, 200.0f };
static vec2 tutorialPos = { 0.0f, 100.0f };
static vec2 level1Pos = { 0.0f, 0.0f };
static vec2 level2Pos = { 0.0f, -100.0f };
static vec2 level3Pos = { 0.0f, -200.0f };

static signed long mouseX, mouseY;
static float mouseInWorldX, mouseInWorldY;

static AEGfxVertexList* bgMesh;
static AEGfxVertexList* buttonMesh;
static AEGfxVertexList* fontMesh;
static AEGfxVertexList* iconMesh;
static AEGfxVertexList* numMesh;

static AEGfxTexture* bgTexture;
static AEGfxTexture* buttonTexture;
static AEGfxTexture* fontTexture;
static AEGfxTexture* iconTexture;
static AEGfxTexture* numTexture;

static TextureOffset numOffsets[10];
static TextureOffset fontOffsets[30];
static int* currentfontOffset = 0;
static int currfontFrame = 0;
static float* fontTime;

//------------------------------------------------------------------------------
// Private Function Declarations:
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Public Functions:
//------------------------------------------------------------------------------

void LevelSelectLoad()
{
/*mesh for bg*/
AEGfxMeshStart();

AEGfxTriAdd(
-backgroundSize.x, -backgroundSize.y, 0xFF00FF00, 0.0f, 1.0f,
backgroundSize.x, -backgroundSize.y, 0xFF00FF00, 1.0f, 1.0f,
-backgroundSize.x, backgroundSize.y, 0xFF00FF00, 0.0f, 0.0f);

AEGfxTriAdd(
backgroundSize.x, -backgroundSize.y, 0xFF00FF00, 1.0f, 1.0f,
backgroundSize.x, backgroundSize.y, 0xFF00FF00, 1.0f, 0.0f,
-backgroundSize.x, backgroundSize.y, 0xFF00FF00, 0.0f, 0.0f);

bgMesh = AEGfxMeshEnd();
AE_ASSERT_MESG(bgMesh, "Failed to create button!");

bgTexture = AEGfxTextureLoad("Assets/CityscapeGrey.png");
AE_ASSERT_MESG(bgTexture, "Failed to create pTex!!");

/*mesh for buttons: green*/
AEGfxMeshStart();

AEGfxTriAdd(
-buttonSize.x, -buttonSize.y, 0xFF00FF00, 0.0f, 1.0f,
buttonSize.x, -buttonSize.y, 0xFF00FF00, 1.0f, 1.0f,
-buttonSize.x, buttonSize.y, 0xFF00FF00, 0.0f, 0.0f);

AEGfxTriAdd(
buttonSize.x, -buttonSize.y, 0xFF00FF00, 1.0f, 1.0f,
buttonSize.x, buttonSize.y, 0xFF00FF00, 1.0f, 0.0f,
-buttonSize.x, buttonSize.y, 0xFF00FF00, 0.0f, 0.0f);

buttonMesh = AEGfxMeshEnd();
AE_ASSERT_MESG(buttonMesh, "Failed to create button!");

buttonTexture = AEGfxTextureLoad("Assets/NookButtonBright.png");
AE_ASSERT_MESG(buttonTexture, "Failed to create texture!");

/*mesh for hover icon*/
iconMesh = createQuadMesh(iconSize.x, iconSize.y, 1.0f, 1.0f, "yarn");

iconTexture = AEGfxTextureLoad("Assets/TempHover.png");
AE_ASSERT_MESG(iconTexture, "Failed to create texture!");

/*mesh for text*/
fontMesh = createQuadMesh(15.0f, 15.0f, 1.0 / 5, 1.0f / 6, "alphabets");

fontTexture = AEGfxTextureLoad("Assets/NookFontSheet_alphabet.png");
AE_ASSERT_MESG(fontTexture, "Failed to create texture!");

fontOffsets[0].mX = 0.0f;			    fontOffsets[0].mY = 0.0f / 6;  //A
fontOffsets[1].mX = 1.0f / 5;		    fontOffsets[1].mY = 0.0f / 6;  //B
fontOffsets[2].mX = 2.0f / 5;			fontOffsets[2].mY = 0.0f / 6;  //C
fontOffsets[3].mX = 3.0f / 5;			fontOffsets[3].mY = 0.0f / 6;  //D
fontOffsets[4].mX = 4.0f / 5;			fontOffsets[4].mY = 0.0f / 6;  //E

fontOffsets[5].mX = 0.0f;			    fontOffsets[5].mY = 1.0f / 6;  //F
fontOffsets[6].mX = 1.0f / 5;		    fontOffsets[6].mY = 1.0f / 6;  //G
fontOffsets[7].mX = 2.0f / 5;			fontOffsets[7].mY = 1.0f / 6;  //H
fontOffsets[8].mX = 3.0f / 5;			fontOffsets[8].mY = 1.0f / 6;  //I
fontOffsets[9].mX = 4.0f / 5;			fontOffsets[9].mY = 1.0f / 6;  //J

fontOffsets[10].mX = 0.0f;			    fontOffsets[10].mY = 2.0f / 6;  //K
fontOffsets[11].mX = 1.0f / 5;		    fontOffsets[11].mY = 2.0f / 6;  //L
fontOffsets[12].mX = 2.0f / 5;			fontOffsets[12].mY = 2.0f / 6;  //M
fontOffsets[13].mX = 3.0f / 5;			fontOffsets[13].mY = 2.0f / 6;  //N
fontOffsets[14].mX = 4.0f / 5;			fontOffsets[14].mY = 2.0f / 6;  //O

fontOffsets[15].mX = 0.0f;			    fontOffsets[15].mY = 3.0f / 6;  //P
fontOffsets[16].mX = 1.0f / 5;		    fontOffsets[16].mY = 3.0f / 6;  //Q
fontOffsets[17].mX = 2.0f / 5;			fontOffsets[17].mY = 3.0f / 6;  //R
fontOffsets[18].mX = 3.0f / 5;			fontOffsets[18].mY = 3.0f / 6;  //S
fontOffsets[19].mX = 4.0f / 5;			fontOffsets[19].mY = 3.0f / 6;  //T

fontOffsets[20].mX = 0.0f;			    fontOffsets[20].mY = 4.0f / 6;  //U
fontOffsets[21].mX = 1.0f / 5;		    fontOffsets[21].mY = 4.0f / 6;  //V
fontOffsets[22].mX = 2.0f / 5;			fontOffsets[22].mY = 4.0f / 6;  //W
fontOffsets[23].mX = 3.0f / 5;			fontOffsets[23].mY = 4.0f / 6;  //X
fontOffsets[24].mX = 4.0f / 5;			fontOffsets[24].mY = 4.0f / 6;  //Y

fontOffsets[25].mX = 0.0f;			    fontOffsets[25].mY = 5.0f / 6;   //Z
fontOffsets[26].mX = 1.0f / 5;		    fontOffsets[26].mY = 5.0f / 6;  //blank (1)
fontOffsets[27].mX = 2.0f / 5;			fontOffsets[27].mY = 5.0f / 6;  //blank (2)
fontOffsets[28].mX = 3.0f / 5;			fontOffsets[28].mY = 5.0f / 6;  //blank (3)
fontOffsets[29].mX = 4.0f / 5;			fontOffsets[29].mY = 5.0f / 6;  //blank (4)

/*mesh for numbers*/
numMesh = createQuadMesh(15.0f, 15.0f, 1.0 / 3, 1.0f / 4, "numbers");

numTexture = AEGfxTextureLoad("Assets/NookFontSheet_numbers.png");
AE_ASSERT_MESG(numTexture, "Failed to create texture!");

numOffsets[0].mX = 0.0f;			    numOffsets[0].mY = 0.0f / 4;  //0
numOffsets[1].mX = 1.0f / 3;		    numOffsets[1].mY = 0.0f / 4;  //1
numOffsets[2].mX = 2.0f / 3;			numOffsets[2].mY = 0.0f / 4;  //2

numOffsets[3].mX = 0.0f;			    numOffsets[3].mY = 1.0f / 4;  //3
numOffsets[4].mX = 1.0f / 3;			numOffsets[4].mY = 1.0f / 4;  //4
numOffsets[5].mX = 2.0f / 3;			numOffsets[5].mY = 1.0f / 4;  //5

numOffsets[6].mX = 0.0f;		        numOffsets[6].mY = 2.0f / 4;  //6
numOffsets[7].mX = 1.0f / 3;			numOffsets[7].mY = 2.0f / 4;  //7
numOffsets[8].mX = 2.0f / 3;			numOffsets[8].mY = 2.0f / 4;  //8

numOffsets[9].mX = 0.0f / 3;			numOffsets[9].mY = 3.0f / 4;  //9
}

void LevelSelectInit()
{
AEGfxSetBackgroundColor(1.0f, 1.0f, 1.0f);
AEGfxSetBlendMode(AE_GFX_BM_BLEND);
}

void LevelSelectUpdate(float dt)
{
/* Tell the compiler that the 'dt' variable is unused. */
UNREFERENCED_PARAMETER(dt);

/*draw background*/
AEGfxSetRenderMode(AE_GFX_RM_TEXTURE);
AEGfxTextureSet(bgTexture, 0, 0);
AEGfxSetTransparency(1.0f);
AEGfxSetPosition(-250.0f, 0.0f);
AEGfxMeshDraw(bgMesh, AE_GFX_MDM_TRIANGLES);

//draw menu button
AEGfxSetPosition(menuPos.x, menuPos.y);
AEGfxTextureSet(buttonTexture, 0, 0); // no texture
AEGfxMeshDraw(buttonMesh, AE_GFX_MDM_TRIANGLES);

//draw tutorial button
AEGfxSetPosition(tutorialPos.x, tutorialPos.y);
AEGfxTextureSet(buttonTexture, 0, 0); // no texture
AEGfxMeshDraw(buttonMesh, AE_GFX_MDM_TRIANGLES);

//draw level1 button
AEGfxSetPosition(level1Pos.x, level1Pos.y);
AEGfxTextureSet(buttonTexture, 0, 0); // no texture
AEGfxMeshDraw(buttonMesh, AE_GFX_MDM_TRIANGLES);

//draw level2 button
AEGfxSetPosition(level2Pos.x, level2Pos.y);
AEGfxTextureSet(buttonTexture, 0, 0); // no texture
AEGfxMeshDraw(buttonMesh, AE_GFX_MDM_TRIANGLES);

//draw level3 button
AEGfxSetPosition(level3Pos.x, level3Pos.y);
AEGfxTextureSet(buttonTexture, 0, 0); // no texture
AEGfxMeshDraw(buttonMesh, AE_GFX_MDM_TRIANGLES);

/*MENU*/
AEGfxSetPosition(menuPos.x - 45.0f, menuPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[12].mX, fontOffsets[12].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(menuPos.x - 13.0f, menuPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[4].mX, fontOffsets[4].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(menuPos.x + 15.0f, menuPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[13].mX, fontOffsets[13].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(menuPos.x + 45.0f, menuPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[20].mX, fontOffsets[20].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

/*MENU - end*/

/*TUTORIAL*/
AEGfxSetPosition(tutorialPos.x - 86.0f, tutorialPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[19].mX, fontOffsets[19].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(tutorialPos.x - 58.0f, tutorialPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[20].mX, fontOffsets[20].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(tutorialPos.x - 30.0f, tutorialPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[19].mX, fontOffsets[19].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(tutorialPos.x, tutorialPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[14].mX, fontOffsets[14].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(tutorialPos.x + 30.0f, tutorialPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[17].mX, fontOffsets[17].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(tutorialPos.x + 46.0f, tutorialPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[8].mX, fontOffsets[8].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(tutorialPos.x + 65.0f, tutorialPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[0].mX, fontOffsets[0].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(tutorialPos.x + 90.0f, tutorialPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[11].mX, fontOffsets[11].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

/*TUTORIAL - end*/

/*LEVEL 1*/
AEGfxSetPosition(level1Pos.x - 85.0f, level1Pos.y);
AEGfxTextureSet(fontTexture, fontOffsets[11].mX, fontOffsets[11].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(level1Pos.x - 60.0f, level1Pos.y);
AEGfxTextureSet(fontTexture, fontOffsets[4].mX, fontOffsets[4].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(level1Pos.x - 34.0f, level1Pos.y);
AEGfxTextureSet(fontTexture, fontOffsets[21].mX, fontOffsets[21].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(level1Pos.x - 5.0f, level1Pos.y);
AEGfxTextureSet(fontTexture, fontOffsets[4].mX, fontOffsets[4].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(level1Pos.x + 17.5f, level1Pos.y);
AEGfxTextureSet(fontTexture, fontOffsets[11].mX, fontOffsets[11].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(level1Pos.x + 85.0f, level1Pos.y);
AEGfxTextureSet(numTexture, numOffsets[1].mX, numOffsets[1].mY, 0.0f); // 1
AEGfxMeshDraw(numMesh, AE_GFX_MDM_TRIANGLES);

/*LEVEL 1 - end*/

/*LEVEL 2*/
AEGfxSetPosition(level2Pos.x - 85.0f, level2Pos.y);
AEGfxTextureSet(fontTexture, fontOffsets[11].mX, fontOffsets[11].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(level2Pos.x - 60.0f, level2Pos.y);
AEGfxTextureSet(fontTexture, fontOffsets[4].mX, fontOffsets[4].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(level2Pos.x - 34.0f, level2Pos.y);
AEGfxTextureSet(fontTexture, fontOffsets[21].mX, fontOffsets[21].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(level2Pos.x - 5.0f, level2Pos.y);
AEGfxTextureSet(fontTexture, fontOffsets[4].mX, fontOffsets[4].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(level2Pos.x + 17.5f, level2Pos.y);
AEGfxTextureSet(fontTexture, fontOffsets[11].mX, fontOffsets[11].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(level2Pos.x + 85.0f, level2Pos.y);
AEGfxTextureSet(numTexture, numOffsets[2].mX, numOffsets[2].mY, 0.0f); // 2
AEGfxMeshDraw(numMesh, AE_GFX_MDM_TRIANGLES);

/*LEVEL 2 - end*/

/*LEVEL 3*/
AEGfxSetPosition(level3Pos.x - 85.0f, level3Pos.y);
AEGfxTextureSet(fontTexture, fontOffsets[11].mX, fontOffsets[11].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(level3Pos.x - 60.0f, level3Pos.y);
AEGfxTextureSet(fontTexture, fontOffsets[4].mX, fontOffsets[4].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(level3Pos.x - 34.0f, level3Pos.y);
AEGfxTextureSet(fontTexture, fontOffsets[21].mX, fontOffsets[21].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(level3Pos.x - 5.0f, level3Pos.y);
AEGfxTextureSet(fontTexture, fontOffsets[4].mX, fontOffsets[4].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(level3Pos.x + 17.5f, level3Pos.y);
AEGfxTextureSet(fontTexture, fontOffsets[11].mX, fontOffsets[11].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(level3Pos.x + 85.0f, level3Pos.y);
AEGfxTextureSet(numTexture, numOffsets[3].mX, numOffsets[3].mY, 0.0f); // 3
AEGfxMeshDraw(numMesh, AE_GFX_MDM_TRIANGLES);

/*LEVEL 3 - end*/

/*get the mouse position*/
AEInputGetCursorPosition(&mouseX, &mouseY);
AEGfxConvertScreenCoordinatesToWorld(mouseX, mouseY, &mouseInWorldX, &mouseInWorldY);

/*if menu is hovered*/
if ((mouseInWorldX > (menuPos.x - buttonSize.x) && mouseInWorldX < (menuPos.x + buttonSize.x)) &&
(mouseInWorldY > (menuPos.y - buttonSize.y) && mouseInWorldY < (menuPos.y + buttonSize.y)))
{
// Hover texture
AEGfxSetRenderMode(AE_GFX_RM_TEXTURE);
AEGfxSetPosition(menuPos.x - 140.0f, menuPos.y);
AEGfxTextureSet(iconTexture, 0.0f, 0.0f);
AEGfxMeshDraw(iconMesh, AE_GFX_MDM_TRIANGLES);

if (AEInputCheckTriggered(RI_MOUSE_LEFT_BUTTON_DOWN))
{
GameStateManagerSetNextState(Menu);
}
}

/*if tutorial is hovered*/
if ((mouseInWorldX > (tutorialPos.x - buttonSize.x) && mouseInWorldX < (tutorialPos.x + buttonSize.x)) &&
(mouseInWorldY > (tutorialPos.y - buttonSize.y) && mouseInWorldY < (tutorialPos.y + buttonSize.y)))
{
// Hover texture
AEGfxSetRenderMode(AE_GFX_RM_TEXTURE);
AEGfxSetPosition(tutorialPos.x - 140.0f, tutorialPos.y);
AEGfxTextureSet(iconTexture, 0.0f, 0.0f);
AEGfxMeshDraw(iconMesh, AE_GFX_MDM_TRIANGLES);

if (AEInputCheckTriggered(RI_MOUSE_LEFT_BUTTON_DOWN))
{
GameStateManagerSetNextState(Tutorial);
}
}

/*if level1 is hovered*/
if ((mouseInWorldX > (level1Pos.x - buttonSize.x) && mouseInWorldX < (level1Pos.x + buttonSize.x)) &&
(mouseInWorldY > (level1Pos.y - buttonSize.y) && mouseInWorldY < (level1Pos.y + buttonSize.y)))
{
// Hover texture
AEGfxSetRenderMode(AE_GFX_RM_TEXTURE);
AEGfxSetPosition(level1Pos.x - 140.0f, level1Pos.y);
AEGfxTextureSet(iconTexture, 0.0f, 0.0f);
AEGfxMeshDraw(iconMesh, AE_GFX_MDM_TRIANGLES);

if (AEInputCheckTriggered(RI_MOUSE_LEFT_BUTTON_DOWN))
{
GameStateManagerSetNextState(Demo);
}
}

/*if level2 is hovered*/
if ((mouseInWorldX > (level2Pos.x - buttonSize.x) && mouseInWorldX < (level2Pos.x + buttonSize.x)) &&
(mouseInWorldY > (level2Pos.y - buttonSize.y) && mouseInWorldY < (level2Pos.y + buttonSize.y)))
{
// Hover texture
AEGfxSetRenderMode(AE_GFX_RM_TEXTURE);
AEGfxSetPosition(level2Pos.x - 140.0f, level2Pos.y);
AEGfxTextureSet(iconTexture, 0.0f, 0.0f);
AEGfxMeshDraw(iconMesh, AE_GFX_MDM_TRIANGLES);

if (AEInputCheckTriggered(RI_MOUSE_LEFT_BUTTON_DOWN))
{
GameStateManagerSetNextState(Level2);
}
}

/*if level3 is hovered*/
if ((mouseInWorldX > (level3Pos.x - buttonSize.x) && mouseInWorldX < (level3Pos.x + buttonSize.x)) &&
(mouseInWorldY > (level3Pos.y - buttonSize.y) && mouseInWorldY < (level3Pos.y + buttonSize.y)))
{
// Hover texture
AEGfxSetRenderMode(AE_GFX_RM_TEXTURE);
AEGfxSetPosition(level3Pos.x - 140.0f, level3Pos.y);
AEGfxTextureSet(iconTexture, 0.0f, 0.0f);
AEGfxMeshDraw(iconMesh, AE_GFX_MDM_TRIANGLES);

if (AEInputCheckTriggered(RI_MOUSE_LEFT_BUTTON_DOWN))
{
GameStateManagerSetNextState(Level3);
}
}
}

void LevelSelectShutdown()
{
AudioCleanup();
}

void LevelSelectUnload()
{
// Unload all textures.
AEGfxTextureUnload(buttonTexture);
AEGfxTextureUnload(fontTexture);
AEGfxTextureUnload(bgTexture);
AEGfxTextureUnload(iconTexture);
AEGfxTextureUnload(numTexture);

// Free all meshes.
AEGfxMeshFree(buttonMesh);
AEGfxMeshFree(fontMesh);
AEGfxMeshFree(bgMesh);
AEGfxMeshFree(iconMesh);
AEGfxMeshFree(numMesh);
}

//------------------------------------------------------------------------------
// Private Functions:
//------------------------------------------------------------------------------```
```//if the last time player moved was left
if (!AEInputCheckCurr("A") && lastPlayerDir == 1 && isWalking == 0)
{
//flip the sprite
AEGfxTextureSet(playerIdleTexture, 0.0f, 0.0f);
AEGfxSetFullTransform(curr->pos.x, curr->pos.y, 0.0f, -(curr->width * tile_dim), curr->height * tile_dim);
isWalking = 0;
}```
```/*get the mouse x and y position*/
AEInputGetCursorPosition(&mouseX, &mouseY);
AEGfxConvertScreenCoordinatesToWorld(mouseX, mouseY, &mouseInWorldX, &mouseInWorldY);

/*only draw line if it's the wall and left click/hold on mouse occurs*/
if ((mouseInWorldX > (wallX - xHalfSize) && mouseInWorldX < (wallX + xHalfSize)) &&
(mouseInWorldY > (wallY - yHalfSize) && mouseInWorldY < (wallY + yHalfSize)) &&
(AEInputCheckCurr(RI_MOUSE_LEFT_BUTTON_DOWN)))
{
/*mesh for line, needs to be updated with loop*/
AEGfxMeshStart();

AEGfxVertexAdd(playerX + xHalfSize, playerY, 0xFFFF0000, 0.0f, 0.0f);
AEGfxVertexAdd(mouseInWorldX, mouseInWorldY, 0xFFFF0000, 0.0f, 0.0f);

meshLine = AEGfxMeshEnd();
AE_ASSERT_MESG(meshLine, "Failed to create line!");

/*draw line*/
AEGfxSetRenderMode(AE_GFX_RM_COLOR);
AEGfxSetPosition(0.0f, 0.0f);
AEGfxMeshDraw(meshLine, AE_GFX_MDM_LINES_STRIP);
}```
```// ---------------------------------------------------------------------------
// Project Name		:	Nook
// File Name		:	Menu.c
// Author			:	Rey Rosario, Mary Khuu
// Creation Date	:	25 Jan 2021
// Purpose			:	Main Menu
//
// All content © 2021 DigiPen (USA) Corporation, all rights reserved.
// ---------------------------------------------------------------------------

#include "framework.h"
#include "AEEngine.h"
#include "Audio.h"
#include "GameStateManager.h"
#include "object_data.h"
#include "Sprite.h"

#include "Menu.h"

//------------------------------------------------------------------------------
// Private Constants:
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Private Structures:
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Public Variables:
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Private Variables:
//------------------------------------------------------------------------------

static vec2 backgroundSize = { 1670.0f, 564.0f };
static vec2 buttonSize = { 100.0f, 30.0f };
static vec2 titleSize = { 150.0f, 50.0f };
static vec2 iconSize = { 30.0f, 30.0f };
static vec2 levelPos = { 0.0f, 0.0f };
static vec2 creditsPos = { 0.0f, -100.0f };
static vec2 exitPos = { 0.0f, -200.0f };
static vec2 titlePos = { 0.0f, 150.0f };

static signed long mouseX, mouseY;
static float mouseInWorldX, mouseInWorldY;

static AEGfxVertexList* buttonMesh;
static AEGfxVertexList* titleMesh;
static AEGfxVertexList* bgMesh;
static AEGfxVertexList* fontMesh;
static AEGfxVertexList* iconMesh;

static AEGfxTexture* bgTexture;
static AEGfxTexture* buttonTexture;
static AEGfxTexture* titleTexture;
static AEGfxTexture* fontTexture;
static AEGfxTexture* iconTexture;

TextureOffset titleOffsets[6];
int* currentTitleOffset = 0;
int currTitleFrame = 0;
float* titleTime;

static TextureOffset fontOffsets[30];
static int* currentfontOffset = 0;
static int currfontFrame = 0;
static float* fontTime;

static float bgMusicTimer;

//------------------------------------------------------------------------------
// Private Function Declarations:
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Public Functions:
//------------------------------------------------------------------------------

void MenuLoad()
{
/*mesh for bg*/
AEGfxMeshStart();

AEGfxTriAdd(
-backgroundSize.x, -backgroundSize.y, 0xFF00FF00, 0.0f, 1.0f,
backgroundSize.x, -backgroundSize.y, 0xFF00FF00, 1.0f, 1.0f,
-backgroundSize.x, backgroundSize.y, 0xFF00FF00, 0.0f, 0.0f);

AEGfxTriAdd(
backgroundSize.x, -backgroundSize.y, 0xFF00FF00, 1.0f, 1.0f,
backgroundSize.x, backgroundSize.y, 0xFF00FF00, 1.0f, 0.0f,
-backgroundSize.x, backgroundSize.y, 0xFF00FF00, 0.0f, 0.0f);

bgMesh = AEGfxMeshEnd();
AE_ASSERT_MESG(bgMesh, "Failed to create button!");

bgTexture = AEGfxTextureLoad("Assets/CityscapeGrey.png");
AE_ASSERT_MESG(bgTexture, "Failed to create pTex!!");

/*mesh for buttons: green*/
AEGfxMeshStart();

AEGfxTriAdd(
-buttonSize.x, -buttonSize.y, 0xFF00FF00, 0.0f, 1.0f,
buttonSize.x, -buttonSize.y, 0xFF00FF00, 1.0f, 1.0f,
-buttonSize.x, buttonSize.y, 0xFF00FF00, 0.0f, 0.0f);

AEGfxTriAdd(
buttonSize.x, -buttonSize.y, 0xFF00FF00, 1.0f, 1.0f,
buttonSize.x, buttonSize.y, 0xFF00FF00, 1.0f, 0.0f,
-buttonSize.x, buttonSize.y, 0xFF00FF00, 0.0f, 0.0f);

buttonMesh = AEGfxMeshEnd();
AE_ASSERT_MESG(buttonMesh, "Failed to create button!");

buttonTexture = AEGfxTextureLoad("Assets/NookButtonBright.png");
AE_ASSERT_MESG(buttonTexture, "Failed to create texture!");

/*mesh for text*/
AEGfxMeshStart();

AEGfxTriAdd(
-titleSize.x, -titleSize.y, 0xFF00FF00, 0.0f, 1.0f / 6,
titleSize.x, -titleSize.y, 0xFF00FF00, 1.0f, 1.0f / 6,
-titleSize.x, titleSize.y, 0xFF00FF00, 0.0f, 0.0f);

AEGfxTriAdd(
titleSize.x, -titleSize.y, 0xFF00FF00, 1.0f, 1.0f / 6,
titleSize.x, titleSize.y, 0xFF00FF00, 1.0f, 0.0f,
-titleSize.x, titleSize.y, 0xFF00FF00, 0.0f, 0.0f);

titleMesh = AEGfxMeshEnd();
AE_ASSERT_MESG(titleMesh, "Failed to create button!");

titleTexture = AEGfxTextureLoad("Assets/NookLogo.png");
AE_ASSERT_MESG(titleTexture, "Failed to create texture!");

titleOffsets[0].mX = 0.0f;			titleOffsets[0].mY = 0.0f;
titleOffsets[1].mX = 0.0f;			titleOffsets[1].mY = 1.0f / 6;
titleOffsets[2].mX = 0.0f;			titleOffsets[2].mY = 2.0f / 6;
titleOffsets[3].mX = 0.0f;			titleOffsets[3].mY = 3.0f / 6;
titleOffsets[4].mX = 0.0f;			titleOffsets[4].mY = 4.0f / 6;
titleOffsets[5].mX = 0.0f;			titleOffsets[5].mY = 5.0f / 6;

/*mesh for hover icon*/
iconMesh = createQuadMesh(iconSize.x, iconSize.y, 1.0f, 1.0f, "yarn");

iconTexture = AEGfxTextureLoad("Assets/TempHover.png");
AE_ASSERT_MESG(iconTexture, "Failed to create texture!");

/*mesh for text*/
fontMesh = createQuadMesh(15.0f, 15.0f, 1.0 / 5, 1.0f / 6, "alphabets");

fontTexture = AEGfxTextureLoad("Assets/NookFontSheet_alphabet.png");
AE_ASSERT_MESG(fontTexture, "Failed to create texture!");

fontOffsets[0].mX = 0.0f;			    fontOffsets[0].mY = 0.0f / 6;  //A
fontOffsets[1].mX = 1.0f / 5;		    fontOffsets[1].mY = 0.0f / 6;  //B
fontOffsets[2].mX = 2.0f / 5;			fontOffsets[2].mY = 0.0f / 6;  //C
fontOffsets[3].mX = 3.0f / 5;			fontOffsets[3].mY = 0.0f / 6;  //D
fontOffsets[4].mX = 4.0f / 5;			fontOffsets[4].mY = 0.0f / 6;  //E

fontOffsets[5].mX = 0.0f;			    fontOffsets[5].mY = 1.0f / 6;  //F
fontOffsets[6].mX = 1.0f / 5;		    fontOffsets[6].mY = 1.0f / 6;  //G
fontOffsets[7].mX = 2.0f / 5;			fontOffsets[7].mY = 1.0f / 6;  //H
fontOffsets[8].mX = 3.0f / 5;			fontOffsets[8].mY = 1.0f / 6;  //I
fontOffsets[9].mX = 4.0f / 5;			fontOffsets[9].mY = 1.0f / 6;  //J

fontOffsets[10].mX = 0.0f;			    fontOffsets[10].mY = 2.0f / 6;  //K
fontOffsets[11].mX = 1.0f / 5;		    fontOffsets[11].mY = 2.0f / 6;  //L
fontOffsets[12].mX = 2.0f / 5;			fontOffsets[12].mY = 2.0f / 6;  //M
fontOffsets[13].mX = 3.0f / 5;			fontOffsets[13].mY = 2.0f / 6;  //N
fontOffsets[14].mX = 4.0f / 5;			fontOffsets[14].mY = 2.0f / 6;  //O

fontOffsets[15].mX = 0.0f;			    fontOffsets[15].mY = 3.0f / 6;  //P
fontOffsets[16].mX = 1.0f / 5;		    fontOffsets[16].mY = 3.0f / 6;  //Q
fontOffsets[17].mX = 2.0f / 5;			fontOffsets[17].mY = 3.0f / 6;  //R
fontOffsets[18].mX = 3.0f / 5;			fontOffsets[18].mY = 3.0f / 6;  //S
fontOffsets[19].mX = 4.0f / 5;			fontOffsets[19].mY = 3.0f / 6;  //T

fontOffsets[20].mX = 0.0f;			    fontOffsets[20].mY = 4.0f / 6;  //U
fontOffsets[21].mX = 1.0f / 5;		    fontOffsets[21].mY = 4.0f / 6;  //V
fontOffsets[22].mX = 2.0f / 5;			fontOffsets[22].mY = 4.0f / 6;  //W
fontOffsets[23].mX = 3.0f / 5;			fontOffsets[23].mY = 4.0f / 6;  //X
fontOffsets[24].mX = 4.0f / 5;			fontOffsets[24].mY = 4.0f / 6;  //Y

fontOffsets[25].mX = 0.0f;			    fontOffsets[25].mY = 5.0f / 6;   //Z
fontOffsets[26].mX = 1.0f / 5;		    fontOffsets[26].mY = 5.0f / 6;  //blank
fontOffsets[27].mX = 2.0f / 5;			fontOffsets[27].mY = 5.0f / 6;  //blank
fontOffsets[28].mX = 3.0f / 5;			fontOffsets[28].mY = 5.0f / 6;  //blank
fontOffsets[29].mX = 4.0f / 5;			fontOffsets[29].mY = 5.0f / 6;  //blank
}

void MenuInit()
{
AEGfxSetBackgroundColor(0.0f, 0.0f, 0.0f);
AEGfxSetBlendMode(AE_GFX_BM_BLEND);

AudioInit();
bgMusicTimer = 1638.0f; // Roughly 27 seconds
}

void MenuUpdate(float dt)
{
/* Tell the compiler that the 'dt' variable is unused. */
UNREFERENCED_PARAMETER(dt);

/*play bg music*/
if (bgMusicTimer == 1638.0f)
{
playSoundAdvanced("Assets/Sounds/Level2Track.mp3", 0.1f);
}

/*reset time for bg music loop*/
if (bgMusicTimer == 0.0f)
{
bgMusicTimer = 1638.0f;
}
else
{
bgMusicTimer--;
}

/*draw background*/
AEGfxSetRenderMode(AE_GFX_RM_TEXTURE);
AEGfxTextureSet(bgTexture, 0, 0);
AEGfxSetTransparency(1.0f);
AEGfxSetPosition(-250.0f, 0.0f);
AEGfxMeshDraw(bgMesh, AE_GFX_MDM_TRIANGLES);

//draw menu button
AEGfxSetPosition(levelPos.x, levelPos.y);
AEGfxTextureSet(buttonTexture, 0, 0); // no texture
AEGfxSetTransparency(1.0f);
AEGfxSetBlendColor(0.0f, 0.0f, 0.0, 0.0f);
AEGfxMeshDraw(buttonMesh, AE_GFX_MDM_TRIANGLES);

//draw replay button
AEGfxSetPosition(creditsPos.x, creditsPos.y);
AEGfxTextureSet(buttonTexture, 0, 0); // no texture
AEGfxMeshDraw(buttonMesh, AE_GFX_MDM_TRIANGLES);

//draw exit button
AEGfxSetPosition(exitPos.x, exitPos.y);
AEGfxTextureSet(buttonTexture, 0, 0); // no texture
AEGfxMeshDraw(buttonMesh, AE_GFX_MDM_TRIANGLES);

/*PLAY*/

AEGfxSetPosition(levelPos.x - 40.0f, levelPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[15].mX, fontOffsets[15].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(levelPos.x - 15.0f, levelPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[11].mX, fontOffsets[11].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(levelPos.x + 10.0f, levelPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[0].mX, fontOffsets[0].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(levelPos.x + 35.0f, levelPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[24].mX, fontOffsets[24].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

/*PLAY - end*/

/*CREDITS*/
AEGfxSetPosition(creditsPos.x - 75.0f, creditsPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[2].mX, fontOffsets[2].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(creditsPos.x - 45.0f, creditsPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[17].mX, fontOffsets[17].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(creditsPos.x - 20.0f, creditsPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[4].mX, fontOffsets[4].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(creditsPos.x + 5.0f, creditsPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[3].mX, fontOffsets[3].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(creditsPos.x + 25.0f, creditsPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[8].mX, fontOffsets[8].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(creditsPos.x + 47.0f, creditsPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[19].mX, fontOffsets[19].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(creditsPos.x + 75.0f, creditsPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[18].mX, fontOffsets[18].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

/*CREDITS - end*/

/*QUIT*/
AEGfxSetPosition(exitPos.x - 40.0f, exitPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[16].mX, fontOffsets[16].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(exitPos.x - 7.5f, exitPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[20].mX, fontOffsets[20].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(exitPos.x + 17.5f, exitPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[8].mX, fontOffsets[8].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

AEGfxSetPosition(exitPos.x + 40.0f, exitPos.y);
AEGfxTextureSet(fontTexture, fontOffsets[19].mX, fontOffsets[19].mY, 0.0f);
AEGfxMeshDraw(fontMesh, AE_GFX_MDM_TRIANGLES);

/*QUIT - end*/

animateFrames(&currentTitleOffset, &titleTime, 0.25f, dt);
checkEndFrames(&currentTitleOffset, 6);
currTitleFrame = currentTitleOffset;

/*draw player*/
AEGfxSetRenderMode(AE_GFX_RM_TEXTURE);
AEGfxSetPosition(titlePos.x, titlePos.y);
AEGfxTextureSet(titleTexture, titleOffsets[currTitleFrame].mX, titleOffsets[currTitleFrame].mY);
AEGfxSetTransparency(1.0f);
AEGfxMeshDraw(titleMesh, AE_GFX_MDM_TRIANGLES);

/*get the mouse position*/
AEInputGetCursorPosition(&mouseX, &mouseY);
AEGfxConvertScreenCoordinatesToWorld(mouseX, mouseY, &mouseInWorldX, &mouseInWorldY);

/*if demo level is hovered*/
if ((mouseInWorldX > (levelPos.x - buttonSize.x) && mouseInWorldX < (levelPos.x + buttonSize.x)) &&
(mouseInWorldY > (levelPos.y - buttonSize.y) && mouseInWorldY < (levelPos.y + buttonSize.y)))
{
// Hover texture
AEGfxSetRenderMode(AE_GFX_RM_TEXTURE);
AEGfxSetPosition(levelPos.x - 140.0f, levelPos.y);
AEGfxTextureSet(iconTexture, 0.0f, 0.0f);
AEGfxMeshDraw(iconMesh, AE_GFX_MDM_TRIANGLES);

if (AEInputCheckTriggered(RI_MOUSE_LEFT_BUTTON_DOWN))
{
GameStateManagerSetNextState(LevelSelect);
}
}
/*if credits is hovered*/
if ((mouseInWorldX > (creditsPos.x - buttonSize.x) && mouseInWorldX < (creditsPos.x + buttonSize.x)) &&
(mouseInWorldY > (creditsPos.y - buttonSize.y) && mouseInWorldY < (creditsPos.y + buttonSize.y)))
{
// Hover texture
AEGfxSetRenderMode(AE_GFX_RM_TEXTURE);
AEGfxSetPosition(creditsPos.x - 140.0f, creditsPos.y);
AEGfxTextureSet(iconTexture, 0.0f, 0.0f);
AEGfxMeshDraw(iconMesh, AE_GFX_MDM_TRIANGLES);

if (AEInputCheckTriggered(RI_MOUSE_LEFT_BUTTON_DOWN))
{
GameStateManagerSetNextState(Credits);
}
}

/*if exit is hovered*/
if ((mouseInWorldX > (exitPos.x - buttonSize.x) && mouseInWorldX < (exitPos.x + buttonSize.x)) &&
(mouseInWorldY > (exitPos.y - buttonSize.y) && mouseInWorldY < (exitPos.y + buttonSize.y)))
{
// Hover texture
AEGfxSetRenderMode(AE_GFX_RM_TEXTURE);
AEGfxSetPosition(exitPos.x - 140.0f, exitPos.y);
AEGfxTextureSet(iconTexture, 0.0f, 0.0f);
AEGfxMeshDraw(iconMesh, AE_GFX_MDM_TRIANGLES);

if (AEInputCheckTriggered(RI_MOUSE_LEFT_BUTTON_DOWN))
{
GameStateManagerSetNextState(GsQuit);
}
}
}

void MenuShutdown()
{
// Do not cleanup audio so music continues into credits and level select
}

void MenuUnload()
{
// Unload all textures.
AEGfxTextureUnload(buttonTexture);
AEGfxTextureUnload(titleTexture);
AEGfxTextureUnload(bgTexture);
AEGfxTextureUnload(fontTexture);
AEGfxTextureUnload(iconTexture);

// Free all meshes.
AEGfxMeshFree(buttonMesh);
AEGfxMeshFree(titleMesh);
AEGfxMeshFree(bgMesh);
AEGfxMeshFree(fontMesh);
AEGfxMeshFree(iconMesh);
}```
```// ---------------------------------------------------------------------------
// Project Name		:	Nook
// File Name		:	Mesh.c
// Author			:	Mary Khuu
// Creation Date	:	19 Feb 2021
// Purpose			:	Deals with all things needed for sprites
// All content © 2021 DigiPen (USA) Corporation, all rights reserved.
// ---------------------------------------------------------------------------

#include "Sprite.h"

//function to create a quadratic mesh
AEGfxVertexList* createQuadMesh(float halfSizeX, float halfSizeY, float u, float v, const char* meshName)
{
AEGfxVertexList* mesh;

AEGfxMeshStart();

AEGfxTriAdd(
-halfSizeX, -halfSizeY, 0x00FFFFFF, 0.0f, v,
halfSizeX, -halfSizeY, 0x00FFFFFF, u, v,
-halfSizeX, halfSizeY, 0x00FFFFFF, 0.0f, 0.0f);
AEGfxTriAdd(
halfSizeX, -halfSizeY, 0x00FFFFFF, u, v,
halfSizeX, halfSizeY, 0x00FFFFFF, u, 0.0f,
-halfSizeX, halfSizeY, 0x00FFFFFF, 0.0f, 0.0f);

mesh = AEGfxMeshEnd();
AE_WARNING_MESG(mesh, "Failed to create %s!", meshName);

if (mesh != 0)
{
return mesh;
}
else
{
return 0;
}
}

//same as above but less parameters, assume halfsize is the same in x and y and u = v
AEGfxVertexList* createEqualQuadMesh(float halfSize, float uv, const char* meshName)
{
AEGfxVertexList* mesh;

AEGfxMeshStart();

AEGfxTriAdd(
-halfSize, -halfSize, 0x00FFFFFF, 0.0f, uv,
halfSize, -halfSize, 0x00FFFFFF, uv, uv,
-halfSize, halfSize, 0x00FFFFFF, 0.0f, 0.0f);
AEGfxTriAdd(
halfSize, -halfSize, 0x00FFFFFF, uv, uv,
halfSize, halfSize, 0x00FFFFFF, uv, 0.0f,
-halfSize, halfSize, 0x00FFFFFF, 0.0f, 0.0f);

mesh = AEGfxMeshEnd();
AE_WARNING_MESG(mesh, "Failed to create %s!", meshName);

if (mesh != 0)
{
return mesh;
}
else
{
return 0;
}
}

int getMaxFrames(int rows, int columns)
{
return rows * columns;
}

void animateFrames(int* currentFrame, float* time, float frameDelay, float dt)
{
(*time) += dt;

if (*time >= frameDelay)
{
(*currentFrame)++;
*time = 0;
}
}

void checkEndFrames(int* currentFrame, int maxFrame)
{
if (*currentFrame >= maxFrame)
{
*currentFrame = 0;
}
}```
```// ---------------------------------------------------------------------------
// Project Name		:	Nook
// File Name		:	Audio.c
// Author			:	Mary Khuu
// Creation Date	:	15 Mar 2021
// Purpose			:	add audio to the game
// All content © 2021 DigiPen (USA) Corporation, all rights reserved.
// ---------------------------------------------------------------------------

#include "fmod.h"
#include <stdio.h>		// printf()
#include <stdbool.h>	// FALSE
#include "AEEngine.h"

#include "Audio.h"

FMOD_SYSTEM* soundSystem;
FMOD_SOUND* sound;
FMOD_CHANNEL* channel;
FMOD_RESULT result;

// Initialize the Audio System
void AudioInit()
{
channel = 0;

// Create and Initialize the FMOD System
result = FMOD_System_Create(&soundSystem);

void* extradriverdata = 0;
result = FMOD_System_Init(soundSystem, 32, FMOD_INIT_NORMAL, extradriverdata);
}

void playSound(bool trigger, const char* file)
{
// Create and Play the sound
// Note: this should be generalized for multiple sounds and
//       be placed in a function to be used outside of init.
result = FMOD_System_CreateStream(soundSystem, file, FMOD_LOOP_OFF | FMOD_2D, 0, &sound);

result = FMOD_System_PlaySound(soundSystem, sound, 0, trigger, &channel);

}

void playSoundAdvanced(const char* file, float volume)
{
FMOD_CHANNEL* channel;

result = FMOD_System_CreateStream(soundSystem, file, FMOD_LOOP_OFF | FMOD_2D, 0, &sound);

result = FMOD_System_PlaySound(soundSystem, sound, 0, true, &channel);

result = FMOD_Channel_SetVolume(channel, volume);

result = FMOD_Channel_SetPaused(channel, false);
}

// Update the Audio System
// Note: this should be called frequently such as every game loop or
//       every time a user enters a command depending on the engine
void AudioUpdate()
{
result = FMOD_System_Update(soundSystem);
}

// Cleanup the Audio System
void AudioCleanup()
{
// Release all sounds that have been created
result = FMOD_Sound_Release(sound);

// Close and Release the FMOD system
result = FMOD_System_Close(soundSystem);
result = FMOD_System_Release(soundSystem);
}

```
```#include <pch.h>
#include "Projects/ProjectTwo.h"
#include "P2_Pathfinding.h"

#pragma region Extra Credit

std::list<AStarPather::Node*> list;
AStarPather::Node map[61][61];

bool ProjectTwo::implemented_floyd_warshall()
{
return false;
}

bool ProjectTwo::implemented_goal_bounding()
{
return false;
}

bool ProjectTwo::implemented_jps_plus()
{
return false;
}
#pragma endregion

bool AStarPather::initialize()
{
// handle any one-time setup requirements you have

/*
If you want to do any map-preprocessing, you'll need to listen
for the map change message.  It'll look something like this:

Callback cb = std::bind(&AStarPather::your_function_name, this);
Messenger::listen_for_message(Messages::MAP_CHANGE, cb);

There are other alternatives to using std::bind, so feel free to mix it up.
Callback is just a typedef for std::function<void(void)>, so any std::invoke'able
object that std::function can wrap will suffice.
*/

return true; // return false if any errors actually occur, to stop engine initialization
}

void AStarPather::shutdown()
{
/*
Free any dynamically allocated memory or any other general house-
keeping you need to do during shutdown.
*/
}
/*
This is where you handle pathing requests, each request has several fields:

start/goal - start and goal world positions
path - where you will build the path upon completion, path should be
start to goal, not goal to start
heuristic - which heuristic calculation to use
weight - the heuristic weight to be applied
newRequest - whether this is the first request for this path, should generally
be true, unless single step is on

smoothing - whether to apply smoothing to the path
rubberBanding - whether to apply rubber banding
singleStep - whether to perform only a single A* step
debugColoring - whether to color the grid based on the A* state:
closed list nodes - yellow
open list nodes - blue

use terrain->set_color(row, col, Colors::YourColor);
also it can be helpful to temporarily use other colors for specific states
when you are testing your algorithms

method - which algorithm to use: A*, Floyd-Warshall, JPS+, or goal bounding,
will be A* generally, unless you implement extra credit features

The return values are:
PROCESSING - a path hasn't been found yet, should only be returned in
single step mode until a path is found
COMPLETE - a path to the goal was found and has been built in request.path
IMPOSSIBLE - a path from start to goal does not exist, do not add start position to path
*/
PathResult AStarPather::compute_path(PathRequest &request)
{

//start/goal - start and goal world positions
GridPos start = terrain->get_grid_position(request.start);
GridPos goal = terrain->get_grid_position(request.goal);

terrain->set_color(start, Colors::Red);
//set color to orange
terrain->set_color(goal, Colors::Red);

//request.path.push_back(request.start);

/***********************************A* SEARCH ALGORITHM*********************************/
//Push Start Node onto the Open List.

if (request.newRequest)
{
for (int i = 0; i <= 40; i++)
{
for (int j = 0; j <= 40; j++)
{
map[i][j].parent = NULL;
map[i][j].pos = GridPos{j, i};
map[i][j].onList_ = onList::NONE;
map[i][j].cost = 0.0f;
map[i][j].given = 0.0f;
}
}
list.clear();
list.push_back(&map[start.col][start.row]);
}

//While (Open List is not empty) {
while (!list.empty())
{
//Pop cheapest node off Open List (parent node).
Node* parentNode = findCheapest(list);

std::list<Node*>::iterator it;
it = list.begin();
std::advance(it, findNodeIndex(list, parentNode));
it = list.erase(it);

//request.path.push_back(terrain->get_world_position(parentNode->pos));
//If node is the Goal Node, then path found (RETURN �found�).
if (parentNode->pos == goal)
{
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
Node* cur = parentNode;
while (cur) {
//push request
request.path.push_front(terrain->get_world_position(cur->pos));
//go to next parent
cur = cur->parent;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

terrain->set_color(start, Colors::Orange);
terrain->set_color(goal, Colors::Orange);
return PathResult::COMPLETE;
}

bool NW = true;
bool NE = true;
bool SE = true;
bool SW = true;

//For (all neighboring child nodes)
for (int i = 1; i <= 8; i++)
{
//set parent to parent
GridPos childPos = getChild(parentNode->pos, i); //get child
//deleted line
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Node* oldParent = map[childPos.col][childPos.row].parent;

if (childPos != parentNode->pos)
{
//set map's parent to new parent after getting position
//map[childNode->pos.col][childNode->pos.row].parent = &map[parentNode->pos.col][parentNode->pos.row];

//grid is on the map and isn't a wall
if (terrain->is_valid_grid_position(childPos) && !terrain->is_wall(childPos))
{
//i is non diagonals or is a valid diagonal
if (i <= 4 || (i == 5 && NE) || (i == 6 && SE) || (i == 7 && SW) || (i == 8 && NW))
{
//Compute its cost, f(x) = g(x) + h(x)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
float given = parentNode->given;
if (i >= 4)
{
//tile is a diagonal
given += (float)std::sqrt(2);
//map[childPos.col][childPos.row].given = map[parentNode->pos.col][parentNode->pos.row].given + (float)std::sqrt(2);
}
else
{
//tile is N, S, W, E
given += 1;
//map[childPos.col][childPos.row].given = map[parentNode->pos.col][parentNode->pos.row].given + 1;
}

float h = getHeuristic(request.settings.heuristic, childPos, goal);
//map[childPos.col][childPos.row].cost = map[parentNode->pos.col][parentNode->pos.row].given + h * request.settings.weight;
float newCost = given + h * request.settings.weight;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

//find if child exists on curr list, and assign it
map[parentNode->pos.col][parentNode->pos.row].onList_ = assignList(list, map[parentNode->pos.col][parentNode->pos.row].pos);

//If child node isn't on Open or Closed list, put it on Open List.
if (map[childPos.col][childPos.row].onList_ == onList::NONE)
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////
map[childPos.col][childPos.row].parent = parentNode;
map[childPos.col][childPos.row].given = given;
map[childPos.col][childPos.row].cost = newCost;
////////////////////////////////////////////////////////////////////////////////////////////////////////////
map[childPos.col][childPos.row].onList_ = onList::OPEN;
terrain->set_color(childPos, Colors::Blue);
list.push_back(&map[childPos.col][childPos.row]);
}
//Else if child node is on Open or Closed List,
else if (map[childPos.col][childPos.row].onList_ == onList::OPEN || map[childPos.col][childPos.row].onList_ == onList::CLOSE)
{
//AND this new one is cheaper,
//then take the old expensive one off both lists
//if oldCost == 0 then it's our first time setting it
if (map[childPos.col][childPos.row].cost > newCost)
{
//and put this new cheaper one on the Open List.
////////////////////////////////////////////////////////////////////////////////////////////////////////////
map[childPos.col][childPos.row].parent = parentNode;
map[childPos.col][childPos.row].given = given;
map[childPos.col][childPos.row].cost = newCost;
////////////////////////////////////////////////////////////////////////////////////////////////////////////
map[childPos.col][childPos.row].onList_ = onList::OPEN;
terrain->set_color(childPos, Colors::Blue);
list.push_back(&map[childPos.col][childPos.row]);
}
/*
else
{
map[childPos.col][childPos.row].cost = oldCost;
map[childPos.col][childPos.row].parent = oldParent;
}*/
}
}
}
//grid is valid but the non-diagonals is a wall, skip the diagonals
else if (terrain->is_valid_grid_position(childPos) && terrain->is_wall(childPos) && i <= 4)
{
if (i == 1) //NORTH
{
NE = false;
NW = false;
}

if (i == 2) //EAST
{
NE = false;
SE = false;
}

if (i == 3) //SOUTH
{
SE = false;
SW = false;
}

if (i == 4) //WEST
{
SW = false;
NW = false;
}
}
}
}

/***************************************************************************************************************/
//Place parent node on the Closed List (we're done with it).
parentNode->onList_ = onList::CLOSE;
map[parentNode->pos.col][parentNode->pos.row].onList_ = onList::CLOSE;
terrain->set_color(parentNode->pos, Colors::Yellow);
map[parentNode->pos.col][parentNode->pos.row] = *parentNode;
//If taken too much time this frame (or in single step mode),
if (request.settings.singleStep == true)
{
//abort search for now and resume next frame (RETURN �working�).
return PathResult::PROCESSING;
}
}
//Open List empty, thus no path possible (RETURN �fail�).
return PathResult::IMPOSSIBLE;

}

float AStarPather::getHeuristic(Heuristic method, GridPos position, GridPos goal)
{
float dx = (float)std::fabs(position.row - goal.row);
float dy = (float)std::fabs(position.col - goal.col);

if (method == Heuristic::OCTILE)
{
return 1 * (dx + dy) + (float)(sqrt(2) - 2 * 1) * std::min(dx, dy);
}

if (method == Heuristic::CHEBYSHEV)
{
return 1 * (dx + dy) + (1 - 2 * 1) * std::min(dx, dy);
}

if (method == Heuristic::MANHATTAN)
{
return dx + dy;
}

if (method == Heuristic::EUCLIDEAN)
{
return (float)sqrt(dx * dx + dy * dy);
}

return 0.0f;
}

AStarPather::onList AStarPather::assignList(std::list<Node*> list, GridPos position)
{
//go through list
for (const Node* node : list)
{
//if node exists in list
//and is labeled as open
if (node->pos == position && node->onList_ == onList::OPEN)
{
//return open
return onList::OPEN;
}
//and is labeled as closed
if (node->pos == position && node->onList_ == onList::CLOSE)
{
//return closed
return onList::CLOSE;
}
//and is labeled as none
if (node->pos == position && node->onList_ == onList::NONE)
{
return onList::NONE;
}
}

//else it's not on either list
return onList::NONE;
}

GridPos AStarPather::getChild(GridPos node, int i)
{
GridPos pos;
if (i == 1) //NORTH
{
pos = { node.row + 1, node.col};
}
else if (i == 5) //NE
{
pos = { node.row + 1, node.col + 1 };
}
else if (i == 2) //EAST
{
pos = { node.row, node.col + 1};
}
else if (i == 6) //SE
{
pos = { node.row - 1, node.col + 1 };
}
else if (i == 3) //SOUTH
{
pos = { node.row - 1, node.col };
}
else if (i == 7) //SW
{
pos = { node.row - 1, node.col - 1 };
}
else if (i == 4) //WEST
{
pos = { node.row, node.col - 1};
}
else if (i == 8) //NW
{
pos = { node.row + 1, node.col - 1};
}

return pos;
}

AStarPather::Node* AStarPather::findCheapest(std::list<Node*> list)
{
Node* cheapestNode;
float minCost = -1.0f;
for (Node* node : list)
{
if ((node->cost < minCost || minCost == -1.0f) && node->onList_ != onList::CLOSE)
{
//is a valid node
if (terrain->is_valid_grid_position(node->pos) && node->cost >= 0.0f)
{
cheapestNode = node;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
minCost = cheapestNode->cost;
}
}
}

return cheapestNode;
}

int AStarPather::findNodeIndex(std::list<Node*> list, Node* node)
{
int i = 0;
int index = 0;
for (Node* node_ : list)
{
if (node_->pos == node->pos)
{
index = i;
}
i++;
}

return index;
}```
```  //Challenge Solution - Part #2
else if (digitalRead(sw2Pin) == HIGH) {
delay(250);
flipSwitch(sw2Pos);
} ```
```  // Challenge Solution - Part #1
// Cascading "if" statement to turn switches "ON" if they are "OFF"
// The PULLUP configuration means that a "LOW" signal equals the switch being "ON",
// while a "HIGH" signal equals the switch being in the "OFF" position
if (digitalRead(sw1Pin) == HIGH) {
delay(250);
flipSwitch(sw1Pos);
} ```
```#include<bits/stdc++.h>
using namespace std;

void solve(){

}

int main(){
int t;
cin>>t;
while(t-->0){
solve();
}
return 0;
}```
```#include<bits/stdc++.h>
using namespace std;

int main(){
int t;
cin>>t;
while(t-->0){

}
return 0;
}```
```#include<bits/stdc++.h>
using namespace std;

int main(){

return 0;
}```
```// C++ code to find count of largest consectutive subset
#include <iostream>
#include <stdlib.h>
#include <unordered_set>
using namespace std;

int main() {
int sz, num;
unordered_set<int> numbers;
int maxLen = 0;
cin>>sz;
for (int i=0;i<sz;i++) {
cin>>num;
numbers.insert(num);
}

for (int i : numbers) {
if (numbers.find(i-1) == numbers.end()) {
int temp = i;
while (numbers.find(temp) != numbers.end()) temp++;

if (maxLen < (temp-i)) maxLen = temp-i;
}
}

cout<< maxLen;
return 0;
}```
```# Makefile

SRC := \$(wildcard *.cpp) \$(wildcard *.cc) \$(wildcard *.c)
OBJ := \$(SRC:.cpp=.o) \$(SRC:.cc=.o) \$(SRC:.c=.o)
TARGET := my_program

CXX := /opt/homebrew/opt/ccache/libexec/g++
CXXFLAGS := -fdiagnostics-color=always -g -Wall -std=c++20

\$(TARGET): \$(OBJ)
\$(CXX) \$(CXXFLAGS) -o \$@ \$^

clean:
rm -f \$(OBJ) \$(TARGET)
```
```#include <iostream>
#include<cstring>
#include<memory>

using namespace std;

bool isValid (string customerNumber) {
if (customerNumber.length() != 6)
return false;

for(int i = 0; i < 2; i++)
if (!isalpha(customerNumber[i]))
return false;

for (int i = 2; i < customerNumber.length(); i++)
if(!isdigit(customerNumber[i]))
return false;

return true;
}

int main() {

string cust_number = "AB1234";
cout << isValid(cust_number);
return 0;
}
```
```#include <iostream>

using namespace std;

int main() {

int numbers[] = {10,20,30};
int* ptrNumbers = &numbers[size(numbers) - 1];

while (ptrNumbers >= &numbers[0]) {//or (ptrNumbers >= numbers)
cout << *ptrNumbers <<endl;
ptrNumbers--;
}
return 0;
}
```
```#include <iostream>

using namespace std;

void increasePrice(double& price) {
price *= 1.2;

}
int main() {

double price = 100;
increasePrice(price);
cout << price;

return 0;
}
```
```#include <iostream>

using namespace std;

int main() {

int number = 10;
int* ptr = &number; // The address of operator
*ptr = 20; // Indirection (de-referencing) operator
cout << number;

return 0;
}
```
```#include <iostream>

using namespace std;

int main() {

int firstArray[] = {10,20,30,40};
int secondArray[] = {10,20,30,40};

bool areEqual = true;
for (int i = 0; i<size(firstArray); i++)
if(firstArray[i] != secondArray[i]) {
areEqual = false;
break;
}
cout << boolalpha << areEqual;```
```#include <iostream>

using namespace std;

int main() {

int firstArray[] = {10,20,30,40};
int secondArray[size(firstArray)];

for (int i = 0; i < size(firstArray); i++)
secondArray[i] = firstArray[i];

for (int number: secondArray)
cout << number << endl;

return 0;

}
```
```#include <iostream>
using namespace std;

int main() {

cout << "Enter a positive number: ";
int number;
cin >> number;

if (number < 0)
cout << "Error! Number is not positive";
else {
int factorial = 1;
for (int i = 1; i<=number; i++)
factorial = factorial * i;  // factorial *= i
cout << "The factorial of " << number << ": " << factorial;
}

return 0;
}
```
```#include<bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef double dl;

#define endl "\n"
#define optimize() ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define fraction() cout.unsetf(ios::floatfield); cout.precision(10); cout.setf(ios::fixed,ios::floatfield);

int main()
{
int n;
cin>>n;
int arr[n];int b[n];
int max=0;
for(int i=0;i<n;i++){
cin>>arr[i];
if(arr[i]>max)max=arr[i];
}
int count_arr[max+1];
for(int i=0;i<=max;i++){
count_arr[i]=0;
}
for(int i=0;i<n;i++){
count_arr[arr[i]]++;
}
for(int i=1;i<=max;i++){
count_arr[i]=count_arr[i]+count_arr[i-1];
}
for(int i=n-1;i>=0;i--){
b[--count_arr[arr[i]]]=arr[i];
}
for(int i=0;i<n;i++){
cout<<b[i]<<" ";
}
return 0;
}

```
```    int n;
cin >> n;
string s;
cin >> s;
for (char c = 'A'; c <= 'Z'; c++) {
int first = n;
int last = -1;
for (int i = 0; i < n; i++) {
if (s[i] == c) {
first = min(first, i);
last = max(last, i);
}
}
for (int i = first; i <= last; i++) {
if (s[i] != c) {
cout << "NO\n";
return;
}
}
}
cout << "YES\n";```
`        score = score + 10 - time_to_press/100;`
`        score = score + 1 + time_to_press/100;`
```    // Challenge Solution Part 5: Add 1 bonus point for every tenth of a second under 1.0 seconds
// Keep in mind that 1 second is equal to 1,000 milliseconds
if(time_to_press < 1000){
score = score + 5;
}```
```      //Challenge Solution Part 4: Calculate the difference in time between the row becoming active and the button press.
time_to_press = millis() - time_start;```
```    //Challenge Solution Part 3: Start the timer for this row being active
time_start = millis();```
```//{ Driver Code Starts
// C++ program to remove recurring digits from
// a given number
#include <bits/stdc++.h>
using namespace std;

// } Driver Code Ends

class Solution{
//Function to find the leaders in the array.
public:
vector<int> leaders(int a[], int n)
{
vector<int>ans;
for(int i=0 ; i<n ; i++)
{
int j;
for( j=i+1 ; j<n ; j++)
{
if(a[i]<a[j])
{
break;
}

}
if(j==n)
{
ans.push_back(a[i]);
}
}
return ans;

}
};

//{ Driver Code Starts.

int main()
{
long long t;
cin >> t;//testcases
while (t--)
{
long long n;
cin >> n;//total size of array

int a[n];

//inserting elements in the array
for(long long i =0;i<n;i++){
cin >> a[i];
}
Solution obj;
//calling leaders() function
vector<int> v = obj.leaders(a, n);

//printing elements of the vector
for(auto it = v.begin();it!=v.end();it++){
cout << *it << " ";
}

cout << endl;

}
}

// } Driver Code Ends

//{ Driver Code Starts
// C++ program to remove recurring digits from
// a given number
#include <bits/stdc++.h>
using namespace std;

// } Driver Code Ends

class Solution{
//Function to find the leaders in the array.
public:
vector<int> leaders(int a[], int n)
{
vector<int>v;
int maxi=INT_MIN;
for(int i=n-1 ; i>=0 ; i--)
{
if(a[i]>=maxi)
{
maxi=a[i];
v.push_back(maxi);
}
}
reverse(v.begin(),v.end());
return v;
}
};

//{ Driver Code Starts.

int main()
{
long long t;
cin >> t;//testcases
while (t--)
{
long long n;
cin >> n;//total size of array

int a[n];

//inserting elements in the array
for(long long i =0;i<n;i++){
cin >> a[i];
}
Solution obj;
//calling leaders() function
vector<int> v = obj.leaders(a, n);

//printing elements of the vector
for(auto it = v.begin();it!=v.end();it++){
cout << *it << " ";
}

cout << endl;

}
}

// } Driver Code Ends```
```//{ Driver Code Starts
#include <iostream>
using namespace std;

// } Driver Code Ends
class Solution{
public:
// Function to find equilibrium point in the array.
// a: input array
// n: size of array
int equilibriumPoint(long long a[], int n)
{
int i=0;
int curr=0;
int sum=0;
for(int i=0 ; i<n ; i++)
{
sum+=a[i];
}
while(i<n)
{
curr+=a[i];
if(curr==sum)
{
return i+1;
}
else
{
sum-=a[i];
}
i++;
}
return -1;
}

};

//{ Driver Code Starts.

int main() {

long long t;

//taking testcases
cin >> t;

while (t--) {
long long n;

//taking input n
cin >> n;
long long a[n];

//adding elements to the array
for (long long i = 0; i < n; i++) {
cin >> a[i];
}

Solution ob;

//calling equilibriumPoint() function
cout << ob.equilibriumPoint(a, n) << endl;
}
return 0;
}

// } Driver Code Ends```
``` if(n<m) return "No";

map<int,int> mp;
for(int i=0;i<n;i++)
{
mp[a1[i]]++;
}

for(int i=0;i<m;i++)
{
if(mp.find(a2[i]) != mp.end())
{
if(mp[a2[i]] == 0)
{
return "No";
}

mp[a2[i]]--;

continue;
}else{
return "No";
}
}
return "Yes";
}

string isSubset(int a1[], int a2[], int n, int m)
{
int i=0;
int count=0;
int j=0;
sort(a1,a1+n);

sort(a2,a2+m);
while(i<n and j<m)
{
if(a1[i]==a2[j])
{
i++;
j++;
count++;

}
else if(a1[i]<a2[j])
{
i++;
}
else
{
return "No";
}

}
if(count==m)
{
return "Yes";
}
return "No";
}```
```int lowestCommonAncestor(TreeNode<int> *root,
int x, int y)
{
if(!root)
return -1;
if(root->data==x or root->data==y)
return root->data;
int lefti=lowestCommonAncestor(root->left,x,y);
int righti=lowestCommonAncestor(root->right,x,y);
if(lefti==-1)
return righti;
if(righti==-1)
return lefti;
return root->data;
}```
```#include <bits/stdc++.h>
vector<vector<string>>
getGroupedAnagrams(vector<string> &input, int n)
{
unordered_map<string,vector<string>>mp;
vector<vector<string>>ans;
for(int i=0 ; i<n ; i++)
{
string str=input[i];
string s=str;
sort(s.begin(),s.end());
mp[s].push_back(str);
}
for(auto it:mp)
{
ans.push_back(it.second);
}
return ans;
}```
```int fib(int n)
{
int a = 0, b = 1, c, i;
if (n == 0)
return a;
for (i = 2; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return b;
}

int fib(int n)
{
if (n <= 1)
return n;
return fib(n - 1) + fib(n - 2);
}```
```  vector <int> calculateSpan(int price[], int n)
{
vector<int>ans;
stack<pair<int,int>>st;
for(int i=0 ; i<n ; i++)
{

while(!st.empty() and st.top().first<=price[i])
{
st.pop();
}
if(st.empty())
{
ans.push_back(-1);
}
else if(!st.empty() and st.top().first>price[i])
{
ans.push_back(st.top().second);
}
st.push({price[i],i});
}
for(int i=0 ; i<n ; i++)
{
ans[i]=i-ans[i];
}
return ans;
}```
```//{ Driver Code Starts
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <bits/stdc++.h>
using namespace std;

struct Node {
int data;
struct Node* next;
Node(int x) {
data = x;
next = NULL;
}
};

// } Driver Code Ends
/* Structure of the linked list node is as
struct Node
{
int data;
struct Node* next;
Node(int x) { data = x;  next = NULL; }
};
*/

class Solution{
public:
//Function to sort the given linked list using Merge Sort.
Node* merge(Node* left,Node* right)
{
Node* ptr=NULL;
if(!left)
return right;
if(!right)
return left;
if(left->data<right->data)
{
ptr=left;
ptr->next=merge(left->next,right);
}
else
{
ptr=right;
ptr->next=merge(left,right->next);
}
return ptr;
}
Node* middle(Node* head)
{
Node* slow=head;
Node* fast=head->next;
while(fast!=NULL and fast->next!=NULL)
{
slow=slow->next;
fast=fast->next->next;
}
return slow;
}
Node* mergeSort(Node* head)
{
if(!head or !head->next)
return head;
Node* left=head;
Node* mid=middle(head);
Node* right=mid->next;
mid->next=NULL;
left=mergeSort(left);
right=mergeSort(right);
Node* ans=merge(left,right);
return ans;
}
};

//{ Driver Code Starts.

void printList(Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}

void push(struct Node** head_ref, int new_data) {
Node* new_node = new Node(new_data);

new_node->next = (*head_ref);
(*head_ref) = new_node;
}

int main() {
long test;
cin >> test;
while (test--) {
struct Node* a = NULL;
long n, tmp;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> tmp;
push(&a, tmp);
}
Solution obj;
a = obj.mergeSort(a);
printList(a);
}
return 0;
}
// } Driver Code Ends```
```void merge(vector<int>&arr,int l,int mid,int h)
{
vector<int>temp;
int i=l;
int j=mid+1;
while(i<=mid and j<=h)
{
if(arr[i]<=arr[j])
{
temp.push_back(arr[i]);
i++;
}
else
{
temp.push_back(arr[j]);
j++;
}
}
while(i<=mid)
{
temp.push_back(arr[i]);
i++;
}
while(j<=h)
{
temp.push_back(arr[j]);
j++;
}
for(int i=l ; i<=h ; i++)
{
arr[i]=temp[i-l];
}
}
void me(vector<int>&arr,int l,int h)
{

if(l>h)
return;
int mid=(l+h)/2;
me(arr,l,mid);
me(arr,mid+1,h);
merge(arr,l,mid,h);
}
void mergeSort(vector < int > & arr, int n)
{
me(arr,0,n-1);
}```
```#include <bits/stdc++.h>
string encode(string &message)
{
string ans="";
int count=1;
int n=message.size();
for(int i=0 ; i<n ; i++)
{
if(message[i]==message[i+1])
{
count++;
}
ans+=message[i];
ans+=to_string(count);
count=1;
}

return ans;
}```
```#include <bits/stdc++.h>
int minimumParentheses(string pattern)
{
int cnt=0;
int req=0;
for(int i=0 ; i<=pattern.length()-1 ; i++)
{
if(pattern[i]=='(')
{
cnt++;
}
else if(pattern[i]==')' and cnt>0)
{
cnt--;
}
else
{
req++;
}
}
return cnt+req;
}```
```#include <bits/stdc++.h>
bool search(int arr[],int n,int num)
{
for(int i=0 ; i<=n ; i++)
{
if(arr[i]==num)
return true;
}
return false;
}
int firstMissing(int arr[], int n)
{
for(int i=1 ; i<=n ; i++)
{
if(search(arr,n,i)==false)
return i;
}
return n+1;
}

time complexity-O(N2)
```
```#include <bits/stdc++.h>
int pairSum(vector<int> &arr, int n, int target)
{
int count=0;
unordered_map<int,int>mp;
for(int i=0 ; i<n ; i++)
{
if(mp.find(target-arr[i])!=mp.end())
{
count+=mp[target-arr[i]];
}
else
{
mp[arr[i]]++;
}
}
if(count==0)
return -1;
else
return count;
}```
```void insertionSort(int n, vector<int> &arr)
{
for(int i=0 ; i<n ; i++)
{
int j=i;
while(j>0 and arr[j]<arr[j-1])
{
swap(arr[j],arr[j-1]);
j--;
}
}
}```
```class Solution {
public:
void moveZeroes(vector<int>& arr)
{
int n=arr.size();
int pos=0;
for(int i=0 ; i<n ; i++)
{
if(arr[i]!=0)
{
swap(arr[i],arr[pos]);
pos++;
}
}
}
};```
```int length(Node *head)
{
//Write your code here
int c = 0;
Node *temp = head;
while(temp != NULL)
{
temp = temp->next;
c++;
}
return c;
}```
```void insertAtTail(Node* &tail,int d)
{
Node* temp = new Node(d);
tail->next = temp;
tail = tail->next;
}

Node* constructLL(vector<int>& arr) {
// Write your code here
Node* head = new Node(arr[0]);
Node* tail = head;

for(int i = 1;i<arr.size();i++)
{
insertAtTail(tail,arr[i]);
}
return head;
}```
```#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
#define placementlelo vector<int>
#define all(a) (a).begin() , (a).end()
#define sz(a) ((int)((a).size()))

const ll INF = 4e18;

vector<placementlelo> dp(1e4+1 , placementlelo(1e4+1 , -1));

int f(int i , int j , int s , int r , string &x , string &y , string &y1)
{
if(i>j)return 0;
if(dp[i][j] != -1)return dp[i][j];

int mini = 1e9;
for(int k=i; k<=j; k++)
{

if(y1.find(x.substr(i , k-i+1)) != string::npos)mini = min(mini , r+f(k+1 , j , s , r , x , y , y1));
if(y.find(x.substr(i , k-i+1)) != string::npos)mini = min(mini , s+f(k+1 , j , s , r , x , y , y1));
}

return mini;
}
int solve(int s , int r , string x, string y)
{
string y1 = y;
reverse(all(y1));
return f(0 , sz(x)-1 , s, r , x , y , y1);
}

int32_t main(){

ios_base::sync_with_stdio(false);
cin.tie(NULL);

string x , y;
cin >> x >> y;
int s, r;
cin >> s >> r;
int ans = solve(s , r, x , y);
cout << ans;

return 0;

}
```
```#include<bits/stdc++.h>
using namespace std;

int main(){
int n, m; // Replace semicolons with commas
cin >> n >> m; // Remove the extra semicolon

vector<vector<int>> cust;
for(int i=0; i<n; i++){
int q, p;
cin >> q >> p;
cust.push_back({p, q});
}

vector<vector<int>> rice;
for(int i=0; i<m; i++){
int q, p;
cin >> q >> p;
rice.push_back({p, q});
}

sort(cust.begin(), cust.end());
sort(rice.begin(), rice.end());

vector<int> placementlelo(m, 0);

int ans = 0;

for(int i=0; i<n; i++){
int quan = -1;
int index = -1;
for(int j=0; j<m; j++){
if(!placementlelo[j]){

if(rice[j][0] > cust[i][0]) break;

if(rice[j][1] > cust[i][1]){
if(quan == -1){
quan = rice[j][1];
index = j;
}
else{
if(quan > rice[j][1]){
index = j;
quan = rice[j][1];
}
}
}
}
}

if(index != -1){
placementlelo[index] = 1;
ans++;
}
}

cout << ans;
return 0; // Add a return statement at the end of main
}
```
```#include <bits/stdc++.h>
using namespace std;
// calculating hamming distance
int hamdis(string& s1,string& s2)
{
int dis= 0;
int n=s1.length();
for (int i = 0; i < n ; i++)
{
if (s1[i] != s2[i])
{
dis++;
}
}
return dis;
}
// checking string is binary or not
bool checkbinary(string& s) {
for (int i = 0; i <s.length() ; i++)
{
if (s[i] != '0' and  s[i]!= '1') {
return false;
}
}
return true;
}
// finding min cost and distance
void findminimum(string& str, int a, int b) {
if (!checkbinary(str))
{
cout << "INVALID"<<endl;
return;
}

string orig = str;
sort(str.begin(), str.end());

int origcost = 0;
int count01 = 0;
int count10 = 0;
int m=str.length() - 1;
for (int i = 0; i <m ; i++)
{
if (str[i] == '0' && str[i + 1] == '1') {
count01++;
origcost += a;
} else if (str[i] == '1' && str[i + 1] == '0') {
count10++;
origcost += b;
}
}

int minHammingDistance = hamdis(str, orig);

cout << minHammingDistance << endl;
}

int main() {
int T;
cin >> T;

for (int t = 0; t < T; t++) {
string binaryStr;
int A, B;

cin >> binaryStr;
cin >> A >> B;

findminimum(binaryStr, A, B);
}

return 0;
}
```
```  void reverse(int arr[],int low,int high)
{
while(low<=high)
{
int temp=arr[low];
arr[low]=arr[high];
arr[high]=temp;
low++;
high--;
}
}
//Function to rotate an array by d elements in counter-clockwise direction.
void rotateArr(int arr[], int d, int n)
{
if(d>n)
{
d=d%n;
}
reverse(arr,0,d-1);
reverse(arr,d,n-1);
reverse(arr,0,n-1);
}```
``` struct Node* reverseList(struct Node *head)
{
if(!head or head->next==NULL)
{
return head;
}
Node* chotahead=reverseList(head->next);
head->next->next=head;
head->next=NULL;
return chotahead;
}```
```class Solution{
public:
//Function to insert a node at the beginning of the linked list.
Node *insertAtBegining(Node *head, int x)
{

Node* newnode=new Node(x);
newnode->next=head;

return newnode;
}

//Function to insert a node at the end of the linked list.
Node *insertAtEnd(Node *head, int x)
{
if(!head)
{
Node* newnode=new Node(x);
return newnode;
}
Node* temp=head;
while(temp->next!=NULL)
{
temp=temp->next;
}
Node* newnode=new Node(x);
temp->next=newnode;
return head;
}
};```
```int isSorted(int n, vector<int> a)
{
bool flag=false;
for(int i=0 ; i<n-1 ; i++)
{
if (a[i] > a[i + 1]) {
return 0;
}
}
return 1;
}
```
```in two traversal-

vector<int> getSecondOrderElements(int n, vector<int> a)
{
int mini=INT_MAX;
int maxi=INT_MIN;
for(int i=0  ; i<n ; i++)
{
if(a[i]>maxi)
{
maxi=a[i];
}
if(a[i]<mini)
{
mini=a[i];
}
}
vector<int>ans;
int mi=INT_MAX;
int ma=INT_MIN;
for(int i=0 ; i<n ; i++)
{
if(a[i]>ma and a[i]!=maxi)
{
ma=a[i];

}
if(a[i]<mi and a[i]!=mini)
{
mi=a[i];
}
}
ans.push_back(ma);
ans.push_back(mi);
return ans;
}

in single traversal-

int findSecondLargest(int n, vector<int> &arr)
{
int largest=INT_MIN;
int secondlargest=INT_MIN;
for(int i=0 ; i<n ; i++)
{
if(arr[i]>largest)
{
secondlargest=largest;
largest=arr[i];
}
if(arr[i]<largest and arr[i]>secondlargest)
{
secondlargest=arr[i];
}
}
if(secondlargest==INT_MIN)
{
return -1;
}
return secondlargest;
}
```
```#include <bits/stdc++.h>
using namespace std;

int main() {
double p,r,t;
cin>>p>>r>>t;
double in=(p*r*t)/100;
cout<<fixed<<setprecision(6)<<in;
return 0;
}```
```int countLeaves(Node* root)
{
if(!root)
return 0;
if(root->left==NULL and root->right==NULL)
{
return 1;
}
return (countLeaves(root->left)+countLeaves(root->right));
}```
```#include <bits/stdc++.h>
using namespace std;

struct StackNode {
int data;
StackNode *next;
StackNode(int a) {
data = a;
next = NULL;
}
};

class MyStack {
private:
StackNode *top;

public:
void push(int);
int pop();
MyStack() { top = NULL; }
};
//Function to push an integer into the stack.
void MyStack ::push(int x)
{
StackNode* newnode=new StackNode(x);
newnode->next=top;
top=newnode;

}

//Function to remove an item from top of the stack.
int MyStack ::pop()
{
int ddata;
if(top==NULL)
{
return -1;
}
ddata=top->data;
top=top->next;
return ddata;
}

```
```Note-
#react ko single page application bolte h kyuki pure project mai ek hi html file hoti h or sara kaam ussi ke ander hota h.
#entry point -index.js
#React DOM implementation h react ka web app pr.DOM ek tree structure h.react khud ka virtual DOM bnata h.

function Chai()
{
return(
<>
{/* fragment */}
<h2>I am Nistha</h2>
<h3>btech</h3>
</>

)
}
export default Chai;
```
```void def(struct Node* root,vector<int>&ans,int k);
vector<int> Kdistance(struct Node *root, int k)
{
vector<int>ans;
def(root,ans,k);
return ans;
}
void def(struct Node* root,vector<int>&ans,int k)
{
if(!root)
return;
if(k==0)
ans.push_back(root->data);
def(root->left,ans,k-1);
def(root->right,ans,k-1);
}```
``` bool solve(Node* root,int mini,int maxi)
{
if(!root)
return true;
if(root->data>mini and root->data<maxi)
{
bool lefti=solve(root->left,mini,root->data);
bool righti=solve(root->right,root->data,maxi);
if(lefti and righti)
return true;
}
return false;
}
bool isBST(Node* root)
{
return solve(root,INT_MIN,INT_MAX);
}```
```   long long int convertEvenBitToZero(long long int n)
{
return n&0xaaaaaaaa;
}```
```string reverseString(string s)
{
unordered_map<char,int>mp;
string ans="";
for(int i=s.length()-1 ; i>=0 ; i--)
{
mp[s[i]]++;
if((mp[s[i]]==1)&&(s[i]!=' '))
{
ans+=s[i];
}
}
return ans;
}```
``` pair<int, int> get(int a, int b)
{
a=a+b;
b=a-b;
a=a-b;
return{a,b};
}
```
```int main()
{
int year;

year=2000;

if(year % 400 == 0)
cout << year << " is a Leap Year";

else if(year % 4 == 0  && year % 100 != 0)
cout << year << " is a Leap Year";

else
cout << year << " is not a Leap Year";

return 0;
}```
``` double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
{
vector<int>ans;
int l=0;
int r=0;
while(l<nums1.size() and r<nums2.size())
{
if(nums1[l]<nums2[r])
{
ans.push_back(nums1[l]);
l++;
}
else
{
ans.push_back(nums2[r]);
r++;
}
}
if(l<nums1.size())
{
while(l<nums1.size())
{
ans.push_back(nums1[l]);
l++;
}
}
if(r<nums2.size())
{
while(r<nums2.size())
{
ans.push_back(nums2[r]);
r++;
}
}
int size=ans.size();
if(size%2==1)
{
return ans[size/2];
}
else
{
int a = ans[size / 2 - 1];
int b = ans[size / 2];
return (a + b) / 2.0;
}
return -1;
}```
```vector<int> inOrder(Node* root)
{
vector<int>ans;
stack<Node *>s;
Node *curr = root;
while(curr != NULL || !s.empty())
{
while(curr != NULL)
{
s.push(curr);
curr = curr -> left;
}
curr = s.top();
s.pop();
ans.push_back(curr -> data);
curr = curr -> right;
}
return ans;
}```
```#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <iterator>
#include <algorithm>
#include <deque>
#include <cmath>
#include <stack>
#include <queue>
#define endl "\n"
#define ll long long
#define all(v) v.begin(),v.end()
void swap(int arr[] , int pos1, int pos2){
int temp;
temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;
}

int partition(int arr[], int low, int high, int pivot){
int i = low;
int j = low;
while( i <= high){
if(arr[i] > pivot){
i++;
}
else{
swap(arr,i,j);
i++;
j++;
}
}
return j-1;
}

void quickSort(int arr[], int low, int high){
if(low < high){
int pivot = arr[high];
int pos = partition(arr, low, high, pivot);

quickSort(arr, low, pos-1);
quickSort(arr, pos+1, high);
}
}

using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);

ll N ;
cin>>N ;
int X[N] ;
for(ll i=0;i<N;i++){
cin>>X[i];}
quickSort(X,0,N-1) ;
for(ll i=0;i<N;i++){
cout<<X[i]<<" ";}

}

```
```#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <iterator>
#include <algorithm>
#include <deque>
#include <cmath>
#include <stack>
#include <queue>
#define endl "\n"
#define ll long long
#define all(v) v.begin(),v.end()
void merge(int array[], int const left,
int const mid, int const right)
{
auto const subArrayOne = mid - left + 1;
auto const subArrayTwo = right - mid;

// Create temp arrays
auto *leftArray = new int[subArrayOne],
*rightArray = new int[subArrayTwo];

// Copy data to temp arrays leftArray[]
// and rightArray[]
for (auto i = 0; i < subArrayOne; i++)
leftArray[i] = array[left + i];
for (auto j = 0; j < subArrayTwo; j++)
rightArray[j] = array[mid + 1 + j];

// Initial index of first sub-array
// Initial index of second sub-array
auto indexOfSubArrayOne = 0,
indexOfSubArrayTwo = 0;

// Initial index of merged array
int indexOfMergedArray = left;

// Merge the temp arrays back into
// array[left..right]
while (indexOfSubArrayOne < subArrayOne &&
indexOfSubArrayTwo < subArrayTwo)
{
if (leftArray[indexOfSubArrayOne] <=
rightArray[indexOfSubArrayTwo])
{
array[indexOfMergedArray] =
leftArray[indexOfSubArrayOne];
indexOfSubArrayOne++;
}
else
{
array[indexOfMergedArray] =
rightArray[indexOfSubArrayTwo];
indexOfSubArrayTwo++;
}
indexOfMergedArray++;
}

// Copy the remaining elements of
// left[], if there are any
while (indexOfSubArrayOne < subArrayOne)
{
array[indexOfMergedArray] =
leftArray[indexOfSubArrayOne];
indexOfSubArrayOne++;
indexOfMergedArray++;
}

// Copy the remaining elements of
// right[], if there are any
while (indexOfSubArrayTwo < subArrayTwo)
{
array[indexOfMergedArray] =
rightArray[indexOfSubArrayTwo];
indexOfSubArrayTwo++;
indexOfMergedArray++;
}
}

// begin is for left index and end is
// right index of the sub-array
// of arr to be sorted */
void mergeSort(int array[],
int const begin,
int const end)
{
// Returns recursively
if (begin >= end)
return;

auto mid = begin + (end - begin) / 2;
mergeSort(array, begin, mid);
mergeSort(array, mid + 1, end);
merge(array, begin, mid, end);
}

using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);

ll N ;
cin>>N ;
int X[N] ;
for(ll i=0;i<N;i++){
cin>>X[i];}
mergeSort(X,0,N-1) ;
for(ll i=0;i<N;i++){
cout<<X[i]<<" ";}

}

```
```void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;

// Move elements of arr[0..i-1],
// that are greater than key,
// to one position ahead of their
// current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}```
```#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <iterator>
#include <algorithm>
#include <deque>
#include <cmath>
#include <stack>
#include <queue>
#define endl "\n"
#define ll long long
#define all(v) v.begin(),v.end()

using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll N ;
cin>>N ;
ll X[N] ;
for(ll i=0 ;i<N ;i++){cin>>X[i];
}
ll k=N ;
for(ll J=0 ;J<N ;J++) {
for (ll i = 0; i < N-1-J; i++) {
if (X[i] > X[i + 1]) {
swap(X[i], X[i +1]);
}
}
}

for(ll i=0 ;i<N ;i++){
cout<<X[i]<<" ";
}

}

```
```//--intersection function--
IntersectionResult sphere::IntersectTest(ray _ray)
{
//creating values
IntersectionResult testResult;
testResult.hitsphere = false;

//p - a calucation for easier use in next calculations
glm::vec3 delta = sphereCenter - _ray.origin;

//calculating d
float d = glm::length(delta - glm::dot(delta,_ray.dir) * _ray.dir);

//--calculate intersection point--

//calculating x
float intersectx = glm::sqrt((radius * radius) - (d * d));

//final intersect point calculation
glm::vec3 Intersect_Point = _ray.origin + (glm::dot((sphereCenter - _ray.origin), _ray.dir) - intersectx) * _ray.dir;

//main intersection test
//if the ray is less than the radius of the sphere that means it hit so set hit to true
if (d <= radius)
{
testResult.Intersectpoint = Intersect_Point;
testResult.hitsphere = true;
}

//returns the result of the ray
return testResult;
}```
```namespace myengine
{
void load_ogg(const std::string& _path, std::vector<unsigned char>& _buffer,
ALenum& _format, ALsizei& _freq)
{

int channels = 0;
int sampleRate = 0;
short* output = NULL;

size_t samples = stb_vorbis_decode_filename(_path.c_str(),
&channels, &sampleRate, &output);
std::cout << samples << std::endl;

if (samples == -1)
{
throw std::runtime_error("Failed to open file '" + _path + "' for decoding");
}

// Record the format required by OpenAL
if (channels < 2)
{
_format = AL_FORMAT_MONO16;
}
else
{
_format = AL_FORMAT_STEREO16;
}

// Copy (# samples) * (1 or 2 channels) * (16 bits == 2 bytes == short)
_buffer.resize(samples * channels * sizeof(short));
memcpy(&_buffer.at(0), output, _buffer.size());

// Record the sample rate required by OpenAL
_freq = sampleRate;

// Clean up the read data
free(output);
}```
```void DealersTurn(cards PlayerHand[], cards DealerHand[])//dealers turn function
{
DealerTotalHandscore = 0;//sets ai hand score to 0 to reset it when they start thier turn

for (i = 0; i < dealerCurrentHand; i++)//when dealer gets a card it adds to the value
{
DealerTotalHandscore += DealerHand[i].PlayerValue;
}

if (DealerTotalHandscore < 17)//if dealer is less than 17 they can draw a card
{
HitDealer(PlayerHand, DealerHand);//draws card for dealer
Sleep(2000);//delay for immersion
DealersTurn(PlayerHand, DealerHand);//dealers turn again since its below 17
}

if (DealerTotalHandscore >= 17)//if dealers hand is above 17
{
if (TotalHandscore > DealerTotalHandscore)//checks if players hand is bigger than the dealers hand, if player went over the game wouldve already end
{
Sleep(2000);//delay for suspense
std::cout << "You win! Congrats! Your hand total is " << TotalHandscore << " The dealers was " << DealerTotalHandscore << std::endl;
Sleep(2000);
bank += currentbet * 2;
std::cout << "You now have \$" << bank << " in your bank" << std::endl;
Sleep(2000);
std::cout << "Do you want to continue playing? " << std::endl << "1.Yes " << std::endl << "2.No" << std::endl;
Choice = 0;
std::cin >> Choice;//player chooses to play or exit

if (Choice == 1)
{
Choice = 0;
reset();
}

if (Choice == 2)
{
Choice = 0;
Quitgame();
}
}
}```
```class Solution {
public:
vector<int> duplicates(vector<int>& nums){
unordered_set<int> uSet;
int n = nums.size();
vector<int> dup(n, 0);
for(int i = 0 ; i < n ;i++){
if(uSet.find(nums[i]) != uSet.end()){
dup[i] = 1;
}
if(i != 0)
dup[i] += dup[i-1];
uSet.insert(nums[i]);
}
return dup;
}
int minOperations(vector<int>& nums) {
sort(nums.begin(), nums.end());
int req = nums.size() - 1 , ans = nums.size() - 1, n =nums.size();
vector<int> d = duplicates(nums);
for(int ptr = 0; ptr < n-1 ;ptr++ ){
int idx = lower_bound(nums.begin(), nums.end(), req + nums[ptr]) - nums.begin();
if(idx < n ){
int val = nums[ptr] + req;
if(nums[idx] != val)
ans = min(ans, n - idx + ptr + d[idx] - d[ptr]);
else
ans = min(ans, n - idx + ptr - 1 + d[idx] - d[ptr]);
}
else
ans = min(ans, d[n-1] - d[ptr]+ptr);
}
return ans;

}
};```
```// given two strings s1 and s2 (|s1| == |s2|) make s1 same as s2 using following 2 operations
// 1. swap any two elements at indices i and j in s1 with cost x ,
// 2. swap two adjacent elements with cost 1
// achieve this with minimum cost

#define pb push_back

class Solution {
public:
vector<double> dp;
double findMin(vector<int>& diff, int i, int x){
if( i == 0)
return x / 2.0;
if( i == -1)
return 0;
if(dp[i] != -1)
return dp[i];
double left  = findMin(diff, i-1, x) + x/2.0;
double right = findMin(diff, i-2 , x) + diff[i] - diff[i-1];
return dp[i] = min(left, right);
}
int minOperations(string s1, string s2, int x) {
vector<int> diffs;
int n = s1.length();
for(int i = 0; i < n; i++)
if(s1[i] != s2[i])
diffs.pb(i);
if(diffs.size() & 1)
return -1;
dp.resize(diffs.size(),-1);
return (int)findMin(diffs, diffs.size() - 1, x);

}
};
// Its O(n) time and O(n) space;```
```/*----------------------------*/
bool isPrime(int n){for(int i=2;i*i<=n;i++){if(n%i==0)return false;}return true;}
bool isvowel(char c){return (c=='a'||c=='e'||c=='i'||c=='o'||c=='u');}
bool isperfect(long long num){int count = 0;while (num & count<11) {count += num % 10;num /= 10;}return count == 10;}
/*----------------------------*/
#define ll long long
#define dd double
#define vi  vector<int>
#define vvi vector<vector<int>>
#define mi map<int,int>
#define pr  pair<int,int>
#define unset unordered_set<int>
#define ff first
#define ss second
#define pb push_back
#define MAX INT_MAX
#define MIN INT_MIN
#define fr(i,a,n) for(int i=a; i<n; i++)
const int MOD=1e9+7;

#include<bits/stdc++.h>
using namespace std;
int main(){
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);

return 0;
}```
```    // for sophon opencv, the memory is not continuous if the width of image is not 64 bytes aligned
uint8_t continous_data[cvmat.cols * cvmat.rows * cvmat.channels()];
if (!cvmat.isContinuous())
{
std::cout << "cvmat is not continuous" << std::endl;
for (int i = 0; i < cvmat.rows; i++)
{
std::memcpy(continous_data + i * cvmat.cols * cvmat.channels(), cvmat.ptr(i), cvmat.cols * cvmat.channels());
}
}
else
{
std::memcpy(continous_data, cvmat.data, cvmat.cols * cvmat.rows * cvmat.channels());
}```
```bool isEven(Node* head){
Node* fast = head;
while(fast && fast->next) fast=fast->next->next;
if(!fast )
return true;
return false;
}```
```#include <iostream>
using namespace std;

int getGcd(int a, int b) {

while(b!=0) {
int rem = a%b;
a=b;
b=rem;
}
return a;
}

int main()
{
int a,b,gcd;
cin>>a>>b;
gcd = getGcd(a, b);
cout<<gcd;
return 0;
}```
```#include <iostream>
using namespace std;

void primeFactorsSieve(int n) {
int spf[n]={0};

for(int i=2;i<=n;i++) {
spf[i]=i;
}

for(int i=2;i<=n;i++) {
if(spf[i]==i) {
for(int j=i*i;j<=n;j+=i) {
if(spf[j]==j) {
spf[j]=i;
}
}
}
}

while(n!=1) {
cout<<spf[n]<<" ";
n=n/spf[n];
}
}

int main()
{
int n;
cin>>n;
primeFactorsSieve(n);
return 0;
}```
```#include <iostream>
using namespace std;

void primeSieve(int n) {
int prime[100]={0};
int cnt=0;

for(int i=2;i<=n;i++) {
if(prime[i]==0) {
for(int j=i*i;j<=n;j+=i) {
prime[j]=1;
}
}
}
cout<<"\nNumbers: ";
for(int i=2;i<=n;i++) {
if(prime[i]==0) {
cout<<i<<" ";
cnt++;
}
}
cout<<"\nTotal prime numbers: "<<cnt;
cout<<endl;
}

int main()
{
// cout << "Hello, World!";
int n;
cin>>n;
primeSieve(n);
return 0;
}```
```from collections import deque

visited_states = []
total_moves = 70
expanded = 0
count = 0

class Node:
def __init__(self, state, parent, operator, depth, cost):
self.state = state
self.parent = parent
self.operator = operator
self.depth = depth
self.cost = cost

def create_node(state, parent, operator, depth, cost):
return Node(state, parent, operator, depth, cost)

def expand_node(node):
expanded_nodes = []

temp_state = move_down(node.state)
temp_node = create_node(temp_state, node, "down", node.depth + 1, node.cost + 1)
expanded_nodes.append(temp_node)

temp_state1 = move_up(node.state)
temp_node1 = create_node(temp_state1, node, "up", node.depth + 1, node.cost + 1)
expanded_nodes.append(temp_node1)

temp_state2 = move_left(node.state)
temp_node2 = create_node(temp_state2, node, "left", node.depth + 1, node.cost + 1)
expanded_nodes.append(temp_node2)

temp_state3 = move_right(node.state)
temp_node3 = create_node(temp_state3, node, "right", node.depth + 1, node.cost + 1)
expanded_nodes.append(temp_node3)

return expanded_nodes

def move_left(state):
swap = state.copy()
idx = swap.index(0)
if (idx == 0 or idx == 3 or idx == 6):
return swap
else:
swap[idx - 1], swap[idx] = swap[idx], swap[idx - 1]
return swap

def move_right(state):
swap = state.copy()
idx = swap.index(0)
if (idx == 2 or idx == 5 or idx == 8):
return swap
else:
swap[idx + 1], swap[idx] = swap[idx], swap[idx + 1]
return swap

def move_up(state):
swap = state.copy()
idx = swap.index(0)
if (idx == 0 or idx == 1 or idx == 2):
return swap
else:
swap[idx - 3], swap[idx] = swap[idx], swap[idx - 3]
return swap

def move_down(state):
swap = state.copy()
idx = swap.index(0)
if (idx == 6 or idx == 7 or idx == 8):
return swap
else:
swap[idx + 3], swap[idx] = swap[idx], swap[idx + 3]
return swap

def bfs(start, goal):
if (start == goal):
return [None]
else:
to_be_expanded = []
current_node = create_node(start, None, None, 0, 0)
to_be_expanded.append(current_node)

for i in range(total_moves):
temp_expanded = []
size = len(to_be_expanded)

for j in range(size):
if (to_be_expanded[j] in visited_states):
continue

node_array = expand_node(to_be_expanded[j])

for x in range(4):
if (node_array[x].state == goal):
count = i + 1
return node_array[x]
else:
temp_expanded.append(node_array[x])
visited_states.append(node_array[x].state)

to_be_expanded.clear()
to_be_expanded = temp_expanded.copy()
temp_expanded.clear()

return None

def main():
method = 'bfs'
length = 0
x = 0
x = x + 1

board_input = input("Enter the initial state values (comma-separated): ")
board_split = board_input.split(',')
starting_state = [int(i) for i in board_split]

goal_input = input("Enter the goal state values (comma-separated): ")
goal_split = goal_input.split(',')
goal_state = [int(i) for i in goal_split]

if (len(starting_state) == 9 and len(goal_state) == 9):
result = bfs(starting_state, goal_state)
if result == None:
print("No solution found")
elif result == [None]:
print("Start node was the goal!")
else:
print("Total number of moves needed =", result.cost)
path = []
path.append(result.state)
current = result
flag = True

while flag:
parent = current.parent
prev_state = parent.state
path.append(prev_state)
current = parent

if (prev_state == starting_state):
flag = False

path.reverse()
print("Step-wise Sequence of states from start to goal is ")
for state in path:
print(state[0], "|", state[1], "|", state[2])
print(state[3], "|", state[4], "|", state[5])
print(state[6], "|", state[7], "|", state[8])
print()
else:
print("Invalid input")

if __name__ == "__main__":
main()

```
```The introduction of computerized technology in the healthcare sector - the promised to bring a qualitative change to patient one. While in various ways there was a bump in the service they received, patients should have experienced higher value all over the board.

Let’s see some of the examples of integration of Healthcare and blockchain technology.

Remote Patient Monitoring (RPM)

RMP should to have allowed the shift from episodic to preventative healthcare delivery. This should have been feasible with proactive patient monitoring with "Internet of Things" (IoT) approved devices. The RMP market is predicted to reach \$535 Million in united states. RMP devices collect PHI, which needs protection, therefore, a private blockchain is the right choice in this case.
Smart contracts on this private blockchain analyze patient health data.

Electronic Medical Records (EMRs)

EMRs record patient data in the format of electronical, that should have reduced the requirement of paper-based processes. This should have permitted multiple healthcare providers to seamlessly access patient data. This was supposed to significantly enhance the provision of healthcare services. To secure EMRs, Medicalchain uses Hyperledger Fabric, an enterprise blockchain.

There are many healthcare blockchain business ideas that have significant potential. However, integrating any of these ideas is a complex process. Blockchain development requires a lot of expertise and planning, so you might want to get proficient help.
```
```#include <iostream>
using namespace std;

string ending(int sum, int cash) {
const string s = "купюр";
const string end1 = "a";
const string end2 = "ы";
string banknote;

sum /= cash;

if (sum > 4 && sum < 21 || sum > 24 && sum % 10 > 4
&& sum % 10 <= 9 && sum % 10 == 0 || sum == 0) banknote = s;
if (sum == 1 || sum % 10 == 1) banknote = s + end1;
if (sum > 1 && sum < 5 || sum % 10 > 1
&& sum % 10 < 5)  banknote = s + end2;

return banknote;
}

int remainder(int sum, int cash) {
sum -= 1;

if (sum >= 100 && sum != 0 && sum / cash != 0) {
cout << sum / cash << " - " << ending(sum, cash) << " " << cash << " руб.\n";
}
return sum;
}

int main() {
system("clear");

int sum;
cout << "Введите сумму, которую хотите обналичить : ";
cin >> sum;
sum += 1;

if (sum > 100 && sum < 150000 && sum % 100 == 1) {

int cash = 5000;
remainder(sum, cash);
cash = 2000; sum = sum % 5000;
remainder(sum, cash);
cash = 1000; sum = sum % 2000;
remainder(sum, cash);
cash = 500; sum = sum % 1000;
remainder(sum, cash);
cash = 200; sum = sum % 500;
remainder(sum, cash);
cash = 100; sum = sum % 200;
remainder(sum, cash);

} else {
cout << "Не корректная сумма для вывода денег.";
}
}```
```#include <iostream>
using namespace std;

int main()
{
int mansCount;
int barbersCount;
int mansPerBarber = 8; // один человек в час, смена 8 часов
int mansPerBarberPerMonth = mansPerBarber * 30;
/*
mansCount;               - КолМужчин
barbersCount;            - КолБарберов
mansPerBarber            - КолПодстриженныхЗаСмену
mansPerBarberPerMonth    - КолПодстриженныхЗаМесяц
NecessaryNumberBarbers   - НеобходимоеКолБарберов
BarbersRequired          - ТребуемыеБарберы
*/
cout << "\n************ Барбершоп-калькулятор ************\n\n";
back:
cout << "Введите число мужчин в городе: ";
cin >> mansCount;
if (mansCount <= 0) {
cout << "\nВы не можете ввести нулевое или отрицательное значение...\n";
cout << "Попробуйте ещё раз.\n\n";
goto back;
}
back1:
cout << "Сколько уже барберов удалось нанять? ";
cin >> barbersCount;
if (barbersCount <= 0) {
cout << "\nВы не можете ввести нулевое или отрицательное значение...\n";
cout << "Попробуйте ещё раз.\n\n";
goto back1;
}

cout << "\nОдин барбер стрижёт " << mansPerBarberPerMonth << " клиентов в месяц.\n";

// Сколько нужно барберов, чтобы постричь mansCount человек?
int NecessaryNumberBarbers = mansCount / mansPerBarberPerMonth;

if (NecessaryNumberBarbers * mansPerBarberPerMonth % mansCount) {
NecessaryNumberBarbers += 1;
}

cout << "Необходимое число барберов: " << NecessaryNumberBarbers << "\n\n";

const string b = "барбер";
const string end1 = "a";
const string end2 = "ов";

string endin;
int n = NecessaryNumberBarbers;
if (n == 1 || (n > 20 && n % 10 == 1)) endin = b;
else if (n > 1 && n < 5 || n > 20 && n % 10 > 1 && n % 10 < 5) endin = b + end1;
else endin = b + end2;

// Сколько человек успеют посчтричь NecessaryNumberBarbers за месяц?
cout << NecessaryNumberBarbers << " " << endin << " могут постричь "
<< NecessaryNumberBarbers * mansPerBarberPerMonth << " мужчин за месяц.\n";

string ending;
int nb = NecessaryNumberBarbers - barbersCount;
if (nb == 1 || (nb > 20 && nb % 10 == 1)) ending = b;
else if (nb > 1 && nb < 5 || nb > 20 && nb % 10 > 1 && nb % 10 < 5) ending = b + end1;
else ending = b + end2;

int BarbersRequired = NecessaryNumberBarbers - barbersCount;

if (NecessaryNumberBarbers > barbersCount) {
cout << "Требуется ещё " << BarbersRequired << " " << ending << ".\n";
} else if (NecessaryNumberBarbers == barbersCount) {
cout << "Барберов ровно столько, сколько нужно!!!\n";
} else if (barbersCount % NecessaryNumberBarbers == 0) {
cout << "У вас работает в " << barbersCount / NecessaryNumberBarbers << " раза больше барберов, чем это нужно!!!\n";
} else cout << "Барберов хватает!!!\n";
}```
```#include <iostream>
#include <set>
#include <algorithm>
#include <math.h>
#include <vector>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <iterator>
// #include<bits/stdc++.h>
using namespace std;
#define forn(i, a, n) for (int i = a; i < n; i++)
#define MAXN 1000000
#define MOD 1000000007
#define int long long
#define tc    \
int t;    \
cin >> t; \
while (t--)
#define TC size(arr) / size(arr[0])
#define mp make_pair
#define Radhe ios::sync_with_stdio(false);
#define Krishna cin.tie(NULL);

int Time = 0;
vector<pair<int, int>> br;
set<pair<int, int>> res;

vector<int> low, disc;
vector<vector<int>> adj;

void dfsBR(int u, int p)
{
low[u] = disc[u] = ++Time;
for (int &v : adj[u])
{
if (v == p)
continue; // we don't want to go back through the same path.
// if we go back is because we found another way back
if (!disc[v])
{
res.insert({u, v});
// if V has not been discovered before
dfsBR(v, u);          // recursive DFS call
if (disc[u] < low[v]) // condition to find a bridge
br.push_back({u, v});

low[u] = min(low[u], low[v]); // low[v] might be an ancestor of u
}
else // if v was already discovered means that we found an ancestor
{
if (low[u] >= disc[v])
{
low[u] = min(low[u], disc[v]); // finds the ancestor with the least discovery time
res.insert({u, v});

}else{
if(res.find({v,u})==res.end()){
res.insert({u,v});
}
}

}
}
}

void BR()
{
low = disc = vector<int>(adj.size(), 0);
Time = 0;
for (int u = 0; u < adj.size(); u++)
{
if (!disc[u])
{
dfsBR(u, u);
}
}
}

void solve()
{
int n, m;
cin >> n >> m;
adj.resize(n);
forn(i, 0, m)
{
int u, v;
cin >> u >> v;
u--, v--;
adj[u].push_back(v);
adj[v].push_back(u);
}

BR();

if (br.size())
{
cout << 0 << endl;
return;
}

// cout<<br.size()<<endl;
for (auto &x : res)
{
cout << x.first + 1 << " " << x.second + 1 << endl;
}
}
int32_t main()
{
Radhe Krishna
{
solve();
}

return 0;
}
```
```// adj[u] = adjacent nodes of u
// ap = AP = articulation points
// p = parent
// disc[u] = discovery time of u
// low[u] = 'low' node of u

int dfsAP(int u, int p) {
int children = 0;
low[u] = disc[u] = ++Time;
for (int& v : adj[u]) {
if (v == p) continue; // we don't want to go back through the same path.
// if we go back is because we found another way back
if (!disc[v]) { // if V has not been discovered before
children++;
dfsAP(v, u); // recursive DFS call
if (disc[u] <= low[v]) // condition #1
ap[u] = 1;
low[u] = min(low[u], low[v]); // low[v] might be an ancestor of u
} else // if v was already discovered means that we found an ancestor
low[u] = min(low[u], disc[v]); // finds the ancestor with the least discovery time
}
return children;
}

void AP() {
ap = low = disc = vector<int>(adj.size());
Time = 0;
for (int u = 0; u < adj.size(); u++)
if (!disc[u])
ap[u] = dfsAP(u, u) > 1; // condition #2
}```
```   for(int k=0;k<26;k++){
for(int j=0;j<26;j++){
for(int i=0;i<26;i++){
if(W[i][k]!=3000 && W[k][j]!=3000)
W[i][j]=min(W[i][j],W[i][k]+W[k][j]);
}
}
}```
```#include <iostream>
#include <set>
#include <algorithm>
#include <math.h>
#include <vector>
#include <queue>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <iterator>
// #include<bits/stdc++.h>
using namespace std;
#define forn(i, a, n) for (int i = a; i < n; i++)
#define MAXN 1000000
#define MOD 1000000007
#define INT_MAX 1e12
#define int long long
#define tc    \
int t;    \
cin >> t; \
while (t--)
#define TC size(arr) / size(arr[0])
#define Radhe ios::sync_with_stdio(false);
#define Krishna cin.tie(NULL);
void solve()
{
int n, m;
cin >> n >> m;
vector<vector<pair<int, int>>> adj(n);
map<pair<int, int>, int> mp;
vector<int> par(n, -1);
for (int i = 0; i < m; i++)
{
int u, v, w;
cin >> u >> v >> w;
if (u == v)
{
continue;
}
if (v < u)
{
swap(u, v);
}
u--, v--;

if (mp.count({u, v}))
{
mp[{u, v}] = min(mp[{u, v}], w);
}
else
{
mp[{u, v}] = w;
}
}

for  (auto i = mp.begin(); i != mp.end(); i++)
{ auto x=*i;
adj[x.first.first].push_back({x.first.second,x.second});
adj[x.first.second].push_back({x.first.first,x.second});
}

priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<pair<int, pair<int, int>>>> pq;
vector<int> dist(n, INT_MAX);
dist[0] = 0;
pq.push({0, {0, -1}});
while (!pq.empty())
{
int u = pq.top().second.first;
if(pq.top().first>dist[u])
{
pq.pop();
continue;
}
par[u] = pq.top().second.second;
pq.pop();
for (auto it : adj[u])
{
int v = it.first;
int weight = it.second;
if (dist[u] == INT_MAX)
{
continue;
}
if (dist[v] > dist[u] + weight)
{
dist[v] = dist[u] + weight;
pq.push({dist[v], {v, u}});
}
}
}

if(dist[n-1]==INT_MAX)
{
cout<<-1<<endl;
return;
}
vector<int> ans;
int i = n - 1;
while (i != -1)
{
ans.push_back(i + 1);
i = par[i];
}
for(int i=ans.size()-1;i>0;i--)
{
cout<<ans[i]<<" ";
}
cout<<ans[0]<<endl;
}
int32_t main()
{
Radhe Krishna
{
solve();
}

return 0;
}
```
```#include <iostream>
#include <set>
#include <algorithm>
#include <math.h>
#include <vector>
#include <stack>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <iterator>
// #include<bits/stdc++.h>
using namespace std;
#define forn(i, a, n) for (int i = a; i < n; i++)
#define MAXN 1000000
#define MOD 1000000007
#define int long long
#define tc    \
int t;    \
cin >> t; \
while (t--)
#define TC size(arr) / size(arr[0])
#define mp make_pair
#define Radhe ios::sync_with_stdio(false);
#define Krishna cin.tie(NULL);

vector<vector<int>> graph;
int tot = 0;

void findComponent(int u, vector<int> &disc, vector<int> &lowLink, stack<int> &stk, vector<bool> &stkItem)
{
static int time = 0;
disc[u] = lowLink[u] = ++time;
stk.push(u);
stkItem[u] = true;

for (auto x : graph[u])
{
{
if (disc[x] == -1)
{
findComponent(x, disc, lowLink, stk, stkItem);
lowLink[u] = min(lowLink[u], lowLink[x]);
}
else if (stkItem[x])
lowLink[u] = min(lowLink[u], disc[x]);
}
}
int poppedItem = 0;

if (lowLink[u] == disc[u])
{
int co = 0;

while (stk.top() != u)
{
poppedItem = stk.top();
co++;
stkItem[poppedItem] = false;
stk.pop();
}
poppedItem = stk.top();
co++;
stkItem[poppedItem] = false;
stk.pop();

if (co > 1)
{
tot += co;
}
}
}

void strongConComponent(vector<vector<int>> &graph)
{
int v = graph.size();
vector<int> disc(v, -1), lowLink(v, -1);
vector<bool> stkItem(v, false);
stack<int> stk;

for (int i = 0; i < v; i++)
if (disc[i] == -1)
findComponent(i, disc, lowLink, stk, stkItem);
}

void solve()
{

tot = 0;
int n;
cin >> n;
graph = vector<vector<int>>(n);
forn(i, 0, n)
{
char x;
cin >> x;
if (x == '<')
{
graph[(i + 1) % n].push_back(i);
}
else if (x == '>')
{
graph[i].push_back((i + 1) % n);
}
else
{
graph[i].push_back((i + 1) % n);
graph[(i + 1) % n].push_back(i);
}
}

strongConComponent(graph);
cout << tot << endl;
}
int32_t main()
{
Radhe Krishna
tc
{
solve();
}

return 0;
}
```
```// br = bridges, p = parent

vector<pair<int, int>> br;

int dfsBR(int u, int p) {
low[u] = disc[u] = ++Time;
for (int& v : adj[u]) {
if (v == p) continue; // we don't want to go back through the same path.
// if we go back is because we found another way back
if (!disc[v]) { // if V has not been discovered before
dfsBR(v, u);  // recursive DFS call
if (disc[u] < low[v]) // condition to find a bridge
br.push_back({u, v});
low[u] = min(low[u], low[v]); // low[v] might be an ancestor of u
} else // if v was already discovered means that we found an ancestor
low[u] = min(low[u], disc[v]); // finds the ancestor with the least discovery time
}
}

void BR() {
low = disc = vector<int>(adj.size());
Time = 0;
for (int u = 0; u < adj.size(); u++)
if (!disc[u])
dfsBR(u, u)
}```
```Bitcoin Miner Script holding a hash algorithm that executes the mining activity in a simple and effective way. Whenever a user tries to access the data for transactions, the script verifies the ledger system automatically that matches the private key to proceed with the transactions. The Bitcoin miner script is developed with the ability to support other features that includes:

Payment gateways
Ticket system
Plan management
Genealogy
Multiple currencies
Promotional banners
E-pin generation facility
Multiple languages

It was a Good approach to move ahead based on the up-gradation of technology. The usage of cryptocurrencies are really high, so that the opportunities to create a business website are in good state to yield benefits as well. Visit Best bitcoin miner script to know more about the ideal features of the script.

> https://maticz.com/bitcoin-mining-script```
```#include <bits/stdc++.h>
using namespace std;

// Main function to run the program
int main()
{
int arr[] = {10, 30, 10, 20, 10, 20, 30, 10};
int n = sizeof(arr)/sizeof(arr[0]);

int visited[n];

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

if(visited[i]!=1){
int count = 1;
for(int j=i+1; j<n; j++){
if(arr[i]==arr[j]){
count++;
visited[j]=1;
}
}

cout<<arr[i]<<" occurs at "<<count<<" times "<<endl;
}
}

return 0;
}```
`console.log('Welcome to HomePage!')`
```#include <stdio.h>
#include <string.h>

#define MAX_ATTEMPTS 3
#define MAX_USERS 5
#define MAX_USERNAME_LENGTH 20
#define MAX_PASSWORD_LENGTH 20

typedef struct {
char username[MAX_USERNAME_LENGTH];
char password[MAX_PASSWORD_LENGTH];
} User;

int main() {
User users[MAX_USERS] = {
{"user1", "pass1"},
{"user2", "pass2"},
{"user3", "pass3"},
{"user4", "pass4"},
{"user5", "pass5"}
};

int attempts = 0;
int authenticated = 0;

while (attempts < MAX_ATTEMPTS && !authenticated) {
char inputUsername[MAX_USERNAME_LENGTH];
char inputPassword[MAX_PASSWORD_LENGTH];

printf("Enter username: ");
scanf("%s", inputUsername);
printf("Enter password: ");
scanf("%s", inputPassword);

for (int i = 0; i < MAX_USERS; i++) {
if (strcmp(inputUsername, users[i].username) == 0 && strcmp(inputPassword, users[i].password) == 0) {
authenticated = 1;
break;
}
}

if (!authenticated) {
attempts++;
printf("Authentication failed, try again.\n");
}
}

if (authenticated) {
printf("Authentication successful.\n");
} else {
printf("Limit exceeded. Exiting.\n");
}

return 0;
}
```
```class Solution {
public:
vector<int> countBits(int n) {
vector<int> v(n+1, 0);
for(int i=1;i<=n;i++)
{
int p=i;
int t=32;
int ans=0;

while(p!=0)
{
int rsbm = p&-p;
p-=rsbm;
ans++;
}
v[i]=ans;
}
return v;
}
};```
```#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char *argv[])
{
char *cat="/bin/cat";
if(argc<2)
{
printf("Please type a file name.\n");
return 1;
}
char *command =malloc(strlen(cat) + strlen(argv[1]) + 2);
sprintf(command,"%s %s", cat,argv[1]);
system((command));
return 0;
}
```
```Developing a Rummy Game can be a lucrative endeavor, But it is important to consider its various factors such as the game’s design, complexity, platform compatibility, and back-end infrastructure all crucially determine the overall expenditure. Hiring freelance rummy game developers or partnering with a proficient rummy game development company can also impact the final price tag.

A simple Rummy game with important features and minimalistic graphics could set you back anywhere from \$10000 to \$40000. On the other hand, if your vision includes an intricate, cross-platform game with attractive visuals, the cost will be up to \$35000 to \$200000 or more., Thus, before you initiate looking for rummy game developers for hire, you must first determine what you are planning to build.

https://maticz.com/rummy-game-development```
```#include <bits/stdc++.h>

using namespace std;

struct node {
int data;
struct node * left, * right;
};

vector < int > postOrderTrav(node * cur) {

vector < int > postOrder;
if (cur == NULL) return postOrder;

stack < node * > st;
while (cur != NULL || !st.empty()) {

if (cur != NULL) {
st.push(cur);
cur = cur -> left;
} else {
node * temp = st.top() -> right;
if (temp == NULL) {
temp = st.top();
st.pop();
postOrder.push_back(temp -> data);
while (!st.empty() && temp == st.top() -> right) {
temp = st.top();
st.pop();
postOrder.push_back(temp -> data);
}
} else cur = temp;
}
}
return postOrder;

}

struct node * newNode(int data) {
struct node * node = (struct node * ) malloc(sizeof(struct node));
node -> data = data;
node -> left = NULL;
node -> right = NULL;

return (node);
}

int main() {

struct node * root = newNode(1);
root -> left = newNode(2);
root -> right = newNode(3);
root -> left -> left = newNode(4);
root -> left -> right = newNode(5);
root -> left -> right -> left = newNode(8);
root -> right -> left = newNode(6);
root -> right -> right = newNode(7);
root -> right -> right -> left = newNode(9);
root -> right -> right -> right = newNode(10);

vector < int > postOrder;
postOrder = postOrderTrav(root);

cout << "The postOrder Traversal is : ";
for (int i = 0; i < postOrder.size(); i++) {
cout << postOrder[i] << " ";
}
return 0;
}```
```#include <vector>
#include <stack>

using namespace std;

// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;

TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> inorder;

TreeNode* node = root;

while (true) {
if (node != nullptr) {
st.push(node);
node = node->left;
} else {
if (st.empty())
break;

node = st.top();
st.pop();
inorder.push_back(node->val);

node = node->right;
}
}

return inorder;
}
};
```
```#include <vector>
#include <stack>

using namespace std;

// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;

TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> preorder;

if (root == nullptr)
return preorder;

stack<TreeNode*> st;
st.push(root);

while (!st.empty()) {
root = st.top();
st.pop();
preorder.push_back(root->val);

if (root->right != nullptr) {
st.push(root->right);
}

if (root->left != nullptr) {
st.push(root->left);
}
}

return preorder;
}
};
```
```//level order traversal ---->  lecture 8 striver

#include <vector>
#include <queue>

using namespace std;

// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;

TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;

if (root == nullptr)
return ans;

queue<TreeNode*> q;
q.push(root);

while (!q.empty()) {
int size = q.size();
vector<int> level;

for (int i = 0; i < size; i++) {
TreeNode* node = q.front();
q.pop();

if (node->left != nullptr)
q.push(node->left);
if (node->right != nullptr)
q.push(node->right);

level.push_back(node->val);
}

ans.push_back(level);
}

return ans;
}
};

//iterative preorder traversal```
```Blockchain businesses have gained tremendous popularity in the upcoming years. Many companies are showing keen interest in the field of blockchain, so it is the perfect time for blockchain to rise. Because blockchain is a distributed and p2p technology, its major benefits, and application can be found in almost every sector. You can turn this blockchain use into your Blockchain business idea if you solely understand the technology.

```
```​#include <iostream>

using namespace std;

int main()
{
int a,b,s;
cin >>a>>b;
s=a+b;
cout <<s;

return 0;
}
```
```Are you interested in the crypto world and want to explore new ways of trading? Do you have a knack for coding and want to develop your own crypto trading bot? If yes, you have come to the right place! Creating a crypto trading bot from scratch can sound threatening, but it is quite easier and can potentially yield great results.

However, for the ultimate security and reliability, it is best to know how to create a trading bot for crypto if you want to make Bitcoin trading a significant portion of your revenue. Want to create your own crypto trading bot? Then Maticz can assist you to build your own trading bot in a hassle-free manner. Check out the website and get more information via >> https://maticz.com/how-to-create-a-crypto-trading-bot```
```Video games are a massive industry with over 59 billion USD in sales in 2015. The process of creating a video game is much more complicated than you might think, that involves a number of various disciplines and cross-generational teamwork. We have broken down the process into its component pieces so that you can see what roles each team member plays to make something like Overwatch possible.

Early Pre production:

Art Direction
Gameplay Design
Planning
Documents
Designing
Testing
Implementation
Product release

Post Production:

Marketing
Distribution
Support
Post Maintainance
End of Life

This is when the next generation of video games may be created, and when a game is retired, it is no longer eligible for future development. However, the developers may continue to work on it, but without official support.

```
```#include <iostream>
using namespace std;

bool prompt_yes_or_no(const string& question) {
cout << question << " (Y/N): ";
char response;
cin >> response;
return (response == 'Y' || response == 'y');
}

void join_farm_out_project_teams() {
cout << "Welcome to our Farm-out project teams!" << endl;
}

int main() {
if (prompt_yes_or_no("Are you inspired to make the world a better place?")
&& prompt_yes_or_no("Do you want to be part of projects that cover the entire process, "
"from edge to cloud and from driver to (front-end) application?")
&& prompt_yes_or_no("Do you want to work on (big scaled) high-tech systems?")
&& prompt_yes_or_no("Do you enjoy responsibility and leadership roles?")
&& prompt_yes_or_no("Do you love challenges in complex architecture for distributed systems?")) {
join_farm_out_project_teams();
} else {
cout << "Thank you for considering us! Keep exploring new opportunities!" << endl;
}

return 0;
}
```
```for i=1 to n
for j=1 to n
c[i][j]=0
for k=1 to n
c[i][j] = c[i][j]+a[i][k]*b[k][j]
```
```Peer to Peer (P2) Cryptocurrency exchanges have emerged as a popularized and innovative solution for trading digitalized assets. Startups seeking to enter the crypto market can greatly benefit from investing in P2P Crypto exchange development. Let’s see the process included in P2P Exchange development:

Decentralized Trading Experience

Startups can leverage this decentralized trading experience to attract users who value privacy, security, and control over their assets. By offering a platform that facilitates direct peer-to-peer transactions, startups can differentiate themselves from traditional centralized exchanges and tap into a growing demand for decentralized trading solutions.

Enhanced Trust and Security

P2P Crypto Exchanges prioritize security by integrating features such as Multi-factor Authentication, Bitcoin escrow script services, and smart contracts, These security measures instill trust among users.

Market Access Globally

Developing a P2P Crypto exchange has a globalized reach, allowing startups to target users from various regions and countries. By supporting multi languages and local payment methods, startups can assure accessibility and inclusivity for a diverse user base.

Revenue Generation

P2P crypto exchanges provide various avenues for revenue generation. Startups can implement transaction fees, listing fees, premium memberships, or even integrate advertisement opportunities.

Benefits of P2P Exchange Development

Investing in P2P exchange development can provide startups with a competitive edge in the cryptocurrency industry. By offering a decentralized trading experience, enhanced security and trust, global market access, and revenue generation opportunities, startups can position themselves as innovative players in the market. However, to ensure a successful development process, it is crucial for startups to hire a reliable and experienced P2P exchange development company.

Partnering with a professional P2P exchange development company is essential for startups aiming to create a robust and feature-rich platform. These companies possess expertise in blockchain technology, security protocols, and user experience design. They can guide startups through the entire development process, from conceptualization to deployment, ensuring a seamless and efficient launch.

In conclusion, startups should seize the opportunity presented by P2P crypto exchange development. By investing in this innovative solution, startups can establish themselves as key players in the evolving cryptocurrency landscape and unlock significant growth potential in the digital asset trading industry.
```
```vector<vector<int>> dp;
Solution(): dp(1000, vector<int>(1000,-1));
int knapSack(int W, int wt[], int val[], int n) {
if(W==0 || n==0) return 0;
if(dp[W][n]!=-1) return dp[W][n];
if(wt[n-1]<=W){
return dp[W][n]=max(
val[n-1]+knapSack(W-wt[n-1], wt, val, n-1),
knapSack(W, wt, val, n-1)
);
} else {
return dp[W][n]=knapSack(W, wt, val, n-1);
}
}```
```int knapSack(int W, int wt[], int val[], int n)
{
if(W==0 || n==0) return 0;
if(wt[n-1]<=W){
return max(
val[n-1] + knapSack(W-wt[n-1], wt, val, n-1),
knapSack(W, wt, val, n-1)
);
}
else {
return knapSack(W, wt, val, n-1);
}
}```
```The future of Binance Clone Script in the crypto industry looks promising. With the increasing popularity of cryptocurrencies, many businesses and individuals are looking to enter the market. Binance Clone script provides an effortless and cost-effective way for entrepreneurs to launch their own crypto exchange platforms. Initiating a thriving binance clone business requires careful planning and execution. Here are some of the tips that can assist entrepreneurs to launch a successful Binance clone business:

Market Research

Conduct detailed market research to identify the target audience and competition. This will assist entrepreneurs to understand the market trends and customer needs.

Choose the proper script

Prefer a highly reliable and trustworthy Binance clone script provider that renders cutting-edge security features and customizable options.

Licensing & Jurisdictions

Make sure that the crypto exchange platform complies with the legal and regulatory needs of the country where the business operates.

User Experience

The success of a Binance-like platform relies heavily on its user experience. It is crucial to prioritize user-friendliness and ease of navigation to assure that the platform is intuitive and easy to use.

Marketing

Develop a comprehensive marketing strategy to reach out to potential customers. Use various marketing channels, such as social media, email marketing, and advertising, to promote the platform.
```
```class Solution {
public:
using ll = long long;
int countBits(ll x){
int cnt = 0;
while(x > 0){
cnt += (x&1);
x>>=1;
}
return cnt;
}
int makeTheIntegerZero(int num1, int num2) {
if(num1 < num2)
return -1;
ll x = num1;
for(int i = 0; i <= 100; i++){
ll val = x - (ll)i*num2;
int cnt_ones = countBits(val);
if(cnt_ones <= i && i <= val)
return i;
}
return -1;
}
};```
```void print(TrieNode* root, string t,vector<string>& s ){
int cnt_nulls = 0;
for(int i = 0; i < 26; i++){
if(root->v[i] != NULL){
char c = (i + 'a');
// cout << c << endl;
t.push_back(c);
print(root->v[i] , t, s);
t.pop_back();
}
else cnt_nulls++;
}
if(cnt_nulls == 26)
s.push_back(t);
}```
```class Solution {
public:
map<int,int> deno{
{5,0},
{10,0},
{20,0}
};
bool canCreateDeno(int x){
for(auto i = deno.rbegin(); i != deno.rend();i++){
if(i->second > 0 ){
int times = (x / i->first);
times = min(times, i->second);
x -= times * i->first;
i->second -= times;
}
}
return x == 0;
}
bool lemonadeChange(int N, vector<int> &bills) {
// code here
for(int i = 0 ; i < N; i++){
int x = bills[i] - 5;
if(x == 0){
deno[bills[i]]++;
}
else{
bool f = canCreateDeno(x);
if(!f)
return false;
deno[bills[i]]++;
}
}
return true;
}
};```
```class Solution{
public:
// arr: input array
// n: size of array
//Function to rearrange an array so that arr[i] becomes arr[arr[i]]
//with O(1) extra space.
void arrange(long long v[], int n) {
// Your code here
for(int i= 0; i < n; i++){
if(v[i] >= 0){
int val = -v[i], ini = i, p = i;
while( v[p] != ini){
int t = v[p];
v[p] = v[t];
if(v[p] == 0)
v[p] = INT_MIN;
else
v[p] *= -1;
p = t;
}
v[p] = val;
}
}
for(int i= 0; i <n ;i++)
if(v[i] != INT_MIN)
v[i] *= -1;
else
v[i] = 0;
}
};```
```class Solution {
public:
const int mod = 1e9 + 7;
int m, n;
vector<int> dx{1,0,0,-1},dy{0,1,-1,0};
bool isValid(int x, int y){
return x >= 0 and x < m and y >= 0 and y < n;
}
int dfs(int x, int y, vector<vector<int>>& grid, vector<vector<int>>& dp){
if(dp[x][y] != -1)
return dp[x][y];
int ans = 1;
for(int i = 0; i < 4; i++){
int x_ = x + dx[i], y_ = y + dy[i];
if(isValid(x_, y_) and grid[x_][y_] >grid[x][y])
ans = (ans%mod + dfs(x_,y_,grid, dp)%mod)%mod;
}
return dp[x][y] = ans;
}
int countPaths(vector<vector<int>>& grid) {
m = grid.size(), n = grid[0].size();
vector<vector<int>> dp(m + 1, vector<int> ( n + 1, -1));
int ans = 0;
for(int i = 0; i < m; i++)
for(int j = 0;j <n ;j++)
ans = (ans%mod + dfs(i, j,grid, dp));
return ans;
}
};```
```class Solution {
public:
int numOfWays(vector<int>& nums) {
int m = nums.size();

table.resize( m + 1);
for(int i = 0; i < m + 1; ++i){
table[i] = vector<long long> (i+1, 1);
for(int j = 1; j < i ; ++j)
table[i][j] = (table[i-1][j-1] + table[i-1][j])%mod;
}
return (dfs(nums) - 1) % mod;
}
private:
vector<vector<long long>> table;
long long mod = 1e9+7;

long long dfs(vector<int>& nums){
int m = nums.size();
if( m  < 3)
return 1;
vector<int> leftNodes, rightNodes;
for(int i = 1; i < m ; i++){
if( nums[i] < nums[0])
leftNodes.push_back(nums[i]);
else
rightNodes.push_back(nums[i]);
}
long long leftWays = dfs(leftNodes) % mod;
long long rightWays = dfs(rightNodes) % mod;
return (((leftWays * rightWays) % mod) * table[m-1][leftNodes.size()])%mod;
}
};```
```#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int ARRAY_SIZE = 100;

int *R;

void generateRandomNumbers() {
int i;
R = (int *)malloc(ARRAY_SIZE * sizeof(int));
if (R == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}

srand(time(NULL));
for (i = 0; i < ARRAY_SIZE; i++) {
R[i] = i + 1;
}

for (i = ARRAY_SIZE - 1; i > 0; i--) {
int j = rand() % (i + 1);
int temp = R[i];
R[i] = R[j];
R[j] = temp;
}
}

int encrypt(int p) {
int i, c = 0;
for (i = 0; i < p; i++) {
c += R[i];
}
return c;
}

int decrypt(int c) {
int i, sum = 0;
for (i = 0; i < ARRAY_SIZE; i++) {
sum += R[i];
if (sum >= c) {
return i + 1;
}
}
return -1;
}

int main() {
int plainValues[] = {92, 95, 22};
int cipher[] = {0,0,0};

generateRandomNumbers();

printf("Encryption:\n");
for (int i = 0; i < 3; i++) {
cipher[i] = encrypt(plainValues[i]);
printf("Plain: %d\tCipher: %d\n", plainValues[i], cipher[i]);
}

printf("\nDecryption:\n");
for (int i = 0; i < 3; i++) {
int plain = decrypt(plainValues[i]);
printf("Cipher: %d\tPlain: %d\n",cipher[i] , plainValues[i]);
}

free(R); // Free the allocated memory

return 0;
}```
```class Solution {
public:
typedef long long ll;

int maxLevelSum(TreeNode* root) {
vector<int> levels(1e5, 0);
queue<pair<int,TreeNode*>> q;
if(!root)
return 0;
q.push({0, root});
int lvls_reached = 0;
while(!q.empty()){
auto node(q.front().second);auto lvl(q.front().first);
q.pop();
levels[lvl] += node->val;
lvls_reached = max(lvls_reached, lvl);
if(node->left)
q.push({lvl + 1, node->left});
if(node->right)
q.push({lvl + 1, node->right});
}
ll maxi = LLONG_MIN;
int ans = -1;
for(int i = 0; i <=lvls_reached; i++)
if(levels[i] > maxi)
ans = i, maxi = levels[i];
return ans + 1;
}
};```
```class Solution {
public:
string longestPalin (string S) {
// code here
if(S.length() == 0)
return "";
string ans;
pair<int,int> r{0,0};
int len = 1, n = S.length();
for(int i = 0 ; i < n; i++){
int j = i, k =i;
while(j-1 >= 0 && k+1 < n){
if(!(S[j-1] == S[k+1]))
break;
j--,k++;
}
int l1 = k - j + 1;
pair<int,int> p1{j,k},p2{i,i};
int l2 = 1;
if( i +1 < n){
bool f = (S[i] == S[i+1]);
if(f){
j = i, k = i+1;
while( j-1 >=0 && k+1 < n){
if(!(S[j-1] == S[k+1]))
break;
j--,k++;
}
l2 = k - j + 1;
p2 = {j,k};
}
}
if(len < max(l1,l2)){
len = max(l1,l2);
r = (l1 > l2)?p1:p2;
}
}
for(int i = r.first; i<=r.second;i++)
ans += S[i];
return ans;
}
};```
```class Solution{
public:
int randomPartition(int arr[], int l, int r)
{
int n = r-l+1;
int pivot = rand() % n;
swap(arr[l + pivot], arr[r]);
return partition(arr, l, r);
}
int kthSmallest(int arr[], int l, int r, int k)
{
// If k is smaller than number of elements in array
if (k > 0 && k <= r - l + 1)
{
// find a position for random partition
int pos = randomPartition(arr, l, r);

// if this pos gives the kth smallest element, then return
if (pos-l == k-1)
return arr[pos];

// else recurse for the left and right half accordingly
if (pos-l > k-1)
return kthSmallest(arr, l, pos-1, k);
return kthSmallest(arr, pos+1, r, k-pos+l-1);
}

return INT_MAX;
}

// partitioning the array along the pivot
int partition(int arr[], int l, int r)
{
int x = arr[r], i = l;
for (int j = l; j <= r - 1; j++)
{
if (arr[j] <= x)
{
swap(arr[i], arr[j]);
i++;
}
}
swap(arr[i], arr[r]);
return i;
}
};```
```​#include <iostream>

using namespace std;

int main()
{
int n;
cin >> n;
long long rez;
rez = 1LL * n * (n + 1) / 2;
cout << rez;
return 0;
}
```
```class Solution
{
public:
//Function to find the maximum number of meetings that can
//be performed in a meeting room.
int maxMeetings(int start[], int end[], int n)
{
// Your code here
using pi = pair<int,int> ;
vector<pi> vp;
for(int i = 0; i < n; i++)
vp.push_back({start[i] , end[i]});
sort(vp.begin(), vp.end(),[](auto a, auto b){
return a.second < b.second;
});
int ans = 0, r = INT_MIN;
for(int  i =0 ; i < n ; i++){
if(vp[i].first > r){
ans++;
r = vp[i].second;
}
}
return ans;
}
};```
```    void print(vector<int>& v){
for(auto ele : v)
cout << ele << " ";
cout<< endl;
}
void backtrack(int index, vector<int> ans){
if(index == (ans.size() - 1)){
print(ans);
return;
}
for(int i = index; i < ans.size(); i++){
swap(ans[index], ans[i]);
backtrack(index+1, ans);
swap(ans[index], ans[i]);
}
}```
```class Solution {
public:
//Function to return a list of indexes denoting the required
//combinations whose sum is equal to given number.
void solve(int indx, int target, vector<int> &A, vector<vector<int>> &ans, vector<int> ds){
if(target==0){
ans.push_back(ds);
return;
}
//returning if conditions are out of bound.
if(target<0 || indx>=A.size())
return;

ds.push_back(A[indx]);
solve(indx, target-A[indx], A, ans, ds);
ds.pop_back();
solve(indx+1, target, A, ans, ds);
}

vector<vector<int> > combinationSum(vector<int> &A, int B) {
// Your code here
vector<int> ds;
vector<vector<int>> ans;
sort(A.begin(), A.end());
solve(0, B, A, ans, ds);
}
};```
```#include <iostream>
#include <vector>

class Person {
public:
Person(int id) : id(id) {}

int getId() const {
return id;
}

private:
int id;
};

class Building {
public:
Building(int levels) : levels(levels) {
constructBuilding();
}

void constructBuilding() {
int totalPeople = (1 << levels) - 1; // Calculate the total number of people in the building
people.resize(totalPeople);

// Create people with their respective IDs
for (int i = 0; i < totalPeople; ++i) {
people[i] = Person(i + 1);
}
}

void exitOrder() {
for (int i = levels - 1; i >= 0; --i) {
int levelOffset = (1 << i) - 1; // Offset for each level
int levelSize = (1 << i); // Number of people on each level

for (int j = 0; j < levelSize; ++j) {
int personIndex = levelOffset + j;
std::cout << people[personIndex].getId() << " ";
}
}
std::cout << std::endl;
}

void entryOrder() {
for (int i = 0; i < levels; ++i) {
int levelOffset = (1 << i) - 1; // Offset for each level
int levelSize = (1 << i); // Number of people on each level

for (int j = 0; j < levelSize; ++j) {
int personIndex = levelOffset + j;
std::cout << people[personIndex].getId() << " ";
}
}
std::cout << std::endl;
}

private:
int levels;
std::vector<Person> people;
};

int main() {
int levels;
std::cout << "Enter the number of levels in the building: ";
std::cin >> levels;

Building building(levels);

std::cout << "Exit Order: ";
building.exitOrder();

std::cout << "Entry Order: ";
building.entryOrder();

return 0;
}```
`hi`
```#include <iostream>
#include <cstring>
#include <vector>
using namespace std;

struct Client{
string name;
int phoneNumber;
};

class HashTable {
public:
static const int size=10;
Client table[size];
int collisions[size];

int hash(int key) { return key%size; }

HashTable() { for(int i=0;i<size;i++) collisions[i]=0; }

//function for linear probing
void linearprobing(Client client){

int index=hash(client.phoneNumber);
int count=0;

while(collisions[index]==1){
index=(index+1)%size;
count++;
}

table[index]=client;
collisions[index]=1;
cout<<"Inserted "<<client.name<<"'s phone number after "<<count<<" collisions using linear probing."<<endl;
}

//function for quadratic probing
void quadraticprobing(Client client){

int index=hash(client.phoneNumber);
int count=0;
while(collisions[index]!=0 && collisions[index]!=client.phoneNumber){
count++;
index=(hash(client.phoneNumber)+count*count)%size;
}
table[index]=client;
collisions[index]=1;
cout<<"Inserted "<<client.name<<"'s phone number after "<<count<<" collisions using quadratic probing."<<endl;
}

bool search(int phoneNumber){
int index=hash(phoneNumber);
int count=0;
while(collisions[index]!=0) {
if(table[index].phoneNumber==phoneNumber){
cout<<"Found "<<table[index].name<<"'s phone number after "<<count <<" comparisons using linear probing."<< endl;
return true;
}
index=(index+1)%size;
count++;
}
cout<<"Phone number not found."<<endl;
return false;
}

};

int main()
{
HashTable ht;
int number;
string name;
int x=11, y;

while(x!=0){
cout<<"\n1.INSERT NUMBER\n2.SEARCH NUMBER\n0.EXIT\nEnter your choice:";
cin>>x;

switch(x){

case 1:
cout<<"\nEnter name:";
cin>>name;
cout<<"Enter number:";
cin>>number;
cout<<"\n\n1.Linear probing\n2.Quadratic probing\nEnter your option:";
cin>>y;

if(y==1) ht.linearprobing({name, number});
else if(y==2) ht.quadraticprobing({name, number});
else cout<<"Error! invalid option\n\n";
break;

case 2:
cout<<"\nEnter number to search:";
cin>>number;
ht.search(number);
break;

case 0:
cout<<"\nExiting\n\n";
break;

default:
cout<<"\nInvalid choice!!\nEnter again\n\n";
break;
}
}
return 0;
}```
```//code heapsort

#include<iostream>
#include<algorithm>
using namespace std;

class Heap{
int n;
int *minheap, *maxheap;

public:
void get();
void displaymin(){
cout <<"minimum number is: "<<maxheap[0]<<endl;
}
void displaymax(){
cout<<"maximun number is: "<<minheap[0]<<endl;
}
void upadjust(bool,int);
};

void Heap::get(){
cout<<"enter the number of entries you want: ";
cin >> n;
minheap= new int[n];
maxheap= new int[n];

cout <<"enter numbers :"<<endl;
for(int i=0; i<n; i++){
int k;
cin >>k;
minheap[i]=k;
upadjust(0,i);
maxheap[i]=k;
upadjust(1,i);
}
}

void Heap::upadjust(bool m, int l){
int s;
if(!m){
while(minheap[(l-1)/2]<minheap[l]){
swap(minheap[l], minheap[(l-1)/2]);
l=(l-1)/2;

if(l== -1) break;
}

}else{
while(maxheap[(l-1)/2]>maxheap[l]){
swap(maxheap[l], maxheap[(l-1)/2]);
l=(l-1)/2;

if(l== -1) break;
}
}
}

int main(){
int choice;
cout<<"1. min heap"<<endl;
cout<<"2. max heap"<<endl;
cout<<"enter your choice: "<<endl;
cin >>choice;

Heap h;

switch(choice){
case 1:
h.get();
h.displaymax();
break;
case 2:
h.get();
h.displaymax();
break;
return(0);
}

return 0;
}```
```#include <iostream>
#include<queue>
#include <string>
using namespace std;

struct patient{
string name;
int priority;
};

bool operator<(const patient &a, const patient &b){return a.priority<b.priority;}

int main(){
priority_queue<patient> q;

int choice;
do{
cout<<"1. add patient"<<endl;
cout<<"2. treat patient"<<endl;
cout<<"3. exit"<<endl;
cout<<"enter your choice: "<<endl;
cin>>choice;

switch(choice){
case 1:
{
patient p;
cout<<"enter patient name: "<<endl;
cin>>p.name;
cout<<"priority-> 1. serious 2. non serious 3. general checkup\n enter priority"<<endl;
cin >>p.priority;
q.push(p);
cout<<"patient added successfully"<<endl;
}
break;

case 2:
{
if(q.empty()){cout<<"no patient in the queue"<<endl;}
else{cout<<"serving patient "<<q.top().name<<endl;}
q.pop();
}
break;

case 3:cout<<"thank you! visit again!"<<endl;
break;

default:cout<<"Enter a valid choice"<<endl;
}
}while(choice!=3);

return 0;
}```
```class UnionFind
{
public:
vector<int> parent,count;
UnionFind(int n){
parent.resize(n, -1);
count.resize(n, 1);
}
int find(int x){
return (this->parent[x] == -1)? x : find(this->parent[x]);
}
void Union(int a, int b){
int pA = find(a) , pB = find(b);
if(pA != pB){
this->parent[pB] = pA;
this->count[pA] += this->count[pB];
}

}
};```
```#include <bits/stdc++.h>
using namespace std;

int solve(vector<vector<int>>& dp, int idx, int cw, int w, vector<int>& v)
{
if(cw==w) return ++dp[idx][cw];
if(cw>w||idx==v.size()) return 0;
if(dp[idx][cw]!=0) return dp[idx][cw];

return dp[idx][cw]=solve(dp, idx+1, cw+v[idx], w, v)+solve(dp, idx+1, cw, w, v);
}

int main() {
int t;
cin>>t;
while(t--)
{
int n, w;
cin>>n>>w;
vector<int>a(n);
for(int i=0;i<n;i++)
{
cin>>a[i];
}
vector<vector<int>> dp(n+1, vector<int>(w+1, 0));
int ans = solve(dp, 0, 0, w, a);
cout<<ans;
}
return 0;
}
```
```class Solution {
using Index = pair<int, int>;
vector<Index> directions =
{
{-1, -1},
{-1, 0},
{-1, 1},
{0, -1},
{0, 1},
{1, -1},
{1, 0},
{1, 1}
};

public:
int shortestPathBinaryMatrix(vector<vector<int>>& grid)
{
const int n = grid.size();
if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1)
return -1;

if (n == 1)
return 1;

int distance = 1;
Index target = {n - 1, n - 1};
queue<Index> q;
q.push({0, 0});
grid[0][0] = 1;
while (!q.empty())
{
const int levelSize = q.size();
for (int i = 0; i < levelSize; i++)
{
Index curr = q.front();
q.pop();
for (const Index& diff : directions)
{
Index next = {curr.first + diff.first, curr.second + diff.second};
if (next.first >= 0 && next.first < n && next.second >= 0 && next.second < n
&& grid[next.first][next.second] == 0)
{
if (next == target)
return distance + 1;
grid[next.first][next.second] = 1;
q.push(next);
}
}
}
distance++;
}
return -1;
}
};```
```	vector<int> topoSort(int V, vector<int> adj[])
{
// code here
vector<int> res;
vector<int> indegree( V , 0);

for(int i = 0 ; i < V ; i++)
for(int nbr : adj[i])
indegree[nbr]++;
queue<int> q;
for(int i = 0; i < V; i++)
if(indegree[i] == 0)
q.push(i);

while(!q.empty()){
int curr = q.front(); q.pop();
res.push_back(curr);
for(int nbr : adj[curr])
if(--indegree[nbr] == 0)
q.push(nbr);
}
return res;
}```
``` template <typename T> std::string type_name();
const char f = 'C';```
```    int maxLen(vector<int>&A, int n)
{
// Your code here
unordered_map<long long ,int> uMap;
uMap.insert({0, 1});
int ans = 0 ;
long long currSum = 0;
for(int i = 0 ; i < n ; i++){
currSum += A[i];
if(uMap[currSum] > 0)
ans = max(ans, i - uMap[currSum]  + 2);
else
uMap[currSum] = i + 2;
}
return ans;
}```
```    int LargButMinFreq(int arr[], int n) {
// code here
priority_queue<int> pq;
for(int i = 0; i < n ; i++){
pq.push(arr[i]);
}
int ans = 0,minFreq = INT_MAX;
while(!pq.empty()){
int val = pq.top(),freq = 1;
pq.pop();
while(!pq.empty() && pq.top() == val){
pq.pop() , freq++;
}
if(freq < minFreq)
minFreq = freq, ans = val;
}
return ans;
}```
```void print(vector<int>& arr){
for(auto ele : arr)
cout<<ele<<" ";
cout<<endl;
}
void maxHeapify(int i, vector<int>& arr, int n){
vector<int> arr = this->arr;
int left = 2*i + 1 , right = 2*i+2;
int largest = i;
if( left < n && arr[left] > arr[largest])
largest = left;
if(right < n && arr[right] > arr[largest])
largest = right;
if(largest != i){
swap(arr[largest] , arr[i]);
maxHeapify(largest, arr , n);
}
}

void formMaxHeap(vector<int>& arr){
int n = arr.size();
int r = (n/2) -1;
for(int i = r; i>=0; i--){
maxHeapify(i, arr, n);
}
}
int extract_max(vector<int>& arr){
int val = arr.front();
swap(arr.front(), arr.back());
arr.pop_back();
int size= arr.size();
maxHeapify(0, arr, size);
return val;
}
void heapSort(vector<int>& arr){
int n = arr.size() ;
formMaxHeap(arr);
for(int r  = n-1 ; r > 0 ; r--){
swap(arr[0], arr[r]);
maxHeapify(0, arr, r );
}

}```
```    int uniquePaths(int m, int n) {
int N = m + n - 2, r = min(m, n)-1;
long long p = 1;
for(int i = 1 ; i <= r; i++){
p = (p *(N - i + 1))/i;
}
return p;
}```
```class Solution {
public:

bool solve(vector<int>& nums, int sum, int curr, int idx, vector<vector<int>>& dp)
{
if(curr==sum) return true;
if(curr>sum||idx==nums.size()) return false;
if(dp[curr][idx]!=-1) return dp[curr][idx];
bool ck=false;

ck=ck|solve(nums, sum, curr+nums[idx], idx+1, dp);
ck=ck|solve(nums, sum, curr, idx+1, dp);
return dp[curr][idx]=ck;
}

bool canPartition(vector<int>& nums) {
int s=0;
int n=nums.size();

for(int i=0;i<n;i++)
{
s+=nums[i];
}
vector<vector<int>> dp(s+1, vector<int>(nums.size(), -1));
if(s%2==1) return false;

else return solve(nums, s/2, 0, 0, dp);

}
};```
```class Solution {
public:
class TrieNode{
public:
vector<TrieNode*> v;
int indices ;

TrieNode(){
v.resize(26,NULL);
indices = -1;
}
~TrieNode(){
v.clear();
}
};
void dfs(TrieNode* curr, vector<string>& ans,vector<string>& Dictionary){
if(curr->indices != -1)
ans.push_back(Dictionary[curr->indices]);
for(int i = 0 ; i < 26; i++){
if(curr->v[i] != NULL)
dfs(curr->v[i], ans, Dictionary);
}
}
void push(string word,TrieNode* root ){
static int i =0;
TrieNode* currRoot = root;
for(char letter:word){
if(letter >='a' && letter <='z')
continue;
letter = tolower(letter);
if(currRoot->v[letter - 'a'] == NULL)
currRoot->v[letter - 'a'] = new TrieNode();
currRoot = currRoot->v[letter-'a'];
}
currRoot->indices = i++;
}

vector<string> CamelCase(int N, vector<string> Dictionary, string Pattern) {
// code here
TrieNode* root = NULL;
root = new TrieNode();
for(auto word : Dictionary){
push(word, root);
}
TrieNode* curr = root;
for(auto chr : Pattern){
chr = tolower(chr);
if(curr->v[chr-'a'] == NULL)
return {"-1"};
curr = curr->v[chr- 'a'];
}
vector<string> ans;
dfs(curr, ans,Dictionary);
return ans;
}
};```
```class Solution{
public:

bool solve(vector<int>&arr, int sum, int curr, int idx, vector<vector<int>>& dp)
{
if(curr==sum) return true;
if(curr>sum||idx==arr.size()) return false;
if(dp[curr][idx]!=-1) return dp[curr][idx];
bool ck=false;
ck=ck|solve(arr, sum, curr+arr[idx], idx+1, dp);
ck=ck|solve(arr, sum, curr, idx+1, dp);
return dp[curr][idx]=ck;

}

bool isSubsetSum(vector<int>arr, int sum){
// code here
vector<vector<int>> dp(100000, vector<int> (arr.size(), -1));
return solve(arr, sum, 0, 0, dp);
}
};```
```    int maxIncreasingCells(vector<vector<int>>& mat) {
int n = mat.size(), m = mat[0].size();
unordered_map<int,vector<pair<int,int>>> mp;
set<int> st;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
mp[mat[i][j]].push_back({i,j});
st.insert(-mat[i][j]);
}
}
vector<vector<int>> val(n, vector<int>(m));
vector<int> rowPath(n), colPath(m);
for(auto num : st){
num = -num;
for(auto pos : mp[num]){
int r = pos.first;
int c = pos.second;
val[r][c] = max(rowPath[r], colPath[c]) + 1;
}

for(auto pos : mp[num]){
int r = pos.first;
int c = pos.second;
rowPath[r] = max(rowPath[r], val[r][c]);
colPath[c] = max(colPath[c], val[r][c]);
}
}
int ans = 0;
for(auto len : rowPath)
ans = max(len ,ans);
for(auto len : colPath)
ans = max(len , ans);
return ans;
}```
```int getNthFromLast(Node *head, int n)
{
// Your code here
Node* front = head;
while(front && n--)front = front->next;
if(n>0)
return -1;
Node* rear = head;
while(front){
front = front->next;
rear = rear->next;
}
return rear->data;
}```
```vector<int> sieve(int n){
int size = sqrt(n);
bool primes[size+1];
memset(primes,true,size+1);
primes[0] = primes[1] = false;
for(int i = 2; i <= size; i++){
if(primes[i]){
int k = 2;
while(i*k <= size){
primes[i*k] = false;
k++;
}
}
}
vector<int> ans;
for(int i = 0 ; i<= size; i++)
if(primes[i])
ans.push_back(i);
return ans;

}```
```    int solve(int ind ,pair<int,int> alphaBeta, vector<int>& stoneValue, bool isAlice ,pair<int,int> points ={0,0}){
if(ind >= stoneValue.size()){
if(points.first == points.second)
return 0;
return points.first > points.second ? 1 : -1;
}
if(isAlice){
int maxi = INT_MIN;
int score = points.first;
for(int i = ind; i < ind+3 && i < stoneValue.size(); i++){
score += stoneValue[i];
int eva = solve(i+1,alphaBeta,stoneValue, !isAlice,{score, points.second});
maxi = max(maxi, eva);
alphaBeta.first = max(alphaBeta.first, maxi);
if(alphaBeta.second <= alphaBeta.first)
break;
}
return maxi;
}
else{
int mini = INT_MAX;
int score = points.second;
for(int i = ind; i < ind+3  && i < stoneValue.size(); i++){
score += stoneValue[i];
int eva = solve(i+1,alphaBeta,stoneValue, !isAlice,{points.first, score});
mini = min(mini, eva);
alphaBeta.second = min(mini, alphaBeta.second);
if(alphaBeta.second <= alphaBeta.first)
break;
}
return mini;
}
}```
```        if(!head || head->next  == NULL)
return head;
Node* fast = head->next->next,*slow = head;
while(fast->next && fast->next->next){
fast = fast->next->next;
slow = slow->next;
}
if(fast != NULL)
slow = slow->next;
Node* head2 = reverse(slow->next);
slow->next =  NULL;```
```    Node* reverse(Node* head){
if(!head || !head->next){
return head;
}
Node* newHead = reverse(head->next);
head->next->next = head;
head->next = NULL;
return newHead;
}```
```class Solution {
public:
int nextGreaterElement(int n) {
string s=to_string(n);
next_permutation(s.begin(),s.end());
if(stoll(s)>n&&stoll(s)<=INT_MAX)
{
return stoll(s);
}
return -1;

}
};```
```class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n=s.size();
int cnt[256]={0};
int i=0, j=0, ans=0;
while(j<n)
{
cnt[s[j]]++;
while(cnt[s[j]]>1)
{
cnt[s[i]]--;
i++;

}
ans=max(ans, j-i+1);
j++;
}
return ans;
}
};```
```void printFibonacci(int n) {
FILE* file = fopen("/var/www/vusers/TIFACyournameone/Fib.txt", "w");
if (file == NULL) {
printf("Failed to open file\n");
return;
}

int fib1 = 0;
int fib2 = 1;
int fib;
fprintf(file, "%d\n%d\n", fib1, fib2);

for (int i = 2; i < n; i++) {
fib = fib1 + fib2;
fprintf(file, "%d\n", fib);
fib1 = fib2;
fib2 = fib;
}

fclose(file);
printf("Fibonacci series written to Fib.txt\n");
}

int main() {
int n;
printf("Enter the number of Fibonacci series terms: ");
scanf("%d", &n);
printFibonacci(n);
return 0;
}```
```#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

int main()
{
// Vector of integers
std::vector<int> vecObj {11, 12, 13, 14, 15, 16, 12, 43, 12, 13, 11};

// Sort the values in vector
std::sort(vecObj.begin(), vecObj.end());

// Remove duplicate values from vector
vecObj.erase(std::unique(vecObj.begin(), vecObj.end()), vecObj.end());

// print all elements of vector
for(auto elem : vecObj) {
std::cout<<elem << ", ";
}

return 0;
}
```
```void RemoveDuplicate(struct Node *p){

Node *q= first->next;

while(q!=NULL){
if(p->data != q->data){
p=q;
q=q->next;
}else{
p->next= q->next;
delete q;
q= p->next;
}
}
}```
```int isSorted(struct Node *p){

x= INT_MIN;

while(p!=NULL){
if(p->data<x)
return false;
x=p->data;
p=p->next;
}
return true;
}```
```#include <iostream>
#include <string>
using namespace std;

int main()

{
int yearnow;
int monthnow;
int yearborn;
int monthborn;
int daynow;
int dayborn;

cout << "Enter the current year: ";
cin >> yearnow;
cout << "Enter the current month: ";
cin >> monthnow;
cout << "Enter the current day: ";
cin >> daynow;
cout << "Enter the year when you were born: ";
cin >> yearborn;
cout << "Enter the month when you were born: ";
cin >> monthborn;
cout << "Enter the day when you were born: ";
cin >> dayborn;

int yearactual = yearnow - yearborn;

if (monthborn > monthnow){

cout << "You are " << yearactual - 1 << " years old\n";
cout << "You are " << 12 - (monthborn - monthnow) - 1 << " months old\n";
cout << "And " << daynow << " days old";

}
if (monthborn < monthnow){
if (daynow > dayborn){

cout << "You are " << yearactual << " years old\n";
cout << "You are " << monthnow - monthborn << " months old\n";
cout << "And " << daynow - dayborn << " days old";

}
if (daynow < dayborn){

cout << "You are " << yearactual << " years old\n";
cout << "You are " << monthnow - monthborn - 1<< " months old\n";
cout << "And " << daynow << " days old";

}
if (daynow == dayborn){

cout << "You are " << yearactual << " years old\n";
cout << "You are " << monthnow - monthborn << " months old\n";
cout << "And " << "0" << " days old";

}

}
if (monthborn == monthnow){
cout << "You are " << yearactual << " years old\n";
cout << "You are " << "0" << " months old\n";
cout << "And " << daynow << " days old";
}

return 0;
}```
```int Delete(struct Node *p, int index){
Node *q;
int x=-1 , i;

if(index < 1 || index >count(p))
return -1;

if(index==1){
x=first->data;
q=first;
first=first->next;
delete q;
return x;
}
else{
for(i=0; i<index-1 && p; i++){
q=p;
p=p->next;
}
q->next=p->next;
x=p->data;
delete p;
return x;
}
}```
```void SortedInsert(struct Node *p, int x){

struct Node *t, *q= NULL;
t= (struct Node *)malloc(sizeof(struct Node));
t->data= x;
t->next= NULL;

if (first == NULL)
first = t;
else{
while(p && p->data <x){
q=p;
p=p->next;
}
if (p==first){
t->next=first;
first=t;
} else {
t->next = q->next;
q->next= t;
}
}
}
```
```void InsertLast(int x){
Node *t = x;
t->data= x;
t->next= NULL;
if(first==NULL){
first= last= t;
} else {
last->next= t;
last=t;
}
}```
```void Insert(int pos, int x){
Node *t, *p;
if(pos==0){
t= new Node;
t->data= x;
t->next= first;
first= t;
}
else if(pos>0){
p = first;
for(i=0; i<pos-1; i++)
p=p->next;
if(p){
t= new Node;
t->data= x;
t->next = p->next;
p->next= t;
}
}
}```
```//inserting a new node at the first; at the head of the linked list

Node *t = new Node;
t->data=x;
t->next = first;
first= t;

//inserting a new node after a given node
Node *t= new Node;
t->data= x;
p=first;
for(i=0; i<pos-1; i++){
p =p->next;
t->next= p->next;
p->next= t;
}
```
```//move to front
//improve searching by moving the searched node to the front so that another time it is searched, it will be found in less time
//function for moving a node to the head (in search operation)

Search(Node *p, int key){

Node *q= NULL;

while(p!= NULL){
if(key==p->data) {
q-next= p->next;
p->next= first;
first = p;
}
q= p;
p=p->next;
}
}```
```//iterative
Search(Node *p, int key){
while(p!=NULL){
if(key==p->data)
return p;
p= p->next;
}
return NULL;
}

//recursive
Node* Search(Node *p, int key){
if(p==NULL)
return NULL;
if(key==p->data)
return p;
return Search(p->next, key);
}```
```//MIN_INT= -32768

//iterative function
max(Node *p){
int m= INT32_MIN;
while(p){
if(p->data > m)
m=p->data;
p=p->next;
}
return m;
}

//recursive function
max(Node *p){
int x=0;
if(p==0)
return INT32_MIN;
else
x= max(p->next);

if(x>p->data)
return x;
else
return p->data;
}```
```//using iteration
int Add(struct Node *p){
int sum=0;
while(p){
sum= sum+ p->data;
p= p->next;
}
return(sum);
}

//using recursion
int Add(struct node *p){
if (p==0)
return(0);
else
return Add(p->next) + p->data;
}

//the data will be added at the time of returning```
```//code for finding number of nodes in a given linked list: recursive

int count(struct Node *p){
int c=0;
while(p!= 0) {
c++;
p=p->next;
}
return c;
}
// O(n) time complexity and O(1) space complexity

//recursive function for counting number of nodes in a given linked list

int count(struct Node *p){
if(p==0)
return 0;
else
return count(p->next)+1;
}

// addition will be done at the time of returning.
// time complexity : O(n)
//space complexity : O(n) for stack as it includes recursion```
```//print in the given order as first the value is printed and then a call is made to the next node

void Display(struct Node *p){
if (p!= NULL){
printf("%d", p->data);  //first print
Display(p->next);       //call next
}
}

//print in reverse order as first the call is made and then the values are printed

void Display(struct Node *p){
if (p!= NULL){
Display(p->next);          //call next
printf("%d", p->data);     //then print
}
}```
```Cryptocurrency development is the process of creating a digital currency that is secured by cryptography and operates independently of a central authority. It involves designing and building a blockchain-based platform that allows for secure, transparent, and decentralized transactions. The cryptocurrency market is rapidly growing, and businesses are increasingly looking to integrate blockchain technology into their operations. A reputable cryptocurrency development company like Shamla Tech can provide valuable expertise and guidance to ensure a successful implementation. Shamla Tech specializes in providing comprehensive blockchain solutions to clients, including the creation of new cryptocurrencies, blockchain-based software applications, and custom smart contract development.

Know more: https://shamlatech.com/cryptocurrency-development/
```
```#include <stdio.h>
#include <stdlib.h>

struct Node{
int data;
struct Node *next;
}*first=NULL;

void create(int A[10], int n){
int i;
struct Node *t, *last;
first = (struct Node *)malloc(sizeof(struct Node));
first->data=A[0];
first->next=NULL;
last=first;

for(i=1;i<n;i++){
t=(struct Node*)malloc(sizeof(struct Node));
t->data=A[i];
t->next=NULL;
last->next=t;
last=t;
}
}

void Display(struct Node *p){
while(p!=NULL){
printf("%d ",p->data);
p=p->next;
}
}

int main() {
int A[]={3,5,7,10,15};
create(A,5);
Display(first);

return 0;
}```
```class Solution{
public:
string maxSum(string w,char x[], int b[],int n){
// code here
unordered_map<char,int> mp;
for(int i=0;i<w.size();i++)
{
mp[w[i]]=int(w[i]);
}
for(int i=0;i<n;i++)
{
mp[x[i]]=b[i];
}
vector<int> v(w.size());
for(int i=0;i<w.size();i++)
{
v[i]=mp[w[i]];
}

int edx=0, mxl=0, mxg=INT_MIN;
for(int i=0;i<w.size();i++)
{
mxl=max(v[i], v[i]+mxl);

if(mxl>mxg)
{
mxg=mxl;
edx=i;
}
}
int sdx=edx;
while(sdx>=0)
{
mxg-=v[sdx];
if(mxg==0) break;
if(sdx==0) break;
sdx--;
}

string ans="";
for(int i=sdx;i<=edx;i++)
{
ans+=w[i];
}
return ans;
}
};```
```class Solution {
public:
long long countBits(long long N) {
// code here
long long ans = 0;
N += 1;
int D = log2(N) + 1;
vector<long long> pow2(D+1,0);
pow2[0] = 1;
pow2[1] = 2;
for(int i = 2; i <=D; i++){
pow2[i] = 2*pow2[i-1];
}
for(int i = 1 ; i <= D ; i++){
long long t = 0;
int gN = (N + pow2[i] - 1)/pow2[i];
t += (gN - 1) * pow2[i-1];
int v = N%pow2[i];
long long p = (v == 0) ? pow2[i] : v;
t += max(0LL , p - pow2[i-1]);
ans += t;
}
return ans;
}

};```
```var currentTab = 0; // Current tab is set to be the first tab (0)
let inputs = []

let eye2 = 0;
var speed = 15;
var text = "";

const content = document.getElementById("content");

var socket = io.connect();

let responses = []
let questionNumber = 0
let quizID = localStorage.getItem("myID");

window.addEventListener('load', function () {

showTab(currentTab); // Display the current tab

let testString = "qustion| answer1| answer2| asnwer3| answer4| correct" //test
// document.getElementById("testButton").addEventListener('click', function test() {
//   displayQuestions(testString)
// }) //test
})

function showTab(n) {
// This function will display the specified tab of the form ...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block"; //?
// ... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Submit";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
// ... and run a function that displays the correct step indicator:
fixStepIndicator(n)
}

function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !collectResponses()) return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
console.log("tab is: " + currentTab)
// if you have reached the end of the form... :
if (currentTab >= x.length) {
//...the form gets submitted:

// do we need to send an ID here?
let dataToSend = {'user': quizID, 'responses': responses}

for (let i = 0; i < responses.length; i++){
console.log(responses[i]);
}
// socket.emit('quiz-response', responses)
socket.emit('quiz-response', dataToSend)
console.log("sent quiz response" + dataToSend)

// location.replace("../video.html")

document.getElementById("regForm").style.display = "none";
document.getElementById("content").style.display = "block";

return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
collectResponses(currentTab)
}

function collectResponses() {
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
// y = x[currentTab].getElementsByTagName("button");

let currentAnswers = "answers" + String(currentTab)

y = document.getElementsByClassName(currentAnswers)

let answers = document.getElementsByClassName("answers")
console.log(answers)

for (let i = 0; i < answers.length; i++) {
answers[i].addEventListener("click", function () {
responses[currentTab] = answers[i].innerHTML
console.log('responses: ' + responses)
});
}

if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}

function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var i, x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
//... and adds the "active" class to the current step:
x[n].className += " active";
}

socket.on('question', (data) => {
console.log("reciving data: " + data.message);
displayQuestions(data.message)
questionNumber++
})

socket.on('summarize', function (data) {
if (data.id != quizID){
console.log("wrong person");
return;}
console.log("we're receiving a summary!");
console.log(data.message.length);

eye2 = 0;
text = data.message;

// delete placeholder text
document.getElementById("content").innerHTML = "";
// document.getElementById("content").scrollTop = scrollHeight;
typeText2();
// </br>
});

function displayQuestions(data) {

console.log("data to display: " + data)
let incomingSting = data
quesionArray = incomingSting.split('|')

console.log(quesionArray)

x = document.getElementsByClassName("tab");

x[questionNumber].innerHTML = quesionArray[0]

for (let i = 0; i < 4; i++) {
let answers = document.createElement("div");

answers.setAttribute("class", "answers");
x[questionNumber].appendChild(answers);
answersDisplay = document.getElementsByClassName("answers")
answersDisplay[i + questionNumber * 4].innerHTML = quesionArray[i + 1]

console.log(answers)
}
collectResponses()

responded = false
}

// worst possible implementation of this hhHAHAAH
function typeText2(){
if (eye2 < text.length) {
let newText = document.getElementById("content");
let i = text.charAt(eye2);
if (i == '\n'){
newText.innerHTML += '<br>'
newText.scrollTop = newText.scrollHeight;
} else {
newText.innerHTML += i;
}
eye2++;

setTimeout(typeText2, speed);
//   if (eye == text.length){
}
else {
let textContent = document.getElementById("content").textContent;
const htmlContent = linkify(textContent);
document.getElementById("content") = htmlContent;
}
}

// stolen from stackOverflow:
// https://stackoverflow.com/questions/1500260/detect-urls-in-text-with-javascript
function linkify(text) {
var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(urlRegex, function(url) {
return '<a href="' + url + '">' + url + '</a>';
});
}
```
```.vscode/settings.json

{
"code-runner.executorMap": {
"cpp": "cd \$dir && g++ \$fileName -o \$fileNameWithoutExt -I/usr/local/include -L/usr/local/lib -lglfw -framework OpenGL -lGLEW && \$dir\$fileNameWithoutExt",
},
}
```
```#include <iostream>
using namespace std;

int main() {
int num=3;
if(num== 1){
cout<< "hello world 1"<< endl;
}else if(num==2){
cout<< "hello world 2"<< endl;
}else if(num==3){
cout<< "hello world 3"<< endl;
}
else{
cout<< "hello world"<< endl;
}
return 0;
}```
```// C++ code
#include<iostream>
using namespace std;

int main(){
for(int i=0 ; i<10000 ; i=i +1){

cout<<"hello world"<<endl;

}
return 0;
}```
```#pragma once
#include "Array.h"
#include "Array.cpp"

int main() {
COLOR_GREEN_TEXT
/*******************************************************/
Array<double> a(5);
a.setSize(7, 2);
for (size_t i = 0; i < 7; i++)
{
a.addElement(rand() % 10);
}
a.showArray();
/*******************************************************/
cout << "GetElement = " << a.getAt(5) << endl;
/*******************************************************/
a.setAt(3, 99);
a.showArray();
a.setAt(3, 99);
a.setAt(1, 89);
a.setAt(10, 59);
a.showArray();
/*******************************************************/
a.addElement(rand() % 10);
a.showArray();
a.addElement(rand() % 10);
a.addElement(rand() % 10);
a.showArray();
/*******************************************************/
cout << "a[] = " << a[7] << endl;
/*******************************************************/
cout << *(a.getData() + 1) << endl;
/*******************************************************/
a.insertAt(2, 22);
a.showArray();
/*******************************************************/
a.freeExtra();
a.showArray();
/*******************************************************/
Array<double> b(1);
b.setSize(3, 2);
b.addElement(5);
b.addElement(10);
b.addElement(25);
b.showArray();
/*******************************************************/
a.Append(b);
a.addElement(1256);
a.addElement(854);
cout << endl;
cout << endl;
cout << endl;
a.showArray();
/*******************************************************/
Array<double> c(10);
c.setSize(5, 3);
c = a;
cout << endl;
cout << endl;
cout << endl;
c.showArray();
/*******************************************************/
STOP
return 0;
}
```
```// Array.cpp
#pragma once
#include "Array.h"

template<class T>
Array<T>::Array(int SIZE) // CONSTRUCTOR
{
this->grow = 1;
this->SIZE = SIZE + grow;
this->preSIZE = SIZE;
this->count = 0;
this->arr = new T[this->SIZE]();
}

template<class T>
Array<T>::Array(const Array & other) // CONSTRUCTOR COPY
{
this->SIZE = other.SIZE;
this->arr = new T[this->SIZE];
for (size_t i = 0; i < this->SIZE; i++)
{
this->arr[i] = other.arr[i];
}
}

template<class T>
Array<T>::~Array() // DESTRUCTOR
{
delete[] arr;
arr = NULL;
}

template<class T>
int Array<T>::getSize() // GET SIZE
{
return this->SIZE;
}

template<class T>
void Array<T>::setSize(int SIZE, int grow) //SET SIZE
{
if(grow > 0)
this->grow = grow;
this->SIZE = SIZE + this->grow;

if (this->SIZE > this->preSIZE)
{
T * buf = new T[this->SIZE]();
for (size_t i = 0; i < this->preSIZE; i++)
{
buf[i] = arr[i];
}
delete[] arr;
arr = new T[this->SIZE]();
for (size_t i = 0; i < this->SIZE; i++)
{
arr[i] = buf[i];
}
delete[] buf;
this->preSIZE = this->SIZE;
}
else
{
T * buf = new T[this->SIZE]();
for (size_t i = 0; i < this->SIZE - this->grow; i++)
{
buf[i] = arr[i];
}
delete[] arr;
arr = new T[this->SIZE]();
for (size_t i = 0; i < this->SIZE; i++)
{
arr[i] = buf[i];
}
delete[] buf;
this->preSIZE = this->SIZE;
this->count = this->SIZE - this->grow;
}
}

template<class T>
void Array<T>::addElement(T element) // ADD ELEMENT
{
if (count < this->SIZE)
{
this->arr[count] = element;
count++;
}
else
{
this->SIZE = this->SIZE + this->grow + 1;
T * buf = new T[this->SIZE]();
for (size_t i = 0; i < this->SIZE - this->grow; i++)
{
buf[i] = arr[i];
}
delete[] arr;
arr = new T[this->SIZE]();
for (size_t i = 0; i < this->SIZE; i++)
{
arr[i] = buf[i];
}
delete[] buf;
buf = NULL;
arr[count] = element;
count++;
}
}

template<class T>
int Array<T>::getUpperBound() //GET UPPER BOUND
{
return count - 1;
}

template<class T>
bool Array<T>::isEmpty() // CHECK EMPTY NO YES?
{
if (count == 0)
return false;
else
return count;
}

template<class T>
void Array<T>::freeExtra() // FREE EXTRA
{
T * buf = new T[this->SIZE - this->grow]();
for (size_t i = 0; i < this->SIZE - this->grow; i++)
{
buf[i] = arr[i];
}
delete[] arr;
arr = new T[this->SIZE - this->grow]();
for (size_t i = 0; i < this->SIZE - this->grow; i++)
{
arr[i] = buf[i];
}
this->SIZE = this->SIZE - this->grow;
}

template<class T>
void Array<T>::removeAll() // CLEAR ALL
{
delete[] arr;
arr = NULL;
this->SIZE = 0;
this->preSIZE = 0;
this->grow = 0;
this->count = 0;
}

template<class T>
T Array<T>::getAt(int index) // GET AT
{
if (index <= count)
return arr[index - 1];
else
return false;
}

template<class T>
void Array<T>::setAt(int index, T element) // SET AT
{
if (index <= count)
{
int iteration = 0;
bool flag = true;
T * buf = new T[SIZE + 1]();
for (size_t i = 0; i < SIZE; i++)
{
if (i != index)
{
buf[iteration] = arr[i];
iteration++;
}
if(i == index && flag == true)
{
buf[iteration] = element;
iteration++;
buf[iteration] = arr[i];
iteration++;
flag = false;
}
}
delete[] arr;
arr = new T[SIZE + 1]();
this->SIZE++;
count++;
for (size_t i = 0; i < this->SIZE; i++)
{
arr[i] = buf[i];
}
delete[] buf;
}
}

template<class T>
T & Array<T>::operator[](int index) // OVERLOAD OPERATOR []
{
if (index <= count)
return this->arr[index];
else
return this->arr[count];
}

template<class T>
void Array<T>::Append(Array<T> ob) // APPEND
{
int temp = this->SIZE + ob.getSize();
int iteration = 0;
T * buf = new T[temp]();
for (size_t i = 0; i < this->SIZE; i++)
{
buf[i] = arr[i];
iteration++;
}
for (size_t i = 0; i < ob.SIZE; i++)
{
buf[iteration] = ob.arr[i];
iteration++;
}
delete[] this->arr;
this->arr = new T[temp]();
for (size_t i = 0; i < temp; i++)
{
this->arr[i] = buf[i];
}
this->SIZE = temp;
this->count = (this->SIZE - this->grow);
delete[] buf;
}

template<class T>
T * Array<T>::getData() // GET POINTER ARR
{
return arr;
}

template<class T>
void Array<T>::insertAt(int index, T element) // INSERT AT
{
if (index <= count)
{
arr[index] = element;
}
}

template<class T>
void Array<T>::showArray()
{
for (size_t i = 0; i < this->SIZE; i++)
{
cout << arr[i] << "\t";
}
cout << endl;
}

template<class T>
Array<T> & Array<T>::operator=(const Array & ob1) // OVERLOAD OPERATOR =
{
this->SIZE = ob1.SIZE;
delete[] this->arr;
this->arr = new T[this->SIZE];
for (size_t i = 0; i < this->SIZE; i++)
{
this->arr[i] = ob1.arr[i];
}
return *this;
}
```
```//Array.h
#pragma once
#include "H.h"
template<class T>
class Array
{
public:
Array(int SIZE);
Array(const Array & other);
~Array();
int getSize();
void setSize(int SIZE, int grow = 1);
void addElement(T element);
int getUpperBound();
bool isEmpty();
void freeExtra();
void removeAll();
T getAt(int index);
void setAt(int index, T element);
T & operator[](int index);
void Append(Array ob);
T * getData();
void insertAt(int index, T element);
void showArray();
Array & operator=(const Array & ob1);
private:
T * arr;
int SIZE;
int preSIZE;
int count;
int grow;
};
```
```class Solution {
public:
int mxlcs(string &t1, string &t2, int i, int j,  vector<vector<int>> & dp)
{
if(i==t1.size()||j==t2.size()) return 0;
if(dp[i][j]!=-1) return dp[i][j];
int p=0;
if(t1[i]==t2[j])
{
p = 1+mxlcs(t1, t2, i+1, j+1, dp);
}
else p = max(mxlcs(t1, t2, i+1, j, dp), mxlcs(t1, t2, i, j+1, dp));
return dp[i][j]=p;
}

int longestCommonSubsequence(string text1, string text2) {
vector<vector<int>> dp(text1.size(), vector<int>(text2.size(), -1));
int ans=mxlcs(text1, text2, 0, 0, dp);
return ans;
}
};```
```class Solution {
public:
int rob(vector<int>& nums) {
int n=nums.size();
vector<int> dp(n,-1);
if(n<1) return 0;
if(n==1) return nums[0];
dp[0]=nums[0];
dp[1]=max(nums[0], nums[1]);
for(int i=2;i<n;i++)
{
dp[i]=max(dp[i-2]+nums[i], dp[i-1]);
}
return dp[n-1];
}
};```
```std::vector<float> distortion_vec = calib_handler_.getCameraDistortion(calib_handler_.getStereoLeftCameraId());

Eigen::Map<Eigen::VectorXf, Eigen::Unaligned> distortion(distortion_vec.data(), distortion_vec.size() - 2);
```
```class Solution {
public:
int tribonacci(int n) {
int dp[n+4];
for(int i=0;i<n+1;i++)
{
dp[i]=-1;
}
dp[0]=0;
dp[1]=1;
dp[2]=1;
for(int i=3;i<n+1;i++)
{
dp[i]=dp[i-1]+dp[i-2]+dp[i-3];
}
return dp[n];
}
};```
```#include <iostream>
using namespace std;

struct element
{
int i;
int j;
int x;
};

struct sparse
{
int m;
int n;
int num;
struct element *ele;
};

void create(sparse *s)
{
cout << "Enter dimensions : ";
cin >> s->m >> s->n;
cout << "Enter number of non zero elements : \n";
cin >> s->num;

s->ele = new element[s->num];

cout << "Enter all non zero elements : ";
for(int i=0; i<s->num; i++)
{
cout << "Enter row no: ";
cin >> s->ele[i].i;
cout << "Enter column no: ";
cin >> s->ele[i].j;
cout << "Enter element: ";
cin >> s->ele[i].x;
}
}

void display(struct sparse s)
{
int k;
for (int i=0; i< s.m; i++)
{
for(int j=0; j< s.n; j++)
{
if(i==s.ele[k].i && j==s.ele[k].j)
cout << s.ele[k++].x << " ";
else
cout << " ";
}
cout << endl;
}
}

int main() {

struct sparse s;
create(&s);
display(s);

return 0;
}```
```#include <iostream>
using namespace std;

int main()
{
int *A,n,x, ch;
int i,j;

cout << "Enter dimension : " ;
cin >> n;

A = new int[n];

do
{
cout << "\n\n---Diagonal matrix---" << endl;
cout << "1. Create " << endl;
cout << "2. Get " << endl;
cout << "3. Set " << endl;
cout << "4. Display " << endl;
cout << "5. Exit " << endl;
cout << "Enter your choice : ";
cin >> ch;

switch(ch)
{
case 1 :
cout << "Enter the diagonal elements : \n";
for (int i=1; i<=n; i++)
cin >> A[i-1];
break;

case 2 :
cout << "Enter indices : ";
cin >> i >> j;
if (i==j)
cout << "Element is : " << A[i-1] << endl;
else
cout << "Element is : 0 " << endl;
break;

case 3 :
cout << "Enter the element : ";
cin >> x;
cout << "Enter the indices : ";
cin >> i >> j;
if (i==j)
{
A[i-1] = x;
cout << "Element is inserted "<< endl;
}
else
cout << "Element cannot be inserted at those indices!" << endl;
break;

case 4 :
for (int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
if (i==j)
cout << A[i-1] << " ";
else
cout << "0 ";
}
cout << endl;
}
break;

}

}
while(ch != 5);

return 0;
}```
```#include <iostream>
using namespace std;

class LowerTri
{
private :
int n;
int *A;

public :

LowerTri(int n)
{
this->n = n;
A = new int[(n*(n+1))/2];
}

void set (int i, int j , int x);
int get (int i, int j);
void display();
LowerTri()
{
delete []A;
}
};

void LowerTri :: set(int i, int j, int x)
{
if(i>=j)
A[(i*(i-1)/2) + (j-1)] = x;
}

int LowerTri :: get(int i ,int j)
{
if(i>=j)
return A[(i*(i-1)/2) + (j-1)];
else
return 0;
}

void LowerTri :: display()
{
//    cout << "\n\n";
for (int i=1; i<=n; i++)
{
for (int j=1; j<=n; j++)
{
if (i>=j)
cout << A[(i*(i-1)/2) + (j-1)] << " ";
else
cout << "0 ";
}
cout << endl;
}
}

int main() {

int d ;
cout << "Enter dimensions : " ;
cin >> d;

LowerTri lm(d);

int x;
cout << "Enter all elements : " << endl;
for(int i=1 ; i<=d; i++)
{
for (int j=1; j<=d; j++)
{
cin >> x;
lm.set(i,j,x);
}
}

cout << "\n\n";
lm.display();
return 0;
}```
```class Solution {
public:
int maximumProduct(vector<int>& nums) {
int n=nums.size();
sort(nums.begin(), nums.end());
return max(nums[0]*nums[1]*nums[n-1], nums[n-1]*nums[n-2]*nums[n-3]);
}
};```
```#include <iostream>
using namespace std;

class Diagonal
{
private :
int n;
int *A;

public :

Diagonal(int n)
{
this->n = n;
A = new int[n];
}

void set (int i, int j , int x);
int get (int i, int j);
void display();
~Diagonal()
{
delete []A;
}
};

void Diagonal :: set(int i, int j, int x)
{
if(i==j)
A[i-1] = x;
}

int Diagonal :: get(int i ,int j)
{
if (i==j)
return A[i-1];
else
return 0;
}

void Diagonal :: display()
{
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
{
if (i==j)
cout << A[i] << " ";
else
cout << "0 ";
}
cout << endl;
}
}

int main() {

Diagonal m(4) ;

m.set(1,1,1);
m.set(2,2,2);
m.set(3,3,3);
m.set(4,4,4);

m.display();

return 0;
}```
```#include <iostream>
using namespace std;

class MergeSort {
private:
int* arr; // pointer to dynamic array
int size;

public:
MergeSort(int size) { // constructor to initialize private array and size
this->size = size;
arr = new int[size];
}

void merge(int* arr, int l, int m, int r) {
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

int L[n1], R[n2];

for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];

i = 0;
j = 0;
k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}

while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

void mergeSort(int* arr, int l, int r) {
if (l < r) {
int m = l + (r - l) / 2;

mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);

merge(arr, l, m, r);
}
}

void sort() { // public function to sort the private array
mergeSort(arr, 0, size - 1);
}

void display() { // public function to display the sorted array
cout << "Sorted array: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}

~MergeSort() { // destructor to deallocate dynamic array memory
delete[] arr;
}
};

int main() {
int size;
cout << "Enter the size of the array: ";
cin >> size;

int* arr = new int[size];
cout << "Enter the elements of the array: ";
for (int i = 0; i < size; i++) {
cin >> arr[i];
}

MergeSort obj(size);
for (int i = 0; i < size; i++) {
obj.arr[i] = arr[i]; // copy the array to the private array in the class
}

obj.sort(); // sort the private array
obj.display(); // display the sorted array

delete[] arr; // deallocate dynamic array memory
return 0;
}
```
`I am currently working on a project from Willings Corp. , a renowed company in Japan, So I am currently developing an app for the organization in a team, so I have a good knowledge how things works in a real projects. And I have also maintained a good CGPA (8.23/10) in an institute of national importance. So I can assure you that I will give my best to do the required work for this role.`
```#include <iostream>
#include <vector>
using namespace std;

class insertionsort{
private:
int a[100];
int n;

public:

insertionsort(int arr[], int size){
n = size;
int j, key;
for (int i=0; i < n; i++) {
a[i] = arr[i];
}
for(int i = 1; i<size; i++) {
key = a[i];
j = i;
while( j > 0 && a[j-1]>key) {
a[j] = a[j-1];
j--;
}
a[j] = key;
}
}

void display() {
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
}
};

int main() {
int size;

cout << "Enter the size of the 1-d array: ";
cin >> size;

int arr[size];

cout << "Enter all the elemets of the array with spaces:\n";
for(int i=0; i<size; i++){
cin>>arr[i];
}

insertionsort is(arr, size);
is.display();

return 0;
}
```
```#include <iostream>
#include <vector>
using namespace std;

class selectionsort{
private:
int a[100];
int n;

public:

selectionsort(int arr[], int size){
n = size;
int imin, temp;

for (int i=0; i < n; i++) {
a[i] = arr[i];
}
for(int i = 0; i<n-1; i++) {
imin = i;
for(int j = i+1; j<n; j++)
if(a[j] < a[imin])
imin = j;
temp = a[i];
a[i] = a[imin];
a[imin] = temp;
}
}

void display() {
cout << "Sorted Array: ";
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
}
};

int main() {
int size;

cout << "Enter the size of the 1-d array: ";
cin >> size;

int arr[size];

cout << "Enter all the elements separated with spaces\n";
for(int i=0; i<size; i++){
cin>>arr[i];
}

selectionsort ss(arr, size);
ss.display();

return 0;
}
```
```#include <iostream>
using namespace std;

class binarysearch {
private:
int n;
public:

void bubblesort(int arr[], int size){
n = size;
for (int i=0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}

}

int search(int arr[], int x, int low, int high) {

if (high >= low) {
int mid = low + (high - low) / 2;

// If found at mid, then return it
if (arr[mid] == x)
return mid;

// Search the left half
if (arr[mid] > x)
return search(arr, x, low, mid - 1);

// Search the right half
return search(arr, x, mid + 1, high);
}

return -1;
}
};

int main() {
int size, x;

cout << "Enter the size of the 1-d array: ";
cin >> size;
int arr[size];

cout << "Enter all the elements separated with spaces\n";
for(int i=0; i<size; i++){
cin>>arr[i];
}

cout <<"Enter the element to do binary search: ";
cin >>x;

binarysearch bs;
bs.bubblesort(arr, size);

cout<<"To do binary search, the array should be sorted\nThe sorted array is:\n";
for(int i=0; i<size; i++){
cout<<arr[i]<<" ";
}
cout<<endl;

int index = bs.search(arr, x, 0, size - 1);

if (index == -1) {
cout << "Element not found" << endl;
} else {
cout << "Element "<<x<<" found at index " << index << endl;
}

return 0;
}
```
```// for LEDS

#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h> // Required for 16 MHz Adafruit Trinket
#endif

#include <Keypad.h>

//
int old_color_piano;
int old_color_guitar;

// for row/col scan
bool initialized = false;
const byte ROWS = 3;
const byte COLS = 8;
char fastPressed;
int lastPressed;
char hexaKeys[ROWS][COLS] = {
{'0','1','2','3','4','5','6','7'},
{'8','9','A','B','C','D','E','F'},
{'G','H','I','J','K','L','M','N'}
};
byte colPins[COLS] = {37,41,43,45,47,49,51,53};
byte rowPins[ROWS] = {31,33,35};

// this one im adding
int current_button;

Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

// for the debouncer
unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
unsigned long debounceDelay = 50;
int lastButtonState = LOW;

//#define LED_PIN   8
//#define LED_COUNT 60
int LED_PIN_piano = 13;
int LED_PIN_guitar = 29;
int LED_COUNT = 60;

Adafruit_NeoPixel piano_strip(LED_COUNT, LED_PIN_piano, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel guitar_strip(LED_COUNT, LED_PIN_guitar, NEO_GRB + NEO_KHZ800);

int current_step = 0;
int old_color;

// end LEDS

// NEW AS OF 12/10
// C = 2,5 B = 6,3 A = 7,4
int g1[] = {0,0,0};
int g2[] = {0,0,0};
//int g2Pins[] = {5,6,7};
//int g1Pins[] = {2,3,4};

int g1Pins[] = {7,6,5};
int g2Pins[] = {4,3,2};

//int g1Pins[] = {5,6,7};
//int g2Pins[] = {2,3,4};

// C = 16,19 B = 15,18 A = 14,17
int p1[] = {0,0,0};
int p2[] = {0,0,0};
int p1Pins[] = {16,15,14};
int p2Pins[] = {19,18,17};

int potVal;
int potVal_speed;
int potPin_piano = A0;
int potPin_guitar = A1;
int potPin_speed = A2;

int buttonPins[] = {41,43,45,47,49,51,53,52};
int buttonCounts[] = {0,0,0,0,0,0,0,0};

//int piano_steps[] = {1,8,11,0,20,0,23,17};
int piano_steps[] = {1,0,3,0,5,0,0,7};

//int guitar_steps[] = {0,1,2,3,4,5,6};
int guitar_steps[] = {17,17,17,17,17,17,17,0};

int modeButton = 10;
// END NEW

/// FROM 12_9_PUTTINGTOGETHER
int prevStateMode = 0;
int lastDebounceTimeMode = 0;
int buttonStateMode = 0;
int lastButtonStateMode = 0;
// mode_bool must be false on init
// false -> write mode, true -> play mode
int mode_bool = true;

int just_pressed[] = {false,false,false,false,false,false,false,false};
int still_pressed[] = {false,false,false,false,false,false,false,false};
int debounced_times[] = {0,0,0,0,0,0,0,0};

int just_pressed_mode = false;
int still_pressed_mode = false;
int debounced_times_mode = 0;
int wait_time = 1000;
//

// for piano
int myArray[40][6]{
{0,0,0,0,0,0},
{0,0,0,0,0,1},
{0,0,0,0,1,0},
{0,0,0,0,1,1},
{0,0,0,1,0,0},
{0,0,0,1,0,1},
{0,0,0,1,1,0},
{0,0,0,1,1,1},
{0,0,1,0,0,0},
{0,0,1,0,0,1},
{0,0,1,0,1,0},
{0,0,1,0,1,1},
{0,0,1,1,0,0},
{0,0,1,1,0,1},
{0,0,1,1,1,1},
{0,1,0,0,0,0},
{0,1,0,0,0,1},
{0,1,0,0,1,0},
{0,1,0,0,1,1},
{0,1,0,1,0,0},
{0,1,0,1,0,1},
{0,1,0,1,1,1},
{0,1,1,0,0,0},
{0,1,1,0,0,1},
{0,1,1,0,1,0},
{0,1,1,0,1,1},
{0,1,1,1,0,0},
{0,1,1,1,0,1},
{0,1,1,1,1,0},
{0,1,1,1,1,1},
{1,0,0,0,0,0},
{1,0,0,0,0,1},
{1,0,0,0,1,0},
{1,0,0,0,1,1},
{1,0,0,1,0,0},
{1,0,0,1,0,1},
{1,0,0,1,1,0},
{1,0,0,1,1,1},
{1,0,1,0,0,0},
{1,0,1,0,0,1},
// {1,0,1,0,1,0},
//{1,0,1,0,1,1}
};

// for guitar
int myArray_guitar[8][6]{
{0,0,0,0,0,0},
{0,0,0,0,0,1},
{0,0,0,0,1,0},
{0,0,0,0,1,1},
{0,0,1,0,0,0},
{0,0,1,0,0,1},
{0,0,1,0,1,0},
{0,0,1,0,1,1}
};

void setup() {
// for leds
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
clock_prescale_set(clock_div_1);
#endif
// END of Trinket-specific code.

piano_strip.begin();           // INITIALIZE NeoPixel strip object (REQUIRED)
piano_strip.show();            // Turn OFF all pixels ASAP
piano_strip.setBrightness(50); // Set BRIGHTNESS to about 1/5 (max = 255)

guitar_strip.begin();           // INITIALIZE NeoPixel strip object (REQUIRED)
guitar_strip.show();            // Turn OFF all pixels ASAP
guitar_strip.setBrightness(50); // Set BRIGHTNESS to about 1/5 (max = 255)
// end LEDS

Serial.begin(9600);
pinMode(potPin_piano, INPUT);
pinMode(potPin_guitar, INPUT);
pinMode(potPin_speed, INPUT);

// init mx/dmx
for (int i = 0; i < 3; i++){
pinMode(g1Pins[i],OUTPUT);
pinMode(g2Pins[i],OUTPUT);
pinMode(p1Pins[i],OUTPUT);
pinMode(p2Pins[i],OUTPUT);
}

// init buttons
for (int i = 0; i < 8; i++){
pinMode(buttonPins[i], INPUT);
}

for(int i=0; i<8; i++) {
piano_strip.setPixelColor(i+3,255,0,0);
guitar_strip.setPixelColor(i+3,255,0,0);
}
piano_strip.show();
guitar_strip.show();
}

void loop() {

Serial.print(digitalRead(12));
//Serial.print(analogRead(A0));
//Serial.print(analogRead(A1));
//Serial.println(analogRead(A2));

// put your main code here, to run repeatedly:
//Serial.println(digitalRead(modeButton));
if (!mode_bool) {
new_write_mode();
}
//     Serial.print("piano ");
//     Serial.print(piano_steps[0]);
//     Serial.print(piano_steps[1]);
//     Serial.print(piano_steps[2]);
//     Serial.print(piano_steps[3]);
//     Serial.print(piano_steps[4]);
//     Serial.print(piano_steps[5]);
//     Serial.print(piano_steps[6]);
//     Serial.println(piano_steps[7]);

//Serial.print("guitar ");
//     Serial.print(guitar_steps[0]);
//     Serial.print(guitar_steps[1]);
//     Serial.print(guitar_steps[2]);
//     Serial.print(guitar_steps[3]);
//     Serial.print(guitar_steps[4]);
//     Serial.print(guitar_steps[5]);
//     Serial.print(guitar_steps[6]);
//     Serial.println(guitar_steps[7]);
//   }

if (mode_bool) {
play_mode();
}

checkModeButton();

}

void checkButtons(){
Serial.println("write mode");
// iterate thru buttons
for (int i = 0; i < 8; i++){

// for LEDS
//if (steps[i] == 0) {
//strip.setPixelColor(i,255,0,0);
//  }

//else if (steps[i] != 0) {
//strip.setPixelColor(i,0,0,255);
//  }

// end LEDS

// read button pin
int buttonState = digitalRead(buttonPins[i]);

if (buttonState == 1 && just_pressed[i] == false){
buttonCounts[i]++;

// NEW
if (buttonCounts[i] % 2 != 0){
debounced_times[i] = millis();
potVal = map(analogRead(potPin_piano), 0,920,0,35);
//steps[i] = potVal;
//Serial.println(steps[i]);

if (millis() - debounced_times[i] > wait_time) {
if (digitalRead(buttonPins[i] == 1)) {
buttonCounts[i]++;
}
}

if (buttonCounts[i] % 2 != 0) {
// is this the right place to show lights?
//strip.show();
break;
}
}
}
}
}

void play_mode() {
Serial.println("read mode");
//for play mode test 12/11 3pm

//int piano_steps[] = {10,11,12,0,13,14,0,25};
//int guitar_steps[] = {0,1,2,3,4,5,6,7};

//int piano_steps[] = {0,1,2,3,4,5,6,7};

for (int i = 0; i < 8; i++){
// iterate thru all 8 steps
//Serial.println("read mode");
int t_piano = piano_steps[i];
int t_guitar = guitar_steps[i];

checkModeButton();

// TODO IMPLEMENT FOR MULTIPLE LED STRIPS
play_mode_leds(i);

for (int j = 0; j < 3; j++){
p1[j] = myArray[t_piano][j+3];
p2[j] = myArray[t_piano][j];

checkModeButton();

g2[j] = myArray[t_guitar][j+3];
g1[j] = myArray[t_guitar][j];
}
//        for (int i = 0; i < 3; i++){
//    Serial.print(g1[i]);
//  }
//   for (int i = 0; i < 2; i++){
//    Serial.print(g2[i]);
//  }
//  Serial.println(g2[2]);

//atoi()
//    Serial.print(p1[0]);
//    Serial.print(p1[1]);
//    Serial.print(p1[2]);
//    Serial.print(p2[0]);
//    Serial.print(p2[1]);
//    Serial.println(p2[2]);

checkModeButton();

for (int j = 0; j < 3; j++){
digitalWrite(p1Pins[j],p1[j]);
digitalWrite(p2Pins[j],p2[j]);

digitalWrite(g1Pins[j],g1[j]);
digitalWrite(g2Pins[j],g2[j]);
}

wait_time = map(analogRead(potPin_speed),0,1000,100,800);
checkModeButton();
delay(wait_time);
}
}

void checkModeButton(){
//Serial.println("fug");
int reading = digitalRead(modeButton);

// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited long enough
// since the last press to ignore any noise:

// If the switch changed, due to noise or pressing:
if (reading != prevStateMode) {

// reset the debouncing timer
lastDebounceTimeMode = millis();
}

if ((millis() - lastDebounceTimeMode) > 50) {
// whatever the reading is at, it's been there for longer than the debounce
// delay, so take it as the actual current state:
//Serial.println("I am capable of extreme violence");

// if the button state has changed:
if (reading != buttonStateMode) {
buttonStateMode = reading;

// only toggle the LED if the new button state is HIGH
if (buttonStateMode == HIGH) {
mode_bool = !mode_bool;
}
}
}
// save the reading. Next time through the loop, it'll be the lastButtonState:
lastButtonState = reading;
}

void play_mode_leds(int current_step) {
current_step = current_step+3;
if (current_step > 0) {
//old_color = strip.getPixelColor(current_step-1);
piano_strip.setPixelColor(current_step-1,old_color_piano);
guitar_strip.setPixelColor(current_step-1,old_color_guitar);

if (piano_steps[current_step-1] == 0) {
piano_strip.setPixelColor(current_step-1,255,0,0);
}

else if (piano_steps[current_step-1] != 0) {
piano_strip.setPixelColor(current_step-1,0,0,255);
}

if (guitar_steps[current_step-1] == 0) {
guitar_strip.setPixelColor(current_step-1,255,0,0);
}

else if (guitar_steps[current_step-1] != 0) {
guitar_strip.setPixelColor(current_step-1,0,0,255);
}

}

else if (current_step == 0) {
//old_color = strip.getPixelColor(7);
//strip.setPixelColor(7,old_color);

if (piano_steps[7] == 0) {
piano_strip.setPixelColor(7+3,255,0,0);
}
//    else if (piano_steps[7] != 0) {
else{
piano_strip.setPixelColor(7+3,0,0,255);
}

if (guitar_steps[7] == 0) {
guitar_strip.setPixelColor(7+3,255,0,0);
}
else if (guitar_steps[7] != 0) {
guitar_strip.setPixelColor(7+3,0,0,255);
}

}

old_color_piano = piano_strip.getPixelColor(current_step);
old_color_guitar = guitar_strip.getPixelColor(current_step);
piano_strip.setPixelColor(current_step,0,255,0);
guitar_strip.setPixelColor(current_step,0,255,0);
//old_color = strip.getPixelColor(current_step-1)
//strip.setPixelColor(current_step-1,old_color);
piano_strip.show();
guitar_strip.show();
}

void new_write_mode() {
Serial.println("write mode");
//Serial.print("potVAL_no press ");
//Serial.println(potVal);
checkModeButton();
char customKey = customKeypad.getKey();
Serial.println(lastPressed);

if (customKey != NO_KEY){
initialized = true;
decoder(customKey);
}

if (lastPressed < 8 && initialized == true) {
potVal = map(analogRead(potPin_piano),20,1000,0,35);
Serial.print("potVAL ");
Serial.println(potVal);
piano_steps[lastPressed] = potVal;
}

else if (lastPressed > 7 && lastPressed < 16) {
potVal = map(analogRead(potPin_guitar),0,1013,0,8);
Serial.print("potVAL ");
Serial.println(potVal);
guitar_steps[lastPressed-8] = potVal;
Serial.println(lastPressed);
}

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

if (piano_steps[i] == 0) {
piano_strip.setPixelColor(i+3,255,0,0);
}

else if (piano_steps[i] != 0) {
piano_strip.setPixelColor(i+3,0,0,255);
}

if (guitar_steps[i] == 0) {
guitar_strip.setPixelColor(i+3,255,0,0);
}

else if (guitar_steps[i] != 0) {
guitar_strip.setPixelColor(i+3,0,0,255);
}

}

piano_strip.show();
guitar_strip.show();

}

void decoder(char myKey){
if (myKey == '0'){lastPressed = 7;}
if (myKey == '1'){lastPressed = 6;}
if (myKey == '2'){lastPressed = 5;}
if (myKey == '3'){lastPressed = 4;}
if (myKey == '4'){lastPressed = 3;}
if (myKey == '5'){lastPressed = 2;}
if (myKey == '6'){lastPressed = 1;}
if (myKey == '7'){lastPressed = 0;}

if (myKey == 'G'){lastPressed = 15;}
if (myKey == 'H'){lastPressed = 14;}
if (myKey == 'I'){lastPressed = 13;}
if (myKey == 'J'){lastPressed = 12;}
if (myKey == 'K'){lastPressed = 11;}
if (myKey == 'L'){lastPressed = 10;}
if (myKey == 'M'){lastPressed = 9;}
if (myKey == 'N'){lastPressed = 8;}

}```
```int LinearSearch(struct arr, int key)
{
int i;
for(i=0; i<arr.length; i++)
{
if (key == arr.A[i])
return i;
}
return -1;
}

int main()
{
struct Array arr={{2,3,4,5,6},10,5};

printf("%d\n", LinearSearch(arr,15));
Display(arr);

return 0;
}```
```#include <iostream>
#include <vector>
using namespace std;

class bubblesort{
private:
int a[100];
int n;

public:

bubblesort(int arr[], int size){
n = size;

for (int i=0; i < n; i++) {
a[i] = arr[i];
}
for (int i=0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (a[j] > a[j+1]) {
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}

void display() {
cout << "Sorted Array: ";
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
}
};

int main() {
int size;

cout << "Enter the size of the 1-d array: ";
cin >> size;

int arr[size];

cout << "Enter all the elements separated with spaces\n";
for(int i=0; i<size; i++){
cin>>arr[i];
}

bubblesort bs(arr, size);
bs.display();

return 0;
}
```
```int delete(struct Array *arr, int index)
{
int x=0;
int i;

if (index >= 0 && index < arr->length)
{
x = arr-> A[index];
for(i = index; i<arr->length-1; i++)
arr ->length--;
return x;
}
return 0;
}

int main()
{
struct Array arr= {{2,3,4,5,6},10,5};

printf("%d\n", Delete(&arr,4));

return 0;
}```
```// Emilio Ordoñez

# include <iostream>
using namespace std;

//Valores
float DiasLaborados = 30;
float UMA = 123.22;
float Factor1 = .25;
float Factor2 = .3750;
float Factor3 = .0110;

float SueldoBruto = 0;
float SalarioDiarioIntegrado = 0;
float CuotaObreroPatronal = 0;
float CuotaPorPrestamo = 0;
float GastosMedicos = 0;
float GastosInvalidez = 0;
float IMSS = 0;

cuotaIMSS(){

//Operaciones
SalarioDiarioIntegrado = SueldoBruto / DiasLaborados;
CuotaObreroPatronal = (( SalarioDiarioIntegrado - UMA ) * DiasLaborados ) * Factor3;
CuotaPorPrestamo = (( SueldoBruto * DiasLaborados ) * Factor1 ) / 100;
GastosMedicos =  (( SueldoBruto * DiasLaborados ) * Factor2 ) / 100 ;
GastosInvalidez = SueldoBruto * Factor1;

IMSS = CuotaObreroPatronal + CuotaPorPrestamo + GastosMedicos + GastosInvalidez;
//Valores de salida
cout << "Salario diario integrado: " << SalarioDiarioIntegrado << endl;
cout << "Cuota obrero patronal: " << CuotaObreroPatronal << endl;
cout << "Cuota por prestamo: " << CuotaPorPrestamo << endl;
cout << "Gastos medicos: " << GastosMedicos << endl;
cout << "Gastos invalidez: " << GastosInvalidez << endl;
cout << "\nCuota del IMSS : " << IMSS << endl;
}

int main(){

cout << "Calculadora de la nomina\n Banco de Mexico\n";
cout << "\nSueldo bruto: ";
cin >> SueldoBruto;

cout << "Ingrese una opcion: ";
int opcion;

cin >> opcion;

switch(opcion)
{
case 1:
cuotaIMSS();
break;
case 2:
break;
default:;
}

return 0;
}```
```#include <iostream>
using namespace std;

class linearsearch {
private:
int a[100], n, x;

public:
int search(int arr[], int size, int key) {
n = size;
x = key;

for (int i=0; i < n; i++) {
a[i] = arr[i];
}

for (int i = 0; i < size; i++) {
if (arr[i] == key) {
return i;
}
}
return -1;
}
};

int main() {
int size, x;

cout << "Enter the size of the 1-d array: ";
cin >> size;
int arr[size];

cout << "Enter all the elements separated with spaces\n";
for(int i=0; i<size; i++){
cin>>arr[i];
}

cout <<"Enter the element to do linear search: ";
cin >>x;

linearsearch ls;
int index = ls.search(arr, size, x);

if (index == -1) {
cout << x <<" not found" << endl;
} else {
cout << x <<" found at index " << index <<" (starts from 0)." <<endl;
}

return 0;
}```
```class Solution {
public:
char bsf(vector<char> letters, char target)
{
char ans=letters[0];
int n=letters.size();
int l=0,h=n-1;
int mid=l+(h-l)/2;
while(l<=h)
{
if(letters[mid]-'a'>target-'a')
{
ans=letters[mid];
h=mid-1;
}
else l=mid+1;
mid=l+(h-l)/2;
}
return ans;
}

char nextGreatestLetter(vector<char>& letters, char target) {
char result=bsf(letters, target);
return result;
}
};```
```class Solution {
public:
bool isPerfectSquare(int num) {
int l=1;
int h=100000;
long long mid=l+(h-l)/2;
long long sq;
while(l<=h)
{
sq=mid*mid;
if(sq==num) return true;
if(sq<num) l=mid+1;
else h=mid-1;
mid=l+(h-l)/2;
}
return false;
}
};```
```class Solution {
public:
double my_Pow(double x, long n)
{
if(n==0) return 1.0;
if(n==1) return x;
if(n<0) return my_Pow(1/x, -n);
double result=my_Pow(x*x, n/2);
if(n%2==1) result*=x;
return result;
}

double myPow(double x, int n) {
return my_Pow(x, n);
}
};```
```class Solution {
public:
int pivot(vector<int> nums)
{
int n=nums.size();
int s=0, l=n-1;
int mid=s+(l-s)/2;
while(s<=l)
{
if(s==l) return s;
if(nums[mid]>nums[n-1]) s=mid+1;
else l=mid;
mid=s+(l-s)/2;
}
return s;
}

int findMin(vector<int>& nums) {
int ans=nums[pivot(nums)];
return ans;
}
};```
```// The API isBadVersion is defined for you.
// bool isBadVersion(int version);

class Solution {
public:
int firstBadVersion(int n) {
int s=0, e=n-1;
int mid=s+(e-s)/2;
int ans=-1;
while(s<=e)
{
if(isBadVersion(mid))
{
ans=mid;
e=mid-1;
}
else s=mid+1;
mid=s+(e-s)/2;
}
return mid;
}
};```
```class Solution {
public:
int findPeakElement(vector<int>& nums) {
int n=nums.size();
if(n==1) return 0;
if(n==2) return nums[0]>nums[1]?0:1;
int s=1, e=n-2;
int mid=s+(e-s)/2;
while(s<=e)
{
if(nums[mid]>nums[mid-1]&&nums[mid]>nums[mid+1]) return mid;
else if(nums[mid]<nums[mid+1]) s=mid+1;
else if(nums[mid]<=nums[mid-1])e=mid-1;
mid=s+(e-s)/2;
}
if(nums[0]>nums[1]) return 0;
else if(nums[n-1]>nums[n-2]) return n-1;

return -1;
}
};```
```/**
* Forward declaration of guess API.
* @param  num   your guess
* @return 	     -1 if num is higher than the picked number
*			      1 if num is lower than the picked number
*               otherwise return 0
* int guess(int num);
*/

class Solution {
public:
// int guess(int num)
// {
//     if(num>)
// }
int guessNumber(int n) {
int s=1, e=n;
int mid=s+(e-s)/2;

while(s<=e)
{
int num=guess(mid);
if(num==0) return mid;
if(num==-1) e=mid-1;
else s=mid+1;
mid=s+(e-s)/2;
}
return mid;

}
};```
```class Solution {
public:
int bs(int x)
{

int long long n=x/2;
int long long s=0, e=n;
int long long mid=s+(e-s)/2;
int long long ans=0;
while(s<=e)
{
int long long p=mid*mid;
int long long p2=(mid+1)*(mid+1);
if(p<=x&&p2>x) return mid;
if(p<x)
{
ans=
s=mid+1;
}
else e=mid-1;
mid=s+(e-s)/2;
}
return mid;
}

int mySqrt(int x) {
if(x==0) return 0;
if(x==1||x==2||x==3) return 1;
int ans=bs(x);
return ans;
}
};```
```        // tennis rackets
for(int item = 0; item < 2; item++) {
glm::mat4 world_transform_matrix = glm::mat4(1.0f);
// global transforms
world_transform_matrix = glm::translate(world_transform_matrix, starting_locations[item]);
world_transform_matrix = rotate(world_transform_matrix, r[item]);
world_transform_matrix = glm::scale(world_transform_matrix, s[item]);

glm::mat4 arm_transform_matrix = world_transform_matrix;
glm::mat4 racket_transform_matrix = world_transform_matrix;

// -- arm -- // tranforms cube to create arm
// forearm (skin)
arm_transform_matrix =  tennis_rackets[item][0].cubeRotate(arm_transform_matrix, glm::vec3(45.0f, 0.0f, 0.0f));
arm_transform_matrix = tennis_rackets[item][0].cubeScale(arm_transform_matrix, glm::vec3(0.5f, 2.0f, 0.5f));
tennis_rackets[item][0].drawCube(arm_transform_matrix);
arm_transform_matrix = tennis_rackets[item][0].cubeScale(arm_transform_matrix, glm::vec3(1/0.5f, 1/2.0f, 1/0.5f));

// arm (skin)
arm_transform_matrix = tennis_rackets[item][0].cubeTranslate(arm_transform_matrix, glm::vec3(0.0f, 2.0f * 0.1f, 0.0f));
arm_transform_matrix =  tennis_rackets[item][0].cubeRotate(arm_transform_matrix, glm::vec3(-45.0f, 0.0f, 0.0f));
arm_transform_matrix = tennis_rackets[item][0].cubeScale(arm_transform_matrix, glm::vec3(0.5f, 2.0f, 0.5f));
tennis_rackets[item][0].drawCube(arm_transform_matrix);
arm_transform_matrix = tennis_rackets[item][0].cubeScale(arm_transform_matrix, glm::vec3(1/0.5f, 1/2.0f, 1/0.5f));

// -- tennis racket shape -- // transforms cube to create racket
// handle
racket_transform_matrix = tennis_rackets[item][1].cubeTranslate(racket_transform_matrix, glm::vec3(0.0f, 3.0f * 0.1f, -0.15f));
racket_transform_matrix = tennis_rackets[item][1].cubeScale(racket_transform_matrix, glm::vec3(0.25f, 2.5f, 0.25f));
tennis_rackets[item][1].drawCube(racket_transform_matrix);
racket_transform_matrix = tennis_rackets[item][1].cubeScale(racket_transform_matrix, glm::vec3(1/0.25f, 1/2.5f, 1/0.25f));
// racket
// racket angled bottom left
racket_transform_matrix = tennis_rackets[item][1].cubeTranslate(racket_transform_matrix, glm::vec3(0.0f,  2.5f * 0.1f, 0.0f));
racket_transform_matrix =  tennis_rackets[item][1].cubeRotate(racket_transform_matrix, glm::vec3(-70.0f, 0.0f, 0.0f));
racket_transform_matrix = tennis_rackets[item][1].cubeScale(racket_transform_matrix, glm::vec3(0.25f, 1.5f, 0.25f));
tennis_rackets[item][1].drawCube(racket_transform_matrix);
racket_transform_matrix = tennis_rackets[item][1].cubeScale(racket_transform_matrix, glm::vec3(1/0.25f, 1/1.5f, 1/0.25f));
// racket vertical left
racket_transform_matrix = tennis_rackets[item][1].cubeTranslate(racket_transform_matrix, glm::vec3(0.0f,  1.5f * 0.1f, 0.0f));
racket_transform_matrix =  tennis_rackets[item][1].cubeRotate(racket_transform_matrix, glm::vec3(70.0f, 0.0f, 0.0f));
racket_transform_matrix = tennis_rackets[item][1].cubeScale(racket_transform_matrix, glm::vec3(0.25f, 2.0f, 0.25f));
tennis_rackets[item][1].drawCube(racket_transform_matrix);
racket_transform_matrix = tennis_rackets[item][1].cubeScale(racket_transform_matrix, glm::vec3(1/0.25f, 1/2.0f, 1/0.25f));
// racket angled top left
racket_transform_matrix = tennis_rackets[item][1].cubeTranslate(racket_transform_matrix, glm::vec3(0.0f,  2.0f * 0.1f, 0.0f));
racket_transform_matrix =  tennis_rackets[item][1].cubeRotate(racket_transform_matrix, glm::vec3(40.0f, 0.0f, 0.0f));
racket_transform_matrix = tennis_rackets[item][1].cubeScale(racket_transform_matrix, glm::vec3(0.25f, 1.0f, 0.25f));
tennis_rackets[item][1].drawCube(racket_transform_matrix);
racket_transform_matrix = tennis_rackets[item][1].cubeScale(racket_transform_matrix, glm::vec3(1/0.25f, 1/1.0f, 1/0.25f));
// racket horizontal top
racket_transform_matrix = tennis_rackets[item][1].cubeTranslate(racket_transform_matrix, glm::vec3(0.0f,  1.0f * 0.1f, 0.0f));
racket_transform_matrix =  tennis_rackets[item][1].cubeRotate(racket_transform_matrix, glm::vec3(50.0f, 0.0f, 0.0f));
racket_transform_matrix = tennis_rackets[item][1].cubeScale(racket_transform_matrix, glm::vec3(0.25f, 1.5f, 0.25f));
tennis_rackets[item][1].drawCube(racket_transform_matrix);
racket_transform_matrix = tennis_rackets[item][1].cubeScale(racket_transform_matrix, glm::vec3(1/0.25f, 1/1.5f, 1/0.25f));
// racket angled top right
racket_transform_matrix = tennis_rackets[item][1].cubeTranslate(racket_transform_matrix, glm::vec3(0.0f,  1.5f * 0.1f, 0.0f));
racket_transform_matrix =  tennis_rackets[item][1].cubeRotate(racket_transform_matrix, glm::vec3(50.0f, 0.0f, 0.0f));
racket_transform_matrix = tennis_rackets[item][1].cubeScale(racket_transform_matrix, glm::vec3(0.25f, 1.0f, 0.25f));
tennis_rackets[item][1].drawCube(racket_transform_matrix);
racket_transform_matrix = tennis_rackets[item][1].cubeScale(racket_transform_matrix, glm::vec3(1/0.25f, 1/1.0f, 1/0.25f));
// racket vertical right
racket_transform_matrix = tennis_rackets[item][1].cubeTranslate(racket_transform_matrix, glm::vec3(0.0f,  1.0f * 0.1f, 0.0f));
racket_transform_matrix =  tennis_rackets[item][1].cubeRotate(racket_transform_matrix, glm::vec3(40.0f, 0.0f, 0.0f));
racket_transform_matrix = tennis_rackets[item][1].cubeScale(racket_transform_matrix, glm::vec3(0.25f, 2.0f, 0.25f));
tennis_rackets[item][1].drawCube(racket_transform_matrix);
racket_transform_matrix = tennis_rackets[item][1].cubeScale(racket_transform_matrix, glm::vec3(1/0.25f, 1/2.0f, 1/0.25f));
// racket horizontal bottom
racket_transform_matrix = tennis_rackets[item][1].cubeTranslate(racket_transform_matrix, glm::vec3(0.0f,  2.0f * 0.1f, 0.0f));
racket_transform_matrix =  tennis_rackets[item][1].cubeRotate(racket_transform_matrix, glm::vec3(90.0f, 0.0f, 0.0f));
racket_transform_matrix = tennis_rackets[item][1].cubeScale(racket_transform_matrix, glm::vec3(0.25f, 2.75f, 0.25f));
tennis_rackets[item][1].drawCube(racket_transform_matrix);
racket_transform_matrix = tennis_rackets[item][1].cubeScale(racket_transform_matrix, glm::vec3(1/0.25f, 1/2.75f, 1/0.25f));

//net
racket_transform_matrix = tennis_rackets[item][1].cubeTranslate(racket_transform_matrix, glm::vec3(0.0f, 0.0f, -2.25f * 0.1f));
racket_transform_matrix = tennis_rackets[item][1].cubeScale(racket_transform_matrix, glm::vec3(0.1f, 2.5f, 0.1f));
tennis_rackets[item][1].drawCube(racket_transform_matrix);
racket_transform_matrix = tennis_rackets[item][1].cubeScale(racket_transform_matrix, glm::vec3(1/0.1f, 1/2.5f, 1/0.1f));

for (float j = 0; j < 6; j++) { ]
```
```class Solution {
public:
int numRescueBoats(vector<int>& people, int limit) {
sort(people.begin(), people.end());
int n=people.size();
int ptri=0;
int ptrl=n-1;
int boats=0;

for(ptrl=n-1;ptrl>=0&&ptrl>=ptri;ptrl--)
{
if(people[ptrl]+people[ptri]<=limit) ptri++;
boats++;
}
return boats;
}
};```
```class Solution {
public:
int pivotIndex(vector<int>& nums) {
int n=nums.size();
int ap[n], aa[n];
ap[0]=0; aa[n-1]=0;
int sum=nums[0];
for(int i=1;i<n;i++)
{
ap[i]=sum;
sum+=nums[i];
}
int s=nums[n-1];
for(int i=n-2;i>=0;i--)
{
aa[i]=s;
s+=nums[i];
}
int ans=-1;
for(int i=0;i<n;i++)
{
if(ap[i]==aa[i])
{
ans=i;
break;
}
}
return ans;
}
};```
```class Solution {
public:
int peakIndexInMountainArray(vector<int>& arr) {
int st=0, end=arr.size()-1;
int mid=st+(end-st)/2;
while(st<=end)
{
if(arr[mid]>arr[mid-1]&&arr[mid]>arr[mid+1]) return mid;
if(arr[mid]<arr[mid+1]) st=mid+1;
else if(arr[mid]<arr[mid-1]) end=mid;
mid=st+(end-st)/2;
}
return mid;
}
};```
```class Solution {
public:

int loweridx(vector<int> nums ,int target)
{
int st=0, end=nums.size()-1;
int ans=-1;
int mid=st+(end-st)/2;
while(st<=end)
{
if(nums[mid]==target)
{
ans=mid;
end=mid-1;
}
else if(target>nums[mid])
{
st=mid+1;
}
else if(target<nums[mid])
{
end=mid-1;
}
mid=st+(end-st)/2;
}
return ans;
}

int largidx(vector<int> nums ,int target)
{
int st=0, end=nums.size()-1;
int ans=-1;
int mid=st+(end-st)/2;
while(st<=end)
{
if(nums[mid]==target)
{
ans=mid;
st=mid+1;
}
else if(target>nums[mid])
{
st=mid+1;
}
else if(target<nums[mid])
{
end=mid-1;
}
mid=st+(end-st)/2;
}
return ans;
}

vector<int> searchRange(vector<int>& nums, int target) {

vector<int> v;
int lowidx=loweridx(nums, target);
int laridx=largidx(nums, target);
v.push_back(lowidx);
v.push_back(laridx);
return v;
}
};```