filename
stringlengths 7
140
| content
stringlengths 0
76.7M
|
---|---|
code/operating_system/src/memory_management/partitioned_allocation/best_fit.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*/
#include <iostream>
#include <vector>
#include <queue>
#include <unistd.h>
class process {
public:
size_t size;
pid_t id;
};
class memory {
public:
size_t size;
pid_t id;
std::queue<process> allocated_processess;
void push(const process p) {
if(p.size <= size) {
allocated_processess.push(p);
size -= p.size;
}
}
process pop(){
if(!allocated_processess.empty()) {
process process_to_pop = allocated_processess.front();
allocated_processess.pop();
size += process_to_pop.size;
return process_to_pop;
}
}
bool empty() {
return allocated_processess.empty();
}
};
std::vector<memory> best_fit(std::vector<memory>memory_blocks, std::queue<process>unallocated_processess) {
memory nonAllocatedProcessess;
nonAllocatedProcessess.id = -1;
nonAllocatedProcessess.size = 0;
while(!unallocated_processess.empty()) {
int candidate_best_index = 0;
bool is_process_allocated = false;
for(int i = 0; i < memory_blocks.size(); ++i) {
if(memory_blocks.at(i).size == unallocated_processess.front().size) {
candidate_best_index = i;
is_process_allocated = true;
break;
}
if(memory_blocks.at(i).size > unallocated_processess.front().size) {
candidate_best_index = (candidate_best_index == -1)? i :
(memory_blocks.at(i).size < memory_blocks.at(candidate_best_index).size)? i : candidate_best_index;
is_process_allocated = true;
}
}
if(is_process_allocated) {
memory_blocks.at(candidate_best_index).push(unallocated_processess.front());
unallocated_processess.pop();
}
else {
nonAllocatedProcessess.size += unallocated_processess.front().size;
nonAllocatedProcessess.push(unallocated_processess.front());
unallocated_processess.pop();
}
}
if(!nonAllocatedProcessess.empty()) {
memory_blocks.push_back(nonAllocatedProcessess);
}
return memory_blocks;
}
void display(std::vector<memory> memory_blocks)
{
int i = 0, temp = 0;
process p;
std::cout << "+-------------+--------------+--------------+"
<< std::endl;
std::cout << "| Process Id | Process size | Memory block |"
<< std::endl;
std::cout << "+-------------+--------------+--------------+"
<< std::endl;
// Traverse memory blocks size
for (i = 0; i < memory_blocks.size(); i++) {
// While memory block size is not empty
while (!memory_blocks.at(i).empty()) {
p = memory_blocks.at(i).pop();
temp = std::to_string(p.id).length();
std::cout << "|" << std::string(7 - temp / 2 - temp % 2, ' ')
<< p.id << std::string(6 - temp / 2, ' ')
<< "|";
temp = std::to_string(p.size).length();
std::cout << std::string(7 - temp / 2 - temp % 2, ' ')
<< p.size
<< std::string(7 - temp / 2, ' ') << "|";
temp = std::to_string(memory_blocks.at(i).id).length();
std::cout << std::string(7 - temp / 2 - temp % 2, ' ');
// If memory blocks is assigned
if (memory_blocks.at(i).id != -1) {
std::cout << memory_blocks.at(i).id;
}
// Else memory blocks is assigned
else {
std::cout << "N/A";
}
std::cout << std::string(7 - temp / 2, ' ')
<< "|" << std::endl;
}
}
std::cout << "+-------------+--------------+--------------+"
<< std::endl;
}
int main()
{
std::vector<memory> memory_blocks(5);
std::vector<memory> best_fit_blocks;
std::queue<process> processess;
process temp;
memory_blocks[0].id = 1;
memory_blocks[0].size = 400;
memory_blocks[1].id = 2;
memory_blocks[1].size = 500;
memory_blocks[2].id = 3;
memory_blocks[2].size = 300;
memory_blocks[3].id = 4;
memory_blocks[3].size = 200;
memory_blocks[4].id = 5;
memory_blocks[4].size = 100;
temp.id = 1;
temp.size = 88;
processess.push(temp);
temp.id = 2;
temp.size = 192;
processess.push(temp);
temp.id = 3;
temp.size = 277;
processess.push(temp);
temp.id = 4;
temp.size = 365;
processess.push(temp);
temp.id = 5;
temp.size = 489;
processess.push(temp);
best_fit_blocks = best_fit(memory_blocks, processess);
display(best_fit_blocks);
memory_blocks.clear();
memory_blocks.shrink_to_fit();
best_fit_blocks.clear();
best_fit_blocks.shrink_to_fit();
return 0;
}
|
code/operating_system/src/memory_management/partitioned_allocation/first_fit.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*/
#include <iostream>
#include <vector>
#include <queue>
#include <unistd.h>
class process {
public:
size_t size;
pid_t id;
};
class memory {
public:
size_t size;
pid_t id;
std::queue<process> allocated_processess;
void push(const process p) {
if(p.size <= size) {
allocated_processess.push(p);
size -= p.size;
}
}
process pop(){
if(!allocated_processess.empty()) {
process process_to_pop = allocated_processess.front();
allocated_processess.pop();
size += process_to_pop.size;
return process_to_pop;
}
}
bool empty() {
return allocated_processess.empty();
}
};
std::vector<memory> first_fit(std::vector<memory>memory_blocks, std::queue<process>unallocated_processess) {
memory nonAllocatedProcessess;
nonAllocatedProcessess.id = -1;
nonAllocatedProcessess.size = 0;
while(!unallocated_processess.empty()) {
int temp_p_id = unallocated_processess.front().id;
for(int i = 0; i < memory_blocks.size(); ++i) {
if(memory_blocks.at(i).size >= unallocated_processess.front().size) {
memory_blocks.at(i).push(unallocated_processess.front());
unallocated_processess.pop();
break;
}
}
if(temp_p_id == unallocated_processess.front().id) {
nonAllocatedProcessess.size += unallocated_processess.front().size;
nonAllocatedProcessess.push(unallocated_processess.front());
unallocated_processess.pop();
}
}
if(!nonAllocatedProcessess.empty()) {
memory_blocks.push_back(nonAllocatedProcessess);
}
return memory_blocks;
}
void display(std::vector<memory> memory_blocks)
{
int i = 0, temp = 0;
process p;
std::cout << "+-------------+--------------+--------------+"
<< std::endl;
std::cout << "| Process Id | Process size | Memory block |"
<< std::endl;
std::cout << "+-------------+--------------+--------------+"
<< std::endl;
// Traverse memory blocks size
for (i = 0; i < memory_blocks.size(); i++) {
// While memory block size is not empty
while (!memory_blocks.at(i).empty()) {
p = memory_blocks.at(i).pop();
temp = std::to_string(p.id).length();
std::cout << "|" << std::string(7 - temp / 2 - temp % 2, ' ')
<< p.id << std::string(6 - temp / 2, ' ')
<< "|";
temp = std::to_string(p.size).length();
std::cout << std::string(7 - temp / 2 - temp % 2, ' ')
<< p.size
<< std::string(7 - temp / 2, ' ') << "|";
temp = std::to_string(memory_blocks.at(i).id).length();
std::cout << std::string(7 - temp / 2 - temp % 2, ' ');
// If memory blocks is assigned
if (memory_blocks.at(i).id != -1) {
std::cout << memory_blocks.at(i).id;
}
// Else memory blocks is assigned
else {
std::cout << "N/A";
}
std::cout << std::string(7 - temp / 2, ' ')
<< "|" << std::endl;
}
}
std::cout << "+-------------+--------------+--------------+"
<< std::endl;
}
int main()
{
std::vector<memory> memory_blocks(5);
std::vector<memory> first_fit_blocks;
std::queue<process> processess;
process temp;
memory_blocks[0].id = 1;
memory_blocks[0].size = 400;
memory_blocks[1].id = 2;
memory_blocks[1].size = 500;
memory_blocks[2].id = 3;
memory_blocks[2].size = 300;
memory_blocks[3].id = 4;
memory_blocks[3].size = 200;
memory_blocks[4].id = 5;
memory_blocks[4].size = 100;
temp.id = 1;
temp.size = 88;
processess.push(temp);
temp.id = 2;
temp.size = 192;
processess.push(temp);
temp.id = 3;
temp.size = 277;
processess.push(temp);
temp.id = 4;
temp.size = 365;
processess.push(temp);
temp.id = 5;
temp.size = 489;
processess.push(temp);
first_fit_blocks = first_fit(memory_blocks, processess);
display(first_fit_blocks);
memory_blocks.clear();
memory_blocks.shrink_to_fit();
first_fit_blocks.clear();
first_fit_blocks.shrink_to_fit();
return 0;
}
|
code/operating_system/src/memory_management/partitioned_allocation/next_fit.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*/
#include <iostream>
#include <vector>
#include <queue>
#include <unistd.h>
class process {
public:
size_t size;
pid_t id;
};
class memory {
public:
size_t size;
pid_t id;
std::queue<process> allocated_processess;
void push(const process p) {
if(p.size <= size) {
allocated_processess.push(p);
size -= p.size;
}
}
process pop(){
if(!allocated_processess.empty()) {
process process_to_pop = allocated_processess.front();
allocated_processess.pop();
size += process_to_pop.size;
return process_to_pop;
}
}
bool empty() {
return allocated_processess.empty();
}
};
std::vector<memory> next_fit(std::vector<memory>memory_blocks, std::queue<process>unallocated_processess) {
memory nonAllocatedProcessess;
nonAllocatedProcessess.id = -1;
nonAllocatedProcessess.size = 0;
while(!unallocated_processess.empty()) {
int temp_p_id = unallocated_processess.front().id;
for(int i = 0; i < memory_blocks.size(); i = ((i+1)%memory_blocks.size())) { //this modules needed to shift memory blocks to the beggnings after iterating till the its end.
if(memory_blocks.at(i).size >= unallocated_processess.front().size) {
memory_blocks.at(i).push(unallocated_processess.front());
unallocated_processess.pop();
break;
}
}
if(temp_p_id == unallocated_processess.front().id) {
nonAllocatedProcessess.size += unallocated_processess.front().size;
nonAllocatedProcessess.push(unallocated_processess.front());
unallocated_processess.pop();
}
}
if(!nonAllocatedProcessess.empty()) {
memory_blocks.push_back(nonAllocatedProcessess);
}
return memory_blocks;
}
void display(std::vector<memory> memory_blocks)
{
int i = 0, temp = 0;
process p;
std::cout << "+-------------+--------------+--------------+"
<< std::endl;
std::cout << "| Process Id | Process size | Memory block |"
<< std::endl;
std::cout << "+-------------+--------------+--------------+"
<< std::endl;
// Traverse memory blocks size
for (i = 0; i < memory_blocks.size(); i++) {
// While memory block size is not empty
while (!memory_blocks.at(i).empty()) {
p = memory_blocks.at(i).pop();
temp = std::to_string(p.id).length();
std::cout << "|" << std::string(7 - temp / 2 - temp % 2, ' ')
<< p.id << std::string(6 - temp / 2, ' ')
<< "|";
temp = std::to_string(p.size).length();
std::cout << std::string(7 - temp / 2 - temp % 2, ' ')
<< p.size
<< std::string(7 - temp / 2, ' ') << "|";
temp = std::to_string(memory_blocks.at(i).id).length();
std::cout << std::string(7 - temp / 2 - temp % 2, ' ');
// If memory blocks is assigned
if (memory_blocks.at(i).id != -1) {
std::cout << memory_blocks.at(i).id;
}
// Else memory blocks is assigned
else {
std::cout << "N/A";
}
std::cout << std::string(7 - temp / 2, ' ')
<< "|" << std::endl;
}
}
std::cout << "+-------------+--------------+--------------+"
<< std::endl;
}
int main()
{
std::vector<memory> memory_blocks(5);
std::vector<memory> next_fit_blocks;
std::queue<process> processess;
process temp;
memory_blocks[0].id = 1;
memory_blocks[0].size = 400;
memory_blocks[1].id = 2;
memory_blocks[1].size = 500;
memory_blocks[2].id = 3;
memory_blocks[2].size = 300;
memory_blocks[3].id = 4;
memory_blocks[3].size = 200;
memory_blocks[4].id = 5;
memory_blocks[4].size = 100;
temp.id = 1;
temp.size = 88;
processess.push(temp);
temp.id = 2;
temp.size = 192;
processess.push(temp);
temp.id = 3;
temp.size = 277;
processess.push(temp);
temp.id = 4;
temp.size = 365;
processess.push(temp);
temp.id = 5;
temp.size = 489;
processess.push(temp);
next_fit_blocks = next_fit(memory_blocks, processess);
display(next_fit_blocks);
memory_blocks.clear();
memory_blocks.shrink_to_fit();
next_fit_blocks.clear();
next_fit_blocks.shrink_to_fit();
return 0;
}
|
code/operating_system/src/memory_management/partitioned_allocation/worst_fit.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*/
#include <iostream>
#include <vector>
#include <queue>
#include <unistd.h>
class process {
public:
size_t size;
pid_t id;
};
class memory {
public:
size_t size;
pid_t id;
std::queue<process> allocated_processess;
void push(const process p) {
if(p.size <= size) {
allocated_processess.push(p);
size -= p.size;
}
}
process pop(){
if(!allocated_processess.empty()) {
process process_to_pop = allocated_processess.front();
allocated_processess.pop();
size += process_to_pop.size;
return process_to_pop;
}
}
bool empty() {
return allocated_processess.empty();
}
};
std::vector<memory> worst_fit(std::vector<memory>memory_blocks, std::queue<process>unallocated_processess) {
memory nonAllocatedProcessess;
nonAllocatedProcessess.id = -1;
nonAllocatedProcessess.size = 0;
while(!unallocated_processess.empty()) {
int candidate_best_index = 0;
bool is_process_allocated = false;
for(int i = 0; i < memory_blocks.size(); ++i) {
if(memory_blocks.at(i).size > unallocated_processess.front().size) {
candidate_best_index = (candidate_best_index == -1)? i :
(memory_blocks.at(i).size > memory_blocks.at(candidate_best_index).size)? i : candidate_best_index;
is_process_allocated = true;
}
}
if(is_process_allocated) {
memory_blocks.at(candidate_best_index).push(unallocated_processess.front());
unallocated_processess.pop();
}
else {
nonAllocatedProcessess.size += unallocated_processess.front().size;
nonAllocatedProcessess.push(unallocated_processess.front());
unallocated_processess.pop();
}
}
if(!nonAllocatedProcessess.empty()) {
memory_blocks.push_back(nonAllocatedProcessess);
}
return memory_blocks;
}
void display(std::vector<memory> memory_blocks)
{
int i = 0, temp = 0;
process p;
std::cout << "+-------------+--------------+--------------+"
<< std::endl;
std::cout << "| Process Id | Process size | Memory block |"
<< std::endl;
std::cout << "+-------------+--------------+--------------+"
<< std::endl;
// Traverse memory blocks size
for (i = 0; i < memory_blocks.size(); i++) {
// While memory block size is not empty
while (!memory_blocks.at(i).empty()) {
p = memory_blocks.at(i).pop();
temp = std::to_string(p.id).length();
std::cout << "|" << std::string(7 - temp / 2 - temp % 2, ' ')
<< p.id << std::string(6 - temp / 2, ' ')
<< "|";
temp = std::to_string(p.size).length();
std::cout << std::string(7 - temp / 2 - temp % 2, ' ')
<< p.size
<< std::string(7 - temp / 2, ' ') << "|";
temp = std::to_string(memory_blocks.at(i).id).length();
std::cout << std::string(7 - temp / 2 - temp % 2, ' ');
// If memory blocks is assigned
if (memory_blocks.at(i).id != -1) {
std::cout << memory_blocks.at(i).id;
}
// Else memory blocks is assigned
else {
std::cout << "N/A";
}
std::cout << std::string(7 - temp / 2, ' ')
<< "|" << std::endl;
}
}
std::cout << "+-------------+--------------+--------------+"
<< std::endl;
}
int main()
{
std::vector<memory> memory_blocks(5);
std::vector<memory> worst_fit_blocks;
std::queue<process> processess;
process temp;
memory_blocks[0].id = 1;
memory_blocks[0].size = 400;
memory_blocks[1].id = 2;
memory_blocks[1].size = 500;
memory_blocks[2].id = 3;
memory_blocks[2].size = 300;
memory_blocks[3].id = 4;
memory_blocks[3].size = 200;
memory_blocks[4].id = 5;
memory_blocks[4].size = 100;
temp.id = 1;
temp.size = 88;
processess.push(temp);
temp.id = 2;
temp.size = 192;
processess.push(temp);
temp.id = 3;
temp.size = 277;
processess.push(temp);
temp.id = 4;
temp.size = 365;
processess.push(temp);
temp.id = 5;
temp.size = 489;
processess.push(temp);
worst_fit_blocks = worst_fit(memory_blocks, processess);
display(worst_fit_blocks);
memory_blocks.clear();
memory_blocks.shrink_to_fit();
worst_fit_blocks.clear();
worst_fit_blocks.shrink_to_fit();
return 0;
}
|
code/operating_system/src/processCreation/Processes.c | #include<unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdbool.h>
int main(void)
{
pid_t child;
int status;
printf("I am the parent, my PID is %d\n", getpid());
printf("My parent's PID is %d\n", getppid());
printf("I am going to create a new process...\n");
child = fork();
if (child == -1)
{
// fork() returns -1 on failure
printf("fork() failed.");
return (-1);
}
else if (child == 0)
{
// fork() returns 0 to the child process
printf("I am the child, my PID is %d\n", getpid());
printf("My parent's PID is %d\n", getppid());
}
else
{
// fork() returns the PID of the child to the parent
wait(&status); // wait for the child process to finish...
printf("I am the parent, my PID is still %d\n", getpid());
}
return (0);
}
|
code/operating_system/src/processCreation/README.md | # Create and handle Processes in Linux operating system.
## Understanding the fork, sleep, wait, exit, getpid, getppid system calls and ps, kill Linux commands.
fork() command is used to create a new process.
getpid() and getppid() commands are used to display the PID(Process ID) of the child and parent processes.
wait() command is used to control the flow of execution.
### To see what programs are currently being executed on our system.
Use the **ps** command with some additional options that provide detailed information about the processes
running on our system.
-a lists processes of all users on the system
-u gives us details about the processes
-x lists processes that run unobtrusively in the background (these are known as daemons and usually end
with a d, like systemd).
### To narrow down the list of processes.
We can use **pgrep** to lookup the processes that match a specific pattern of text.
For example, pgrep -l chrome will search processes metadata for the pattern ‘chrome’, then
display the PIDs of those processes along with the program’s name.
[Click here for more and detailed information about Processes:](https://medium.com/@eightlimbed/creating-and-killing-processes-in-linux-7d4470f1f7a6)
|
code/operating_system/src/processCreation/vfork.c | /*
description: When a vfork system call is issued, the parent process will be suspended until
the child process has either completed execution or been replaced with a new executable image
via one of the "exec" family of system calls.
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#define print printf
int main(int argc, char const *argv[])
{
printf("In parent process(A) before fork \n");
printf("A : pid %d pgid %d ppid %d\n",getpid(),getpgid(0),getppid());
int x;
int a=5;
int b =10;
print("a is %d\n",a);
print("b is %d\n",b);
if((x=vfork())==0)
{
printf("In child process(B)\n");
printf("B : pid %d pgid %d ppid %d\n",getpid(),getpgid(0),getppid());
a=10;
b=5;
print("a is %d\n",a);
print("b is %d\n",b);
print("exiting child process\n");
exit(0);
}
else
{
wait(NULL);
print("back in parent process\n");
print("a is %d\n",a);//a is updated even in parent by child
print("b is %d\n",b);//b is updated even in parent by child if vfork
}
return 0;
}
|
code/operating_system/src/scheduling/first_come_first_serve/fcfs.cpp | // C++ program for implementation of FCFS
// scheduling
#include <iostream>
using namespace std;
// Function to find the waiting time for all
// processes
void findWaitingTime(int n, int bt[], int wt[])
{
// waiting time for first process is 0
wt[0] = 0;
// calculating waiting time
for (int i = 1; i < n; i++)
wt[i] = bt[i - 1] + wt[i - 1];
}
// Function to calculate turn around time
void findTurnAroundTime(int n, int bt[], int wt[], int tat[])
{
// calculating turnaround time by adding
// bt[i] + wt[i]
for (int i = 0; i < n; i++)
tat[i] = bt[i] + wt[i];
}
//Function to calculate average time
void findavgTime(int n, int bt[])
{
int wt[n], tat[n], total_wt = 0, total_tat = 0;
//Function to find waiting time of all processes
findWaitingTime(n, bt, wt);
//Function to find turn around time for all processes
findTurnAroundTime(n, bt, wt, tat);
//Display processes along with all details
cout << "Processes " << " Burst time "
<< " Waiting time " << " Turn around time\n";
// Calculate total waiting time and total turn
// around time
for (int i = 0; i < n; i++)
{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
cout << " " << i + 1 << "\t\t" << bt[i] << "\t "
<< wt[i] << "\t\t " << tat[i] << endl;
}
cout << "Average waiting time = "
<< (float)total_wt / (float)n;
cout << "\nAverage turn around time = "
<< (float)total_tat / (float)n;
}
// Driver code
int main()
{
//process id's
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];
//Burst time of all processes
int burst_time[] = {10, 5, 8};
findavgTime(n, burst_time);
return 0;
}
|
code/operating_system/src/scheduling/first_come_first_serve/fcfs.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/*
* Part of cosmos from OpenGenus Foundation
* */
namespace fcfs
{
/// <summary>
/// Class FCFS will take two inputs, process
/// </summary>
class FCFS
{
int[] processes; // to store process id
int[] bursts; // to store process
int[] ta; // to store turn arround time
int[] wt; // to store awating time
public FCFS(int[] processes,int[] bursts)
{
this.processes = processes;
this.bursts = bursts;
ta = get_ta();
wt = get_wt();
}
/// <summary>
/// Private method to get an array of turn arround time
/// </summary>
/// <returns></returns>
int[] get_ta()
{
int[] temp = new int[bursts.Length];
temp[0] = bursts[0];
for (int i = 1; i < bursts.Length; i++)
{
temp[i] = temp[i - 1] + bursts[i];
}
return temp;
}
/// <summary>
/// Private Method to get an array of waiting time
/// </summary>
/// <returns></returns>
int[] get_wt()
{
int[] temp = new int[bursts.Length];
temp[0] = 0;
for (int i = 1; i < bursts.Length; i++)
{
temp[i] = temp[i - 1] + bursts[i];
}
return temp;
}
/// <summary>
/// Method returning average waiting time
/// </summary>
/// <returns></returns>
public int get_avg_wt()
{
return Convert.ToInt32(wt.Average());
}
/// <summary>
/// Method returning average turn arround time
/// </summary>
/// <returns></returns>
public int get_avg_ta()
{
return Convert.ToInt32(ta.Average());
}
/// <summary>
/// Method to print all process_id -> burst_time -> waiting_time -> turn_arround
/// </summary>
public void print_process()
{
Console.WriteLine("FORMAT : process_id -> burst_time -> waiting_time -> turn_arround");
for(int i = 0; i < processes.Length; i++)
{
Console.WriteLine("{0} -> {1} -> {2} -> {3}", processes[i], bursts[i], wt[i], ta[i]);
}
}
}
class Program
{
static void Main(string[] args)
{
// int array to store process ids
int[] processes = { 1, 2, 3 };
// int array to store burst times
int[] burts = { 10, 5, 8 };
FCFS fcfs = new FCFS(processes, burts);
fcfs.print_process();
Console.WriteLine("Average Waiting time : {0}",fcfs.get_avg_wt());
Console.WriteLine("Average Turn Arround time : {0}", fcfs.get_avg_ta());
Console.ReadKey();
}
}
}
|
code/operating_system/src/scheduling/first_come_first_serve/fcfs.java | import java.io.*;
class FCFS
{
public static void main(String args[]) throws Exception
{
int n,at[],bt[],wt[],tat[];
float AWT=0;
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println(“Enter no of process”);
n=Integer.parseInt(br.readLine());
wt=new int[n];
tat=new int[n];
bt=new int[n];
at=new int[n];
System.out.println(“Enter Burst time for each process\n”);
for(int i=0;i<n;i++)
{
System.out.println(“Process[“+(i+1)+"]");
bt[i]=Integer.parseInt(br.readLine());
}
System.out.println(“\n\nEnter Around Time”);
for(int i=0;i<n;i++)
{
System.out.println(“Process[”+i+"]");
at[i]=Integer.parseInt(br.readLine());
}
System.out.println(“\n”);
wt[0]=0;
for(int i=1;i<n;i++)
{
wt[i]=wt[i-1]+bt[i-1];
wt[i]=wt[i]-at[i];
}
for(int i=0;i<n;i++)
{
tat[i]=wt[i]+bt[i];
awt=awt+wt[i];
}
System.out.println(” PROCESS\t\tBURST-TIME\tWAITING-TIME\tTURN AROUND-TIME\n“);
for(int i=0;i<n;i++)
{
System.out.println(” “+ i + ”\t\t“+bt[i]+”\t“+wt[i]+”\t“+tat[i]);
}
awt=awt/n;
System.out.println(“\n”);
System.out.println(“Avg waiting time=”+awt+”\n”);
}
}
|
code/operating_system/src/scheduling/first_come_first_serve/fcfs.py | # ------------------
# Part of cosmos from OpenGenus Foundations
# ------------------
import sys
"""
Class FCFS accepts dictionary for __processes
"""
class FCFS:
def __init__(self, processes):
# initializing private method
self.__processes = processes # colling processes
self.__wtList = self.__wtl() # self.__wtl() returns a list of waiting_time
self.__taList = self.__tal() # self.__tal() returns a list of turn_arround_time
pass
# Print() prints details about the processes
def Print(self):
l = 0 # local variable used to print elements in list
print(
"FORMAT : process_name -> arrival_time -> burst_time -> waiting_time -> turn_arround_time\n"
)
for process in self.__processes:
print(
process,
self.__processes[process][0],
self.__processes[process][1],
self.__wtList[l],
self.__taList[l],
sep=" -> ",
)
l += 1 # incrementing the list
pass
pass
# Print_Chat() prints the gantt chart for the FCFS
def Print_Chat(self):
for (
process
) in (
self.__processes
): # creating line | separates the process and = indicates the burst_time
print("=" * self.__processes[process][1], "|", end="", sep="")
pass
print()
temp = 0
# printing the waiting_time
for process in self.__processes:
temp += self.__processes[process][1]
print(" " * self.__processes[process][1], temp, end="", sep="")
pass
print("\n")
pass
# Method that returns the average waiting_time upto 3 decimal places
def get_avg_wt(self):
return round(sum(self.__wtList) / len(self.__wtList), 3)
# Method that returns the average turn_arround_time upto 3 decimal places
def get_avg_ta(self):
return round(sum(self.__taList) / len(self.__taList), 3)
# Private method to build a list of waiting_time
def __wtl(self):
temp = []
for x in self.__processes:
if len(temp) == 0:
temp.append(0)
pass
else:
temp.append(temp[-1] + self.__processes[x][1])
pass
pass
return temp
# Private method to build a list of turn_arround_time
def __tal(self):
temp = []
for x in self.__processes:
if len(temp) == 0:
temp.append(self.__processes[x][1])
pass
else:
temp.append(temp[-1] + self.__processes[x][1])
pass
pass
return temp
pass
# processes with key as process and value as list having 0th index = arrival time and 1st index = burst time
process = {"P01": [0, 4], "P02": [1, 5], "P03": [2, 8], "P04": [3, 3]}
fcfs = FCFS(process)
print("<--=[printing process]=-->")
fcfs.Print()
print("\n<--=[printing gantt chart]=-->")
fcfs.Print_Chat()
print("average waiting time : ", fcfs.get_avg_wt())
print("average turn arround time : ", fcfs.get_avg_ta())
|
code/operating_system/src/scheduling/first_come_first_serve/fcfs.rs | fn find_waiting_time(bt: &[i32]) -> Vec<i32> {
let mut wt = Vec::with_capacity(bt.len());
// Waiting time for first process is 0
wt.push(0);
for i in 1..bt.len() {
let last_wt = wt.last().cloned().unwrap();
wt.push(bt[i - 1] + last_wt);
}
wt
}
fn find_turnaround_time(bt: &[i32], wt: &[i32]) -> Vec<i32> {
let mut tat = Vec::with_capacity(bt.len());
for i in 0..bt.len() {
tat.push(bt[i] + wt[i]);
}
tat
}
fn find_avg_time(processes: &[i32], burst_times: &[i32]) {
if processes.len() != burst_times.len() {
return;
}
let n = processes.len();
let wt = find_waiting_time(burst_times);
let tat = find_turnaround_time(burst_times, &wt);
println!("Processes\tBurst Time\tWaiting Time\t Turn around time");
let total_wt = wt.iter().fold(0, |acc, &t| acc + t);
let total_tat = tat.iter().fold(0, |acc, &t| acc + t);
// Calculate total waiting ntime and total turn around time
for i in 0..n {
println!("{}\t{}\t{}\t{}", i + 1, burst_times[i], wt[i], tat[i]);
}
println!("Average waiting time: {}", total_wt / n as i32);
println!("Average turn around time: {}", total_tat / n as i32);
}
fn main() {
let processes = vec![1, 2, 3];
let burst_time = vec![10, 5, 8];
find_avg_time(&processes, &burst_time);
}
|
code/operating_system/src/scheduling/guaranteed_scheduler/guaranteed_scheduling.c | /*
Guaranteed scheduler is a specialized scheduling algorithm designed to ensure that specific processes receive a guaranteed share of CPU time. This scheduler represents a basic implementation of a Guaranteed Scheduling Scheduler with Priority Levels. It demonstrates a simple but effective approach to priority-based scheduling and provides a clear log for tracking job execution.
Philosophy behind Guaranteed Scheduler: Priority-Based Scheduling, Dynamic Time Quantum, Logging and Transparency, Random Priority Assignment
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX_JOBS 15
#define NUM_PRIORITIES 3 /* Example: 3 priority levels */
#define TIME_QUANTUM_HIGH 10
#define TIME_QUANTUM_MEDIUM 5
#define TIME_QUANTUM_LOW 2
struct Job
{
int id;
int cpu_burst;
int io_burst;
int remaining_cpu_burst;
int priority; /* Priority level */
};
/* Function to log output to console and a file */
void
logToFileAndConsole(const char *message, const char *filename)
{
FILE *file = fopen(filename, "a"); /* Open file in append mode */
if (!file)
{
perror("Error opening file");
exit(EXIT_FAILURE);
}
/* Log to both the console and the file */
printf("%s", message);
fprintf(file, "%s", message);
fclose(file);
}
void
guaranteedScheduling(struct Job *jobRequests, int maxJobs)
{
int currentTime = 0;
int completedJobs = 0;
/* Create an array to hold the jobs in execution order */
struct Job *executionOrder[MAX_JOBS * NUM_PRIORITIES];
int executionIndex = 0;
while (completedJobs < maxJobs)
{
int jobFound = 0; /* Flag to check if a job has been found and executed in this iteration. */
/* Loop through priority levels from highest to lowest */
for (int priority = 0; priority < NUM_PRIORITIES; priority++)
{
/* Loop through all jobs to find the next job with the current priority */
for (int i = 0; i < maxJobs; i++)
{
struct Job *currentJob = &jobRequests[i];
if (currentJob->priority == priority && currentJob->remaining_cpu_burst > 0)
{
int executeTime;
/* Determine time quantum based on priority */
if (priority == 0)
executeTime = (currentJob->remaining_cpu_burst > TIME_QUANTUM_HIGH)
? TIME_QUANTUM_HIGH
: currentJob->remaining_cpu_burst;
else if (priority == 1)
executeTime = (currentJob->remaining_cpu_burst > TIME_QUANTUM_MEDIUM)
? TIME_QUANTUM_MEDIUM
: currentJob->remaining_cpu_burst;
else
executeTime = (currentJob->remaining_cpu_burst > TIME_QUANTUM_LOW)
? TIME_QUANTUM_LOW
: currentJob->remaining_cpu_burst;
char message[256];
sprintf(message, "Executing Job %d for %d seconds at time %d (Priority %d)\n", currentJob->id, executeTime, currentTime, priority);
logToFileAndConsole(message, "log.txt");
currentJob->remaining_cpu_burst -= executeTime;
currentTime += executeTime;
if (currentJob->remaining_cpu_burst == 0)
{
sprintf(message, "Job %d completed at time %d (Priority %d)\n", currentJob->id, currentTime, priority);
logToFileAndConsole(message, "log.txt");
completedJobs++;
}
/* Add the job to the execution order*/
executionOrder[executionIndex++] = currentJob;
jobFound = 1; /* Set the flag to indicate that a job has been found and executed. */
break; /* Break out of the inner loop to recheck priorities. */
}
}
}
if (!jobFound)
{
/* If no job was found to execute in this iteration, increment the time. */
currentTime++;
}
}
}
int
main()
{
struct Job jobRequests[MAX_JOBS];
const char *filename = "job_requests.txt";
/* Read job requests from the file */
FILE *file = fopen(filename, "r");
if (!file)
{
perror("Error opening file");
exit(EXIT_FAILURE);
}
int i = 0;
while (i < MAX_JOBS && fscanf(file, "Job %d: CPU Burst %d seconds, I/O Burst %d seconds\n", &jobRequests[i].id, &jobRequests[i].cpu_burst, &jobRequests[i].io_burst) == 3)
{
jobRequests[i].remaining_cpu_burst = jobRequests[i].cpu_burst;
jobRequests[i].priority = rand() % NUM_PRIORITIES; /* Assign a random priority */
i++;
}
fclose(file);
/* Clear log file at the beginning */
FILE *logFile = fopen("log.txt", "w");
fclose(logFile);
printf("\nGuaranteed Scheduling Scheduler with Priority Levels:\n");
guaranteedScheduling(jobRequests, i); /* Pass the number of jobs read from the file */
return (0);
} |
code/operating_system/src/scheduling/job_sequencing/job_sequencing.cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Job {
char id;
int deadline;
int profit;
};
bool jobComparator(const Job &a, const Job &b) {
return a.profit > b.profit;
}
void jobSequence(vector<Job> &jobs) {
int n = jobs.size();
sort(jobs.begin(), jobs.end(), jobComparator);
int maxDeadline = 0;
for (const Job &job : jobs) {
maxDeadline = max(maxDeadline, job.deadline);
}
vector<bool> slot(maxDeadline, false);
vector<char> sequence;
int totalProfit = 0;
for (const Job &job : jobs) {
for (int i = min(maxDeadline - 1, job.deadline - 1); i >= 0; i--) {
if (!slot[i]) {
slot[i] = true;
sequence.push_back(job.id);
totalProfit += job.profit;
break;
}
}
}
cout << "Job sequence: ";
for (char jobId : sequence) {
cout << jobId << " ";
}
cout << "\nTotal profit: " << totalProfit << endl;
}
int main() {
vector<Job> jobs = {
{'a', 2, 100},
{'b', 1, 19},
{'c', 2, 27},
{'d', 1, 25},
{'e', 3, 15}
};
jobSequence(jobs);
return 0;
}
|
code/operating_system/src/scheduling/multi_level_feedback_queue_scheduling/mlfq.ts | /**
* Schedule for running MLFQ simulations and genarating data
* https://github.com/Spensaur-K/mlfq-viz
*/
/**
* Config to create a job
*/
interface JobConfig {
id: number;
createTime: number;
flags: {}[];
runTime: number;
ioFreq: number;
ioLength: number;
}
/**
* A single job in the simulation
*/
class Job {
// Usage determined fields
flags: {}[];
// Values the job is created with
init: {
// unique job id
id: number;
// Time when job was created
createTime: number;
// Total time job needs to spend on CPU to finish
runTime: number;
// Period of cycles that a job will perform IO
ioFreq: number;
// How long this job performs IO for
ioLength: number;
};
// values collected once turing the jobs lifetime
perf: {
// Time it took from when job was created to be scheduled
responseTime: number;
// total time from when job was created till it finished
turnaroundTime: number;
};
// values that vary as the job runs
running: {
// Which queue job is in
priority: number;
// Time job has spent on the CPU
serviceTime: number;
// Whether the job has finished yet
isFinished: boolean;
// Value that starts = to time quantum and deplets as job is run
// Forces a context switch and resets when it reaches 0
quantumLeft: number;
// Amount of time quantum a job has when it is first assigned a new time quantum
quantumFull: number;
// Total time a job has waited for in queue
totalWaitingTime: number;
// Current time job has waited in queue, resets on cpu
waitingTime: number;
// Amount of ticks left to complete io, 0 if job isn't performing io
ioLeft: number;
// Cycles until job performs IO
ioFreqLeft: number;
// Average priority over job's lifetime
avgPriority: number;
};
/**
* Lowers the job's priority and reset its time quantum
* @param priority to set as
* @param quantum to use
*/
lowerPriority(priority: number, quantum: number) {
this.running.quantumLeft = quantum;
this.running.quantumFull = quantum;
this.running.priority = priority;
}
/**
* Boost the job's priority and reset its time quantum
* @param quantum to use
*/
setQuantum(quantum: number) {
this.running.quantumLeft = quantum;
this.running.quantumFull = quantum;
this.running.priority = 0;
}
/**
* Reset a job's time quantum to full without changing priority
*/
resetTQ() {
this.running.quantumLeft = this.running.quantumFull;
}
/**
* Increment the job's waiting time and recalculate it's average priority
*/
wait() {
const oldSum = this.running.avgPriority * this.running.totalWaitingTime;
this.running.totalWaitingTime++;
this.running.waitingTime++;
this.running.avgPriority = (oldSum + this.running.priority) / this.running.totalWaitingTime;
}
/**
* Simulate this job on the CPU
* May start IO
* @param globalTick number of ticks since the simulation started
*/
doWork(globalTick: number) {
this.running.waitingTime = 0;
if (this.perf.responseTime === -1)
this.perf.responseTime = globalTick - this.init.createTime;
this.running.serviceTime++;
this.running.quantumLeft--;
if (this.running.serviceTime < 0 ||
this.running.quantumLeft < 0 ||
this.running.ioLeft > 0) {
throw new Error("Job was not meant to be run");
}
if (this.running.serviceTime === this.init.runTime) {
this.perf.turnaroundTime = globalTick - this.init.createTime + 1;
} else if (this.running.serviceTime > this.init.runTime) {
throw new Error("job missed finish");
} else if (!this.quantumExpired()) {
this.maybeStartIO();
}
}
/**
* Return whether jobs time quantum has run out
*/
quantumExpired() {
return this.running.quantumLeft === 0;
}
/**
* Check if the job is finished
*/
isFinished(): boolean {
if (this.perf.turnaroundTime !== -1) {
this.running.isFinished = true;
}
return this.running.isFinished;
}
/**
* Simulate this job doing IO
* @throws if job has no IO left
*/
doIO() {
if (!this.doingIO())
throw new Error("job not doing IO");
this.running.ioLeft--;
}
/**
* Checks if job should start now, throws if it missed its start
* @param globalTick number of ticks since the simulation started
*/
shouldStart(globalTick: number): boolean {
if (this.init.createTime === globalTick) {
return true;
}
if (this.init.createTime < globalTick) {
throw new Error("Job missed start");
}
return false;
}
/**
* Sometimes starts performing IO (uses IO freq)
*/
private maybeStartIO() {
this.running.ioFreqLeft--;
if (this.running.ioFreqLeft <= 0) {
this.running.ioLeft = this.init.ioLength;
this.running.ioFreqLeft = this.init.ioFreq;
}
}
/**
* Returns whether job is performing IO
*/
doingIO(): boolean {
return this.running.ioLeft > 0;
}
constructor({ createTime, runTime, ioFreq, ioLength, id, flags }: JobConfig) {
this.flags = flags;
this.init = {
id,
createTime,
runTime,
ioFreq,
ioLength
};
this.perf = {
responseTime: -1,
turnaroundTime: -1
};
this.running = {
priority: 0,
isFinished: false,
serviceTime: 0,
quantumLeft: 0,
quantumFull: 0,
ioLeft: 0,
ioFreqLeft: ioFreq,
totalWaitingTime: 0,
waitingTime: 0,
avgPriority: 0
};
}
}
/**
* Config for Scheduler
*/
interface Configuration {
timeQuantums: number[];
resetTQsOnIO: boolean;
boostTime: number;
speed: number;
generation: {
ioFrequencyRange: [number, number];
ioLengthRange: [number, number];
jobRuntimeRange: [number, number];
numJobsRange: [number, number];
jobCreateTimeRange: [number, number];
// usage determined flags added to all jobs in generation
flags: {}[] | void;
}[];
}
interface Queue {
timeQuantum: number;
priority: number;
jobs: Job[];
}
/**
* MLFQ Simulator
*/
export default class Scheduler {
// How many priority levels
numQueues: number;
// How often to boost job priorities
boostTime: number;
boostLeft: number;
queues: Queue[];
cpuJob: Job | undefined;
private config: Configuration;
// jobs that have not yet entered a queue
private futureJobs: Job[];
// jobs that have been completed
private finishedJobs: Job[];
// jobs doing io
private ioJobs: Job[];
// How often, in real ms, to tick the scheduler
private speed: number;
public running: boolean;
private tickIntervalId: number;
// How many ticks the scheduler has performed
public globalTick: number;
/**
* Create a scheduler with a queue for each given time quantum
* and a global boost time
*/
constructor(config: Configuration) {
this.finishedJobs = [];
this.futureJobs = [];
this.cpuJob = undefined;
this.ioJobs = [];
this.speed = config.speed;
this.numQueues = config.timeQuantums.length;
this.queues = config.timeQuantums.map((q, i) => ({
timeQuantum: q,
jobs: [],
priority: i
}));
this.configure(config);
this.globalTick = 1;
}
/**
* Reinitialize queues after queue num change
*/
reshapeQueues() {
throw new Error("Not Implemented Yet");
}
/**
* Runs the scheduler
*/
play(update: { (data: Scheduler): void }) {
if (this.running)
throw new Error("Scheduler is already running!");
const tick = () => {
this.tickIntervalId = setTimeout(tick, this.speed);
if (!this.processJobs()) {
clearTimeout(this.tickIntervalId);
this.tickIntervalId = setTimeout(tick, 0);
}
update(this);
};
this.tickIntervalId = setTimeout(tick, 0);
}
/**
* Plays only the next step of simulation
*/
playNext(update: { (data: Scheduler): void }) {
if (this.running)
throw new Error("Scheduler is already running!");
this.processJobs();
update(this);
}
/**
* Returns whether simulation is finished
*/
get simulationFinished(): boolean {
if (this.futureJobs.length || this.ioJobs.length || this.cpuJob)
return false;
for (const queue of this.queues) {
if (queue.jobs.length)
return false;
}
return true;
}
/**
* Boost all jobs
*/
boostJobs() {
this.queues[0].jobs = Array.prototype.concat(
...this.queues.map(q => q.jobs)
);
for (let i = 1; i < this.queues.length; i++) {
this.queues[i].jobs = [];
}
for (const job of this.allJobs) {
if (!job.isFinished()) {
job.setQuantum(this.queues[0].timeQuantum);
}
}
}
/**
* Configure the schedule
*/
configure(config: Configuration) {
const { timeQuantums, boostTime } = config;
this.config = config;
this.boostTime = boostTime;
this.boostLeft = boostTime;
// reset the queues if numbers changed
if (this.numQueues !== config.timeQuantums.length) {
this.boostJobs();
const firstQueue = this.queues[0].jobs;
this.queues = config.timeQuantums.map((q, i) => ({ timeQuantum: q, jobs: [], priority: i }));
this.queues[0].jobs = firstQueue;
}
this.numQueues = timeQuantums.length;
}
/**
* Put jobs that have finished IO back in their queues
* @returns whether any jobs finished IO
*/
finishIO(): boolean {
let didFinish = false;
for (let i = this.ioJobs.length - 1; i >= 0; i--) {
const job = this.ioJobs[i];
if (!job.doingIO()) {
this.ioJobs.splice(i, 1);
this.queues[job.running.priority].jobs.push(job);
didFinish = true;
}
}
return didFinish;
}
/**
* performs IO for all IO jobs
*/
doIO() {
for (const job of this.ioJobs) {
job.doIO();
}
}
/**
* Stop the scheduler
*/
stop() {
this.running = false;
clearTimeout(this.tickIntervalId);
this.tickIntervalId = -1;
}
/**
* Add futureJobs to queue 1
* @param globalTick scheduler tick
*/
startJobs(globalTick: number) {
for (let i = this.futureJobs.length - 1; i >= 0; i--) {
const job = this.futureJobs[i];
if (job.shouldStart(globalTick)) {
this.futureJobs.splice(i, 1);
job.setQuantum(this.queues[0].timeQuantum);
this.queues[0].jobs.push(job);
}
}
}
/**
* Get all the jobs in the scheduler
* @return a new array containing every job
*/
get allJobs(): Job[] {
const sorted = (this.cpuJob ? [this.cpuJob] : ([] as Job[])).concat(
...this.ioJobs,
...this.futureJobs,
...this.finishedJobs,
...this.queues.map(q => q.jobs))
.sort((a, b) => {
return a.init.id > b.init.id ? 1 : -1;
});
return sorted;
}
/**
* Process the jobs in the scheduler
* @returns whether any state changed that should be animated
*/
processJobs(): boolean {
let stateChanged = false;
if (!this.simulationFinished) {
this.boostLeft--;
if (this.boostLeft <= 0) {
this.boostJobs();
this.boostLeft = this.boostTime;
}
this.doIO();
stateChanged = stateChanged || this.finishIO();
this.startJobs(this.globalTick);
stateChanged = stateChanged || this.processCpuJob();
stateChanged = stateChanged || this.initCpuJob();
this.waitJobs();
this.globalTick++;
}
if (this.simulationFinished) {
this.stop();
}
return stateChanged;
}
/**
* Increment the waiting timer of all jobs that are waiting in
* a queue
*/
waitJobs() {
for (const queue of this.queues) {
for (const job of queue.jobs) {
if (job !== this.cpuJob) {
job.wait();
}
}
}
}
/**
* Loads the next job onto the CPU
* unless there's one already there
* @return whether a new job was loaded
*/
initCpuJob(): boolean {
if (!this.cpuJob) {
this.cpuJob = this.popNextJob();
return this.cpuJob != undefined;
}
return false;
}
/**
* Process a single job on the cpu
* @returns whether CPU state changed
*/
processCpuJob(): boolean {
let stateChanged = false;
if (this.cpuJob) {
this.cpuJob.doWork(this.globalTick);
if (this.cpuJob.isFinished()) {
this.finishedJobs.push(this.cpuJob);
this.cpuJob = undefined;
stateChanged = true;
}
else if (this.cpuJob.quantumExpired()) {
const lastQueue = this.numQueues - 1;
const lowerPriority = this.cpuJob.running.priority === (lastQueue) ? lastQueue : this.cpuJob.running.priority + 1;
this.cpuJob.lowerPriority(lowerPriority, this.queues[lowerPriority].timeQuantum);
this.queues[this.cpuJob.running.priority].jobs.push(this.cpuJob);
this.cpuJob = undefined;
stateChanged = true;
}
else if (this.cpuJob.doingIO()) {
if (this.config.resetTQsOnIO) {
this.cpuJob.resetTQ();
}
this.ioJobs.push(this.cpuJob);
this.cpuJob = undefined;
stateChanged = true;
} else {
this.cpuJob = this.cpuJob;
}
} else {
// IDLE
}
return stateChanged;
}
/**
* Generate jobs based on the scheduler's config
*/
generateJobs() {
this.futureJobs = [];
let id = 1;
this.config.generation.forEach(generate => {
const {
numJobsRange,
jobCreateTimeRange,
ioFrequencyRange,
ioLengthRange,
jobRuntimeRange,
flags
} = generate;
function ran([lower, upper]: number[]) {
const diff = upper - lower;
return lower + (Math.random() * diff);
}
const numJobs = ran(numJobsRange);
for (let i = 0; i <= numJobs; i++) {
this.futureJobs.push(new Job({
id: id++,
flags: flags || [],
createTime: ran(jobCreateTimeRange),
runTime: ran(jobRuntimeRange),
ioFreq: ran(ioFrequencyRange),
ioLength: ran(ioLengthRange),
}));
}
});
}
/**
* Removes the job the should be run next from it's queue
* return undefined if theyre no jobs to run
*/
private popNextJob(): Job | undefined {
for (const queue of this.queues) {
if (queue.jobs.length > 0) {
return queue.jobs.shift();
}
}
}
}
|
code/operating_system/src/scheduling/priority_scheduling/priority_scheduling_non_preemptive.c | //Priority scheduling: each process is assigned a priority. Process with highest priority is to be executed first and so on.
//Non-preemptive algorithms: once a process enters the running state, it cannot be preempted until it completes its allotted time,
#include <stdio.h>
#include <stdlib.h>
typedef struct process
{
int pname, pr, at, bt;
int ct, wt, rt, tat, flag; //flag=0 means unfinished process
}process;
int next_process(process pro[], int n, int t);
int main()
{
int t = 0, n;
process pro[20];
float act = 0, awt = 0, atat = 0, art = 0;
int ntemp, i;
printf("Enter no. of process : ");
scanf("%d", &n);
for(i = 0; i < n; ++i) //input process details
{
printf("Enter Process Name : ");
scanf("%d", &pro[i].pname);
printf("Enter priority : ");
scanf("%d", &pro[i].pr);
printf("Enter arrival time : ");
scanf("%d", &pro[i].at);
printf("Enter burst time : ");
scanf("%d", &pro[i].bt);
}
ntemp = n; //keeping value of n safe
i = -1;
printf("---------Gantt Chart--------\n\n");
while(ntemp > 0)
{
i = next_process(pro, n, t);
if(i > -1)
{
printf("%d| %d |%d \t", t, pro[i].pname, t + pro[i].bt);
pro[i].rt = t; //setting response time
t += pro[i].bt;//updating time
pro[i].ct = t; //getting completion time
pro[i].flag = 1; //flag=1 process is finished
ntemp--;
}
else
{
t++;
}
} //end of execution loop
printf("\n\n----------Table--------\n\n");
printf("Pname\tPriority\tAT\tBT\tCT\tWT\tTAT\tRT\n");
for(i = 0; i < n; ++i)
{
printf("%d\t%d\t\t%d\t%d\t", pro[i].pname, pro[i].pr, pro[i].at, pro[i].bt);
pro[i].wt = pro[i].ct-pro[i].at - pro[i].bt;
pro[i].tat = pro[i].ct - pro[i].at;
printf("%d\t%d\t%d\t%d\n", pro[i].ct, pro[i].wt, pro[i].tat, pro[i].rt);
act += pro[i].ct;
awt += pro[i].wt;
atat += pro[i].tat;
art += pro[i].rt;
}
printf("---------Average Values----------\n\n");
printf("Average CT = %.3f\n", act / n);
printf("Average WT = %.3f\n", awt / n);
printf("Average TAT = %.3f\n", atat / n);
printf("Average RT = %.3f\n", art / n);
return 0;
}
int next_process(process pro[], int n, int t)
{
int i, nprocess = -1;
for(i = 0; i < n; ++i)
{
if(pro[i].at <= t && pro[i].flag == 0)
break;
}
if(i == n)
{
return nprocess;
}
nprocess = i;
for(; i < n; ++i)
{
if(pro[i].at <= t && pro[i].flag == 0 && pro[i].pr < pro[nprocess].pr)
nprocess = i;
}
return nprocess;
} |
code/operating_system/src/scheduling/priority_scheduling/priority_scheduling_preemptive.c | // Priority scheduling: each process is assigned a priority. Process with
// highest priority is to be executed first and so on.
#include <stdio.h>
#include <stdlib.h>
typedef struct process
{
int pname, pr, at, bt;
int ct, wt, rt, tat, flag; // flag=0 means unfinished process
}process;
int next_process(process pro[], int n, int t);
int main()
{
int t = 0, n;
process pro[20];
float act=0, awt=0, atat=0, art=0;
int ntemp, i;
printf("Enter no. of process : ");
scanf("%d", &n);
for (i = 0; i < n; ++i) // input process details
{
printf("Enter Process Name : ");
scanf("%d", &pro[i].pname);
printf("Enter priority : ");
scanf("%d", &pro[i].pr);
printf("Enter arrival time : ");
scanf("%d", &pro[i].at);
printf("Enter burst time : ");
scanf("%d", &pro[i].bt);
}
ntemp = n; // keeping value of n safe
i = -1;
printf("---------Gantt Chart--------\n\n");
while (ntemp > 0)
{
i = next_process(pro, n, t);
if (i > -1)
{
printf("%d| %d |%d \t", t, pro[i].pname, t + pro[i].bt);
pro[i].rt = t; // setting response time
t += pro[i].bt; // updating time
pro[i].ct = t; // getting completion time
pro[i].flag = 1; //flag=1 process is finished
ntemp--;
}
else
{
t++;
}
} // end of execution loop
printf("\n\n----------Table--------\n\n");
printf("Pname\tPriority\tAT\tBT\tCT\tWT\tTAT\tRT\n");
for (i = 0; i < n; ++i)
{
printf("%d\t%d\t\t%d\t%d\t", pro[i].pname, pro[i].pr, pro[i].at, pro[i].bt);
pro[i].wt = pro[i].ct - pro[i].at - pro[i].bt;
pro[i].tat = pro[i].ct - pro[i].at;
printf("%d\t%d\t%d\t%d\n", pro[i].ct, pro[i].wt, pro[i].tat, pro[i].rt);
act += pro[i].ct;
awt += pro[i].wt;
atat += pro[i].tat;
art += pro[i].rt;
}
printf("---------Average Values----------\n\n");
printf("Average CT = %.3f\n", act / n);
printf("Average WT = %.3f\n", awt / n);
printf("Average TAT = %.3f\n", atat / n);
printf("Average RT = %.3f\n", art / n);
return 0;
}
int next_process(process pro[], int n, int t)
{
int i, nprocess = -1;
for (i = 0; i < n; ++i)
{
if (pro[i].at <= t && pro[i].flag == 0)
break;
}
if (i == n)
{
return nprocess;
}
nprocess = i;
for (; i < n; ++i)
{
if (pro[i].at <= t && pro[i].flag == 0 && pro[i].pr < pro[nprocess].pr)
nprocess = i;
}
return nprocess;
} |
code/operating_system/src/scheduling/round_robin_scheduling/round_robin_c/README.md | # Round robin scheduling in C
Just compile the whole, launch the program and follow the steps.
|
code/operating_system/src/scheduling/round_robin_scheduling/round_robin_c/queue.c | /*
* Part of Cosmos by OpenGenus Foundation.
* Basic queue.
* Author : ABDOUS Kamel
*/
#include "queue.h"
int
init_queue(queue* q, size_t n)
{
q->vals = malloc(sizeof(QUEUE_VAL) * (n + 1));
if (q->vals == NULL)
return (-1);
q->n = n + 1;
q->head = q->tail = 0;
return (0);
}
void
free_queue(queue* q)
{
free(q->vals);
}
inline int
queue_empty(queue* q)
{
return (q->head == q->tail);
}
inline int
queue_full(queue* q)
{
return ((q->tail + 1) % q->n == q->head);
}
int
enqueue(queue* q, QUEUE_VAL val)
{
if (queue_full(q))
return (-1);
q->vals[q->tail] = val;
q->tail = (q->tail + 1) % q->n;
return (0);
}
QUEUE_VAL
dequeue(queue* q)
{
if (queue_empty(q))
return (0);
QUEUE_VAL ret = q->vals[q->head];
q->head = (q->head + 1) % q->n;
return (ret);
}
|
code/operating_system/src/scheduling/round_robin_scheduling/round_robin_c/queue.h | /*
* Part of Cosmos by OpenGenus Foundation.
* Basic queue.
* Author : ABDOUS Kamel
*/
#ifndef QUEUE_H
#define QUEUE_H
#include <stdlib.h>
typedef int QUEUE_VAL;
typedef struct
{
QUEUE_VAL* vals;
size_t n;
int head, tail;
} queue;
int
init_queue(queue* q, size_t n);
void
free_queue(queue* q);
int
queue_empty(queue* q);
int
queue_full(queue* q);
int
enqueue(queue* q, QUEUE_VAL val);
QUEUE_VAL
dequeue(queue* q);
#endif // DEQUEUE
|
code/operating_system/src/scheduling/round_robin_scheduling/round_robin_c/round_robin.c | /*
* Part of Cosmos by OpenGenus Foundation.
* scanf is used for reading integers without any verification, so be careful.
* Author : ABDOUS Kamel
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "queue.h"
typedef struct
{
uint32_t turn_around, /* Total turn around of all processes */
wait_time; /* Total wait time of all processes */
} perf_times;
typedef struct
{
uint32_t id, /* Sequential id */
arrival_time,
burst_time,
remain_time;
} process;
/*
* Holds processes array and processes queue.
*/
typedef struct
{
process* procs;
uint32_t n;
uint32_t next_arrive_proc; /* Index of next arriving process */
queue p_queue;
} context_t;
/*
* Init n processes with arrival time & burst time.
*/
int
init_procs(context_t* context);
/*
* This function is used for sorting processes by ascendant arrival time.
*/
int
procs_sort_cmp(const void* proc1, const void* proc2);
/*
* Free context_t struct.
*/
void
free_procs(context_t* context);
/*
* Init performance structure by setting times to 0.
*/
void
init_perf_struct(perf_times* perf_struct);
/*
* Check to see if new arriving processes must be enqueued.
*/
void
enqueue_arriving_processes(context_t* context, uint32_t cur_time);
int
main()
{
uint32_t quantum;
context_t context;
/* Read quantum */
printf("Enter quantum : ");
scanf("%u", &quantum);
/* Init context_t */
if (init_procs(&context) == -1) {
printf("Can't init procs, program will be closed.\n");
return (1);
}
/* Start execution */
perf_times perfs;
init_perf_struct(&perfs);
uint32_t nb_remain = context.n,
cur_time = context.procs[0].arrival_time, /* cur_time is initialized to first arrival time */
i = 0; /* Index of executing process */
enqueue_arriving_processes(&context, cur_time);
/* Run till all processes end */
while (nb_remain != 0) {
/* If the queue is empty, and there's still remaining processes,
we move time forward to the next arriving process */
if (queue_empty(&context.p_queue)) {
cur_time = context.procs[context.next_arrive_proc].arrival_time;
enqueue_arriving_processes(&context, cur_time);
}
i = dequeue(&context.p_queue);
/* This is the end of the process */
if (context.procs[i].remain_time <= quantum) {
cur_time += context.procs[i].remain_time;
context.procs[i].remain_time = 0;
perfs.turn_around += (cur_time - context.procs[i].arrival_time);
perfs.wait_time += (cur_time - context.procs[i].arrival_time - context.procs[i].burst_time);
nb_remain--;
printf("%d- Ended at %d.\n", context.procs[i].id, cur_time);
}
/* Execute till the end of the quantum */
else {
context.procs[i].remain_time -= quantum;
cur_time += quantum;
enqueue(&context.p_queue, i);
printf("%d- Preempted at %d\n", context.procs[i].id, cur_time);
}
/* Maybe we have arriving processes */
if (context.next_arrive_proc < context.n)
enqueue_arriving_processes(&context, cur_time);
}
printf("\nAverage turn around : %d\n", perfs.turn_around / context.n);
printf("Average wait time : %d\n", perfs.wait_time / context.n);
free_procs(&context);
return (0);
}
/*
* Init n processes with arrival time & burst time.
*/
int
init_procs(context_t* context)
{
printf("Enter total number of procs : ");
scanf("%u", &context->n);
context->procs = malloc(sizeof(process) * context->n);
if (context->procs == NULL)
return (-1);
uint32_t i;
for (i = 0; i < context->n; ++i) {
/* Sequential id */
context->procs[i].id = i + 1;
printf("Arrival time of process %d : ", i + 1);
scanf("%u", &context->procs[i].arrival_time);
printf("Burst time of process %d : ", i + 1);
scanf("%u", &context->procs[i].burst_time);
context->procs[i].remain_time = context->procs[i].burst_time;
printf("\n");
}
/* Sort processes by ascendant arrival time */
qsort(context->procs, context->n, sizeof(process), procs_sort_cmp);
/* Init processes queue */
init_queue(&context->p_queue, context->n);
context->next_arrive_proc = 0;
return (0);
}
/*
* This function is used for sorting processes by ascendant arrival time.
*/
int
procs_sort_cmp(const void* proc1, const void* proc2)
{
const process* p1 = (process*)proc1;
const process* p2 = (process*)proc2;
return (p1->arrival_time - p2->arrival_time);
}
/*
* Free context_t struct.
*/
void
free_procs(context_t* context)
{
free(context->procs);
free_queue(&context->p_queue);
}
/*
* Init performance structure by setting times to 0.
*/
void
init_perf_struct(perf_times* perf_struct)
{
perf_struct->turn_around = perf_struct->wait_time = 0;
}
/*
* Check to see if new arriving processes must be enqueued.
*/
void
enqueue_arriving_processes(context_t* context, uint32_t cur_time)
{
uint32_t i = context->next_arrive_proc;
while (i < context->n && context->procs[i].arrival_time <= cur_time) {
enqueue(&context->p_queue, i);
++i;
}
context->next_arrive_proc = i;
}
|
code/operating_system/src/scheduling/round_robin_scheduling/round_robin_scheduling.cpp | #include <iostream>
#include <vector>
using namespace std;
int main()
{
int flag = 0, timeQuantum;
int n, remain;
int waitTime = 0;
cout << "Enter Total Process:\n";
cin >> n;
remain = n;
vector<int> arrivalTime(n);
vector<int> burstTime(n);
vector<int> remainingTime(n);
for (int i = 0; i < n; i++)
{
cout << "Enter Arrival Time and Burst Time for Process\n";
cin >> arrivalTime[i];
cin >> burstTime[i];
remainingTime[i] = burstTime[i];
}
cout << "Enter Time Quantum:\n";
cin >> timeQuantum;
int turnaroundTime;
for (int time = 0, count = 0; remain != 0;)
{
if (remainingTime[count] <= timeQuantum && remainingTime[count] > 0)
{
time += remainingTime[count];
remainingTime[count] = 0;
flag = 1;
}
else if (remainingTime[count] > 0)
{
remainingTime[count] -= timeQuantum;
time += timeQuantum;
}
if (remainingTime[count] == 0 && flag == 1)
{
remain--;
waitTime += time - arrivalTime[count] - burstTime[count];
turnaroundTime += time - arrivalTime[count];
flag = 0;
}
if (count == n - 1)
count = 0;
else if (arrivalTime[count + 1] <= time)
count++;
else
count = 0;
}
cout << "\nAverage Waiting Time is " << waitTime * 1.0 / n;
cout << "\nAvg Turnaround Time is " << turnaroundTime * 1.0 / n << "\n";
return 0;
}
|
code/operating_system/src/scheduling/round_robin_scheduling/round_robin_scheduling.java | // Java program for implementation of RR scheduling
public class round_robin_scheduling
{
// Method to find the waiting time for all
// processes
static void findWaitingTime(int processes[], int n,
int bt[], int wt[], int quantum)
{
// Make a copy of burst times bt[] to store remaining
// burst times.
int rem_bt[] = new int[n];
for (int i = 0 ; i < n ; i++)
rem_bt[i] = bt[i];
int t = 0; // Current time
// Keep traversing processes in round robin manner
// until all of them are not done.
while(true)
{
boolean done = true;
// Traverse all processes one by one repeatedly
for (int i = 0 ; i < n; i++)
{
// If burst time of a process is greater than 0
// then only need to process further
if (rem_bt[i] > 0)
{
done = false; // There is a pending process
if (rem_bt[i] > quantum)
{
// Increase the value of t i.e. shows
// how much time a process has been processed
t += quantum;
// Decrease the burst_time of current process
// by quantum
rem_bt[i] -= quantum;
}
// If burst time is smaller than or equal to
// quantum. Last cycle for this process
else
{
// Increase the value of t i.e. shows
// how much time a process has been processed
t = t + rem_bt[i];
// Waiting time is current time minus time
// used by this process
wt[i] = t - bt[i];
// As the process gets fully executed
// make its remaining burst time = 0
rem_bt[i] = 0;
}
}
}
// If all processes are done
if (done == true)
break;
}
}
// Method to calculate turn around time
static void findTurnAroundTime(int processes[], int n,
int bt[], int wt[], int tat[])
{
// calculating turnaround time by adding
// bt[i] + wt[i]
for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i];
}
// Method to calculate average time
static void findavgTime(int processes[], int n, int bt[],
int quantum)
{
int wt[] = new int[n], tat[] = new int[n];
int total_wt = 0, total_tat = 0;
// Function to find waiting time of all processes
findWaitingTime(processes, n, bt, wt, quantum);
// Function to find turn around time for all processes
findTurnAroundTime(processes, n, bt, wt, tat);
// Display processes along with all details
System.out.println("Processes " + " Burst time " +
" Waiting time " + " Turn around time");
// Calculate total waiting time and total turn
// around time
for (int i=0; i<n; i++)
{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
System.out.println(" " + (i+1) + "\t\t" + bt[i] +"\t " +
wt[i] +"\t\t " + tat[i]);
}
System.out.println("Average waiting time = " +
(float)total_wt / (float)n);
System.out.println("Average turn around time = " +
(float)total_tat / (float)n);
}
|
code/operating_system/src/scheduling/shortest_job_first/SJF.ASM | ; Author: SYEED MOHD AMEEN
; Email: [email protected]
;----------------------------------------------------------------;
; Shortest Job First ;
;----------------------------------------------------------------;
;----------------------------------------------------------------;
; FUNCTION PARAMETERS ;
;----------------------------------------------------------------;
; 1. push ready queue base address ;
; 2. push base address of process queue ;
; 3. push no. of process in process queue ;
;----------------------------------------------------------------;
SJF:
POP AX ;POP RET ADDRESS OF SUBROUTINE
POP CX ;NO. OF PROCESS
POP SI ;BASE ADDRESS OF PROCESS LENGTH
POP DI ;READY QUEUE BASE ADDRESS
PUSH AX ;RETURN ADDRESS OF SUBROUTINE
; CALL SELECTION SORT TO SORT (PROCESS JOBS) {According to Burst Time}
PUSH CX
PUSH SI
CALL SELSORT
; ENTER SHORTED PROCESS INTO (READY QUEUE)
REPEAT_SJF:
MOV [DI],[SI] ;ENTER PROCESS INTO READY QUEUE
INC DI
INC SI
LOOP REPEAT_SJF
RET ;RETURN SJF SUBROUTINE
;--------------------------------------;
; SELECTION SORT ;
;--------------------------------------;
SELSORT:
POP AX ;POP RET ADDRESS OF SUBROUTINE
POP SI ;BASE ADDRESS OF ARRAY
POP CX ;COUNTER REGISTER
PUSH AX ;PUSH RET ADDRESS OF SUBROUTINE
COUNTER_SELSORT: EQU 0X4500
DPTR_SELSORT: EQU 0X4510
MOV ES:[COUNTER_SELSORT],CX
MOV ES:[COUNTER_SELSORT+2],CX
MOV ES:[DPTR_SELSORT],SI
XOR BX,BX ;CLEAR INDEX REGISTER
REPEAT2_SELSORT:
MOV AH,[SI+BX] ;MOVE INITIAL ELEMENT AND COMPARE IN ENTIRE ARRAY
REPEAT1_SELSORT:
CMP AH,[SI+BX+1]
JC NOSWAP_SELSORT
XCHG AH,[SI+BX+1]
NOSWAP_SELSORT:
INC SI ;INCREMENT INDEX REGISTER
LOOP REPEAT1_SELSORT ;REPEAT UNTIL COUNTER != 0
MOV SI,ES:[DPTR_SELSORT] ;MOVE BASE ADDRESS OF ARRAY
DEC ES:[COUNTER_SELSORT+2]
MOV CX,ES:[COUNTER_SELSORT+2] ;MOVE COUNTER INTO CX REG.
INC BX ;INCREMENT INDEX REGISTER
CMP BX,ES:[COUNTER_SELSORT]
JNE SKIP_SELSORT ;IF BX == ES:[COUNTER_SELSORT] RET SUBROUTINE
RET ;RETURN SUBROUTINE
SKIP_SELSORT:
JMP REPEAT2_SELSORT
|
code/operating_system/src/scheduling/shortest_job_first/sjf.cpp | #include <iostream>
#include <stdlib.h>
using namespace std;
void input_burst_arrival_time(int burst_time[],int process[],int arrival_time[])
{
cout<<"Enter burst time and arrival time (in pairs) for four processes : "<<endl;
for(int i=0;i<4;i++)
// The user is asked to enter burst time and arrival time of 4 processes.
{
process[i]=i;
cin>>burst_time[i];
cin>>arrival_time[i];
// Input is taken for the butst time and arrival time.
}
}
void sort_arrival_time(int arrival_time[],int process[],int burst_time[])
// Function is used to sort the processes on the basis of their arrival time.
// In case, two processes have same arrival time they will be placed next to each other.
{
for(int i=0;i<4;i++)
{
for(int j=i+1;j<4;j++)
{
if(arrival_time[i]>arrival_time[j])
{
swap(process[i],process[j]);
swap(arrival_time[i],arrival_time[j]);
swap(burst_time[i],burst_time[j]);
// Process id, arrival time as well as burst time of the processes are sorted inaccordance with arrival time.
}
}
}
}
void sort_burst_time(int arrival_time[],int process[],int burst_time[])
// Function is used to sort the processes with same burst time according to their arrival time.
{
for(int i=0;i<4;i++)
{
for(int j=i+1;j<4;j++)
{
if(arrival_time[i]==arrival_time[j])
// Condition is checked if two processes have same arrival time.
{
if(burst_time[i]>burst_time[j])
// In case the arrival time is same, the processes are compared according to their burst time and further sorted.
{
swap(process[i],process[j]);
swap(arrival_time[i],arrival_time[j]);
swap(burst_time[i],burst_time[j]);
}
}
}
}
}
void sjf_operations(int arrival_time[],int waiting_time[],int burst_time[],int turn_around_time[],int completion_time[])
// This function is used to calcuate waiting time and turn around time fot the processes.
{
int temp;
int value;
completion_time[0] = arrival_time[0] + burst_time[0];
turn_around_time[0] = completion_time[0] - arrival_time[0];
waiting_time[0] = turn_around_time[0] - burst_time[0];
// For the first process the completion time, waiting time an turn around time are initialised.
for(int i=1;i<4;i++)
// Process from the seconf are iterated to till the last process in reached.
{
temp = completion_time[i-1];
int low = burst_time[i];
for(int j=i;j<4;j++)
{
if(temp >= arrival_time[j] && low >=burst_time[j])
// Completion time of previous process is compare with the arrival time of current process as well the burst time is compared.
{
low = burst_time[j];
value = j;
}
}
completion_time[value] = temp + burst_time[value];
turn_around_time[value] = completion_time[value] - arrival_time[value];
waiting_time[value] = turn_around_time[value] - burst_time[value];
// Value of completion time, waiting time and turn around time is calculated using formulae.
}
}
void print_table(int process[],int burst_time[],int waiting_time[],int turn_around_time[],int arrival_time[])
// Table is printed which prints the calculated value as the output.
{
cout<<endl<<endl;
cout<<"Process"<<" \t"<<"Arrival Time"<<" \t"<<"Burst Time"<<" \t"<<"Waiting Time"<<" \t"<<"Turn Around Time"<<endl;
for(int i=0;i<4;i++)
{
cout<<process[i]<<"\t\t"<<arrival_time[i]<<"\t\t"<<burst_time[i]<<"\t\t"<<waiting_time[i]<<"\t\t"<<turn_around_time[i]<<endl;
}
cout<<endl<<endl;
}
int main()
{
int process[4];
int burst_time[4];
int waiting_time[4];
int completion_time[4];
int turn_around_time[4];
int arrival_time[4];
input_burst_arrival_time(burst_time,process,arrival_time);
sort_arrival_time(arrival_time,process,burst_time);
sort_burst_time(arrival_time,process,burst_time);
sjf_operations(arrival_time,waiting_time,burst_time,turn_around_time,completion_time);
print_table(process,burst_time,waiting_time,turn_around_time,arrival_time);
return 0;
}
|
code/operating_system/src/scheduling/shortest_seek_time_first/shortest_seek_time_first.c | // C program for implementing Shortest Seek Time First
// Disk Scheduling
#include<stdio.h>
#include<stdlib.h> // has inbuilt quick sort, abs for ints
// For Ascending Order Sort
int compare (const void * a, const void * b) {
return ( *(int*)a - *(int*)b );
}
int main() {
// Initialization
int noOfRequests, headAt;
int requests[20];
int headMovement = 0;
int left = 0 , right = 0 ;
// Read input
printf("Enter no. of requests ... ");
scanf("%d", &noOfRequests);
printf("Enter no. of requests ... \n");
for ( int i = 0 ; i < noOfRequests; i ++)
scanf("%d", &requests[i]);
printf("Enter the starting position for head ... ");
scanf("%d", &headAt);
/*============ SSTF ================= */
// quick sort
qsort(requests, noOfRequests, sizeof(int), compare);
// initializing left and right counters
while ( requests[right] < headAt){
left = right;
right ++;
}
// Until head reaches extreme left 0 or extreme right 199
while ( left != -1 && right != noOfRequests){
// Left request is near to head
if ( abs( headAt - requests[left]) < abs (headAt - requests[right]) ){
headMovement += abs( headAt - requests[left]);
headAt = requests[left];
left --;
}
// Right request is near to head
else{
headMovement += abs( headAt - requests[right]);
headAt = requests[right];
right ++;
}
}
// When we have requests only to the left of the head
while( left != -1){
headMovement += abs( headAt - requests[left]);
headAt = requests[left];
left --;
}
// When we have requests only to the right of the head
while( right != noOfRequests ){
headMovement += abs( headAt - requests[right]);
headAt = requests[right];
right ++;
}
/* ================== SSTF ENDS ================ */
printf("Total head movement is %d\n", headMovement);
}
/*
Example form Operating System Concepts 7th edition by Silberschatz, Galvin, Gagne
Page no. 459
OUTPUT:
Enter no. of requests ... 8
Enter no. of requests ...
98 183 37 122 14 124 65 67
Enter the starting position for head ... 53
Total head movement is 236
*/
|
code/operating_system/src/scheduling/shortest_seek_time_first/shortest_seek_time_first.cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n;
cout << "Enter number of process: ";
cin >> n;
vector<int> burstTime(n); // Array of burst times of processes
cout << "Enter Burst time: \n";
for (int i = 0; i < n; i++)
{
cout << "Process[" << i + 1 << "]: ";
cin >> burstTime[i];
}
sort(burstTime.begin(), burstTime.end()); // Sort the burst times
vector<int> waitingTime(n);
int total = 0;
for (int i = 1; i < n; i++)
{
waitingTime[i] = 0;
for (int j = 0; j < i; j++)
waitingTime[i] += burstTime[j];
total += waitingTime[i];
}
// Average waiting time = Total waiting time / no of processes
int averageWaitingTime = (float)total / n;
total = 0;
vector<int> turnAroundTime(n);
cout << "\nProcess\t Burst Time \tWaiting Time\tTurnaround Time";
for (int i = 0; i < n; i++)
{
turnAroundTime[i] = burstTime[i] + waitingTime[i]; //Calculating Turnaround Time
total += turnAroundTime[i];
cout << "\np" << i + 1 << "\t\t" << burstTime[i] << "\t\t" << waitingTime[i] << "\t\t" <<
turnAroundTime[i];
}
// Average Turnaround Time = total turn around time / no of processes
int averageTurnAroundTime = (float)total / n;
cout << "\nAverage Waiting Time: " << averageWaitingTime << "\n";
cout << "Average Turnaround Time: " << averageTurnAroundTime << "\n";
return 0;
}
|
code/operating_system/src/scheduling/smallest_remaining_time_first/srtf.c | #include <stdio.h>
void main()
{
int arrival_time[10], burst_time[10], temp[10];
int i, smallest, count = 0, time, limit;
double wait_time = 0, turnaround_time = 0, end;
float average_waiting_time, average_turnaround_time;
printf("\nEnter the Total Number of Processes:\t");
scanf("%d", &limit);
printf("\nEnter Details of \n");
for(i = 0; i < limit; i++)
{
printf("\nEnter Arrival Time:\t");
scanf("%d", &arrival_time[i]);
printf("Enter Burst Time:\t");
scanf("%d", &burst_time[i]);
temp[i] = burst_time[i];
}
burst_time[9] = 9999;
for(time = 0; count != limit; time++)
{
smallest = 9;
for(i = 0; i < limit; i++)
{
if(arrival_time[i] <= time && burst_time[i] < burst_time[smallest] && burst_time[i] > 0)
{
smallest = i;
}
}
burst_time[smallest]--;
if(burst_time[smallest] == 0)
{
count++;
end = time + 1;
wait_time = wait_time + end - arrival_time[smallest] - temp[smallest];
turnaround_time = turnaround_time + end - arrival_time[smallest];
}
}
average_waiting_time = wait_time / limit;
average_turnaround_time = turnaround_time / limit;
printf("\n\nAverage Waiting Time:\t%lf\n", average_waiting_time);
printf("Average Turnaround Time:\t%lf\n", average_turnaround_time);
}
|
code/operating_system/src/shell/README.md | # Shell
## What is Shell?
Simply put, the shell is a program that takes commands from the keyboard and gives them to the operating system to perform. In the old days, it was the only user interface available on a Unix-like system such as Linux. Nowadays, we have graphical user interfaces (GUIs) in addition to command line interfaces (CLIs) such as the shell.
On most Linux systems a program called bash (which stands for Bourne Again SHell, an enhanced version of the original Unix shell program, sh, written by Steve Bourne) acts as the shell program. Besides bash, there are other shell programs that can be installed in a Linux system. These include: ksh, tcsh and zsh. |
code/operating_system/src/shell/c/README.md | # Implement a Shell in C
The Shell include some feature as follows,
1. It is able to run all the single-process commands.
2. It is able to run all the two-process pipelines.
3. It is able to handle input and output redirection.
4. It is able to execute commands in the background.
## What is a Makefile
A makefile is a file containing a set of directives used by a make build automation tool to generate a target/goal. This is convenient when working with multiple C files and header files.
## How to make this work - Using the Makefile
First step: make clean
Second step: make all
Last step: ./Shell
## Note
"cd" is **not** a built-in command, so you need to build a "cd" function and use system call "chdir" to implement "cd".
##
You are, of course, free and encouraged to add more features to the shell.
|
code/operating_system/src/shell/c/makefile | all: Shell
B013040049_Shell: Shell.o
gcc -o Shell Shell.o
B013040049_Shell.o:
gcc -c Shell.c
dep:
gcc -M *.c > .depend
clean:
rm -f *.o Shell .depend
|
code/operating_system/src/shell/c/shell.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
#define SIZE 50
#define STD_INPUT 0
#define STD_OUTPUT 1
#define TRUE 1
void cd (char *pathname) { /*add cd fuction*/
chdir(pathname);
}
int main(void)
{
while (TRUE) {
char *argv_1[SIZE]={0}, *argv_2[SIZE]={0}, *temp=NULL;
char input[100]={0};
int i, background=0, work;
char *process_1, *process_2;
int fd[2], _fd;
pid_t pid[2], _pid; /*_pid for the return value from fork()*/
char *pathname;
printf("C_Shell:");
fgets(input, 100, stdin); /*stantard input stream*/
if (input[strlen(input)-1]=='\n') { /*get the string length*/
input[strlen(input)-1]='\0';
}
if (strchr(input, '&')!=NULL) { /*Search the first &*/
char *p;
p=strrchr(input, '&'); /*record the address of last & exist*/
input[(int)(p-input)]='\0';
background=1;
}
if (strstr(input,"cd")!=NULL) { /*cd function is a builtin*/
temp = strtok(input, " ");
for (i=0; i<=1; i++) {
argv_1[i]=temp;
temp=strtok(NULL, " ");
cd(argv_1[1]);
}
}
if (strchr(input, '|')!=NULL) { /*two-process*/
work=1;
process_1=strtok(input, "|");
process_2=strtok(NULL, "|");
temp=strtok(process_1, " ");
for (i=0; i<SIZE && temp!=NULL ; i++) {
argv_1[i]=temp;
temp=strtok(NULL, " ");
}
temp=strtok(process_2, " ");
for (i=0; i<SIZE && temp!=NULL ; i++) {
argv_2[i]=temp;
temp=strtok(NULL, " ");
}
}
else if (strchr(input, '<')!=NULL) { /*input redirection,like read*/
work=2;
process_1=strtok(input, "<");
process_2=strtok(NULL, "<");
temp=strtok(process_1, " ");
for (i=0; i<SIZE && temp!=NULL ; i++) {
argv_1[i]=temp;
temp=strtok(NULL, " ");
}
temp=strtok(process_2, " ");
for (i=0; i<SIZE && temp!=NULL ; i++) {
argv_2[i]=temp;
temp=strtok(NULL, " ");
}
}
else if (strchr(input, '>')!=NULL) { /*output redirection,like write*/
work=3;
process_1=strtok(input, ">");
process_2=strtok(NULL, ">");
temp=strtok(process_1, " ");
for (i=0; i<SIZE && temp!=NULL; i++) {
argv_1[i]=temp;
temp=strtok(NULL, " ");
}
temp=strtok(process_2, " ");
for (i=0; i<SIZE && temp!=NULL; i++) {
argv_2[i]=temp;
temp=strtok(NULL, " ");
}
}
else { /*one-process*/
work=4;
temp=strtok(input, " ");
for (i=0; i<SIZE && temp!=NULL; i++) {
argv_1[i]=temp;
temp=strtok(NULL, " ");
}
}
pipe(&fd[0]); /*create pipe and return two file descriptor*/
/**/
/*fd[0]put file descriptor for read,fd[1] put file descriptor for write*/
if ((_pid=fork())!=0) { /*create child process*/
if (background==1) {
continue;
}
close(fd[0]); /*close pipe,if not it will cause dead lock*/
close(fd[1]); /*close pipe*/
waitpid(_pid, NULL, 0); /*wait child process exit。pid = -1 will wait any child process*/
}
else {
switch (work) {
case 1: /*two-process*/
if ((pid[0]=fork())==0) {
close(fd[0]); /*close read*/
close(STD_OUTPUT); /*prepare new stdout*/
dup(fd[1]);
close(fd[1]);
execvp(argv_1[0], argv_1);
exit(0);
}
if ((pid[1]=fork())==0) {
close(fd[1]); /*close write*/
close(STD_INPUT); /*prepare new stdin*/
dup(fd[0]);
close(fd[0]);
execvp(argv_2[0], argv_2);
exit(0);
}
close(fd[0]);
close(fd[1]);
waitpid(pid[1], NULL, 0); /*pid[1]=0 will wait any wait group process ID and parent process that have same child process to leave*/
break;
case 2: /*input*/
_fd=open(argv_2[0], O_RDONLY);
close(STD_INPUT);
dup2(_fd, STD_INPUT);
close(_fd);
execvp(argv_1[0], argv_1);
break;
case 3: /*output*/
_fd=open(argv_2[0], O_WRONLY | O_CREAT | O_TRUNC, 0644);
close(STD_OUTPUT);
dup2(_fd, STD_OUTPUT);
close(_fd);
execvp(argv_1[0], argv_1);
break;
case 4:
execvp(argv_1[0], argv_1);
}
}
}
return (0);
}
|
code/operating_system/test/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/quantum_algorithms/grovers_algorithm/P1_grover_plot.py | ### Imports required for this solution
import matplotlib.pyplot as plot
import numpy as NP
import hashlib
from math import sqrt, pi
from collections import OrderedDict
from statistics import mean
###############
### PlotGraph(n, amplitude): Plots the graph for target value with the highest amplitude.
def PlotGraph(n, amp_val):
plot.title('Grovers Algorithm')
plot.ylabel('Amplitude Value')
y_pos = NP.arange(n)
plot.bar(y_pos, amp_val.values(), align='center', color='b') # Here 'b' is color code for blue in matplotlib
plot.xticks(y_pos, amp_val.keys())
plot.show()
###############
### GetOracle(x_value): Returns the hex digest of the x value. This is referred to as the Oracle function.
def GetOracle(x_val):
return hashlib.sha256(bytes(x_val, 'utf-8')).hexdigest()
###############
### GroverAlgo(target,objects,n_value,no_of_rounds): Returns amplitude retrieved based on the 1/sqrt(n_value).
def GroverAlgo(tgt, objs, nval, rounds):
y_pos = NP.arange(nval)
# Calculate amplitude to be returned
amp = OrderedDict.fromkeys(objs, 1/sqrt(nval))
for i in range(0, rounds, 2):
for j, k in amp.items():
if(GetOracle(j)==GetOracle(tgt)):
amp[j] = k*(-1)
avg = mean(amp.values())
for j, k in amp.items():
if(GetOracle(j)==GetOracle(tgt)):
amp[j] = (2*avg) + abs(k)
continue
amp[j] = k-(2*(k-avg))
##
print("Final Map with corresponding grover_amplitude", end="\n\n")
print(amp, end="\n\n")
return amp
###############
### Driver-Code
target = '8' #Value to be searched
objects = ('10', '20', '8', '9','16','21','22') #(Set) of different values
no_of_objs = len(objects)
no_of_rounds = int((pi/4)*sqrt(no_of_objs))
print("Number of rounds are {}".format(no_of_rounds),end="\n\n")
amp = GroverAlgo(target, objects, no_of_objs, no_of_rounds) #Calling Grover's Algo
###############
### To-Plot-Graph :- This part is the solution to P-1. in README.md
PlotGraph(no_of_objs, amp)
#Note:- If the target is found then it will have highest amplitude else all objects will have same amplitude.
###############
|
code/quantum_algorithms/grovers_algorithm/README.md | # Grover’s Algorithm
## Detailed Resources to Understand the Algorithm:-
+ [Quantum Computing Resources](https://www.topcoder.com/quantum-computing-for-beginners-what-you-need-to-know) - For Beginners
+ [Topcoder's Tutorial on Grover's Algorithm](https://www.topcoder.com/grovers-algorithm-in-quantum-computing)
+ [Wikipedia](https://en.wikipedia.org/wiki/Grover%27s_algorithm) - For complete details of this algorithm
## Complexity:-
The time complexity for Grover's Searching Algo is **O(sqrt(N))** where, N is the number of element in the set that is to be searched.
### Live Contest for More Problems:-
+ [Topcoder's Fujitsu challenge](https://www.topcoder.com/blog/an-inside-look-at-the-first-quantum-computing-challenge) – Quantum computing challenge using simulated annealing
+ More To Be Added
# Problem Statements
**P-1.** Implement the Grover’s Searching Algorithm that searches the target value from a set and plots the target value with the highest amplitude on Graph.
**Implementation:-** P1_grover_plot.py
*More To Be Added*
### *Note:- Python 3.5 or Greater is Recommended for Compiling*
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/quantum_algorithms/shors_algorithm/P1_shor_primefactorization.py | ### Imports required for this solution
import math
import random as rdm
###############
############ Quantum Part (START) ############
### QuantumMapping: Keeps track of state and amplitude of an electron.
class QuantumMapping:
def __init__(self, state, amplitude):
self.state = state
self.amplitude = amplitude
###############
### QuantumState: Keeps track properties amplitude, register, and entangled list.
class QuantumState:
def __init__(self, amplitude, register):
self.amplitude = amplitude
self.register = register
self.entangled = {}
## entangle(fromState, amplitude): Sets the entangled to QuantumState initialised with fromState.
def entangle(self, fromState, amplitude):
register = fromState.register
entanglement = QuantumMapping(fromState, amplitude)
try:
self.entangled[register].append(entanglement)
except KeyError:
self.entangled[register] = [entanglement]
## entangles(register): Returns the length of the entangled states.
def entangles(self, register=None):
entangles = 0
if register is None:
for states in self.entangled.values():
entangles += len(states)
else:
entangles = len(self.entangled[register])
return entangles
###############
### QuantumRegister: Contains numBits, numStates, entangled list and states array.
class QuantumRegister:
def __init__(self, numBits):
self.numBits = numBits
self.numStates = 1 << numBits
self.entangled = []
self.states = [QuantumState(complex(0.0), self) for x in range(self.numStates)]
self.states[0].amplitude = complex(1.0)
## propagate(fromRegister): Sets the propagate on the register.
def propagate(self, fromRegister=None):
if fromRegister is not None:
for state in self.states:
amplitude = complex(0.0)
try:
entangles = state.entangled[fromRegister]
for entangle in entangles:
amplitude += entangle.state.amplitude * entangle.amplitude
state.amplitude = amplitude
except KeyError:
state.amplitude = amplitude
for register in self.entangled:
if register is fromRegister:
continue
register.propagate(self)
## map(toRegister, mapping, propagate): Sets the normalized tensor X and Y lists.
def map(self, toRegister, mapping, propagate=True):
self.entangled.append(toRegister)
toRegister.entangled.append(self)
mapTensorX = {}
mapTensorY = {}
for x in range(self.numStates):
mapTensorX[x] = {}
codomain = mapping(x)
for element in codomain:
y = element.state
mapTensorX[x][y] = element
try:
mapTensorY[y][x] = element
except KeyError:
mapTensorY[y] = {x: element}
def normalize(tensor, p=False):
lSqrt = math.sqrt
for vectors in tensor.values():
sumProb = 0.0
for element in vectors.values():
amplitude = element.amplitude
sumProb += (amplitude * amplitude.conjugate()).real
normalized = lSqrt(sumProb)
for element in vectors.values():
element.amplitude = element.amplitude / normalized
normalize(mapTensorX)
normalize(mapTensorY, True)
# Entangle the registers
for x, yStates in mapTensorX.items():
for y, element in yStates.items():
amplitude = element.amplitude
toState = toRegister.states[y]
fromState = self.states[x]
toState.entangle(fromState, amplitude)
fromState.entangle(toState, amplitude.conjugate())
if propagate:
toRegister.propagate(self)
## measure(): Returns the final X state.
def measure(self):
measure = rdm.random()
sumProb = 0.0
# Pick a state
finalXval = None
finalState = None
for x, state in enumerate(self.states):
amplitude = state.amplitude
sumProb += (amplitude * amplitude.conjugate()).real
if sumProb > measure:
finalState = state
finalXval = x
break
# If state was found, update the system
if finalState is not None:
for state in self.states:
state.amplitude = complex(0.0)
finalState.amplitude = complex(1.0)
self.propagate()
return finalXval
## entangles(): Returns the entangled state value.
def entangles(self, register=None):
entanglevals = 0
for state in self.states:
entanglevals += state.entangles(None)
return entanglevals
## amplitudes(): Returns the amplitudes array based on the Quantum States.
def amplitudes(self):
amplitudesarr = []
for state in self.states:
amplitudesarr.append(state.amplitude)
return amplitudesarr
###############
### ListEntangles(register): Print list of entangles.
def ListEntangles(register):
print("Entangles: " + str(register.entangles()))
###############
### ListAmplitudes(register): Print values of amplitudes of the register.
def ListAmplitudes(register):
amplitudes = register.amplitudes()
for x, amplitude in enumerate(amplitudes):
print("State #" + str(x) + "'s Amplitude value: " + str(amplitude))
###############
### hadamard(lambda_x, QBit): Returns the codomain array after appending the Quantum Mapping of the QBits.
def hadamard(x, Q):
codomainarr = []
for y in range(Q):
amplitude = complex(pow(-1.0, bitCount(x & y) & 1))
codomainarr.append(QuantumMapping(y, amplitude))
return codomainarr
###############
### QModExp(a_value, exp_val, mod_value): Quantum Modular Exponentiation.
def QModExp(a_val, exp_val, mod_val):
state = ModExp(a_val, exp_val, mod_val)
amplitude = complex(1.0)
return [QuantumMapping(state, amplitude)]
###############
### QFT(x, QBit): Quantum Fourier Transform
def QFT(x, Q):
fQ = float(Q)
k = -2.0 * math.pi
codomainarr = []
for y in range(Q):
theta = (k * float((x * y) % Q)) / fQ
amplitude = complex(math.cos(theta), math.sin(theta))
codomainarr.append(QuantumMapping(y, amplitude))
return codomainarr
###############
### FindPeriod(a, N): Returns the period 'r' for the function.
def FindPeriod(a, N):
nNumBits = N.bit_length()
inputNumBits = (2 * nNumBits) - 1
inputNumBits += 1 if ((1 << inputNumBits) < (N * N)) else 0
Q = 1 << inputNumBits
print("Finding the period...")
print("Q = " + str(Q) + "\ta = " + str(a))
inputRegister = QuantumRegister(inputNumBits)
hmdInputRegister = QuantumRegister(inputNumBits)
qftInputRegister = QuantumRegister(inputNumBits)
outputRegister = QuantumRegister(inputNumBits)
print("Registers generated")
print("Performing Hadamard on input register")
inputRegister.map(hmdInputRegister, lambda x: hadamard(x, Q), False)
print("Hadamard Success")
print("Mapping input register to output register, where f(x) is a^x mod N")
hmdInputRegister.map(outputRegister, lambda x: QModExp(a, x, N), False)
print("Modular exponentiation success")
print("Performing quantum Fourier transform on output register")
hmdInputRegister.map(qftInputRegister, lambda x: QFT(x, Q), False)
inputRegister.propagate()
print("Quantum Fourier transform success")
print("Performing a measurement on the output register")
y = outputRegister.measure()
print("Output register measured\ty = " + str(y))
print("Performing a measurement on the periodicity register")
x = qftInputRegister.measure()
print("QFT register measured\tx = " + str(x))
if x is None:
return None
print("Finding the period via continued fractions")
rperiod = ContinuedFraction(x, Q, N)
print("Candidate period\tr = " + str(rperiod))
return rperiod
###############
############ Quantum Part (END) ############
############ Classical Functions for Shor's Algorithm (START) ############
### bitCount(x_value): Returns no. of set bits in x.
BIT_LIMIT = 12
def bitCount(x_val):
sumBits = 0
while x_val > 0:
sumBits += x_val & 1
x_val >>= 1
return sumBits
###############
### GCD(a, b): Returns GCD(a,b) by using Euclid's Algorithm.
def GCD(a, b):
while b != 0:
rem = a % b
a = b
b = rem
return a
###############
### ExtendedGCD(a, b): Returns GCD(a,b) using Extended Euclidean Algorithm.
def ExtendedGCD(a, b):
fractions = []
while b != 0:
fractions.append(a // b)
rem = a % b
a = b
b = rem
return fractions
###############
### ContinuedFraction(y, Q, N): Returns a continued fraction based on partial fractions derived from extended GCD.
def ContinuedFraction(y, Q, N):
fractions = ExtendedGCD(y, Q)
depth = 2
def partial(fractions, depth):
c = 0
r = 1
for i in reversed(range(depth)):
tR = fractions[i] * r + c
c = r
r = tR
return c
rcf = 0
for d in range(depth, len(fractions) + 1):
tR = partial(fractions, d)
if tR == rcf or tR >= N:
return rcf
rcf = tR
return rcf
###############
### ModExp(a, exp, mod): Returns (a^exp)%mod.
def ModExp(a, exp, mod):
fx = 1
while exp > 0:
if (exp & 1) == 1:
fx = fx * a % mod
a = (a * a) % mod
exp = exp >> 1
return fx
###############
### Pick(N): Returns a random value < N.
def Pick(N_val):
return math.floor((rdm.random() * (N_val - 1)) + 0.5)
###############
### CheckCandidates(a, r, n, neighbourhood): Returns candidates which have period 'r'.
def CheckCandidates(a, r, n, nbrhood):
if r is None:
return None
# Check multiples
for i in range(1, nbrhood + 2):
tR = i * r
if ModExp(a, a, N) == ModExp(a, a + tR, N):
return tR
# Check lower neighborhood
for tR in range(r - nbrhood, r):
if ModExp(a, a, N) == ModExp(a, a + tR, N):
return tR
# Check upper neigborhood
for tR in range(r + 1, r + nbrhood + 1):
if ModExp(a, a, N) == ModExp(a, a + tR, N):
return tR
return None
###############
############ Classical Functions for Shor's Algorithm (START) ############
###### The Main Shor's Algorithm ######
### ShorAlgo(N, attempts, neighborhood, no_of_periods): Runs Shor’s algorithm to find the prime factors of a given Number N.
def ShorAlgo(N, attempts=1, nbrhood=0.0, no_of_Periods=1):
if N.bit_length() > BIT_LIMIT or N < 3:
return False
periods = []
nbrhood = math.floor(N * nbrhood) + 1
print("N = " + str(N))
print("Neighborhood = " + str(nbrhood))
print("Number of Periods = " + str(no_of_Periods))
for attempt in range(attempts):
print("\nAttempt #" + str(attempt))
a = Pick(N)
while a < 2:
a = Pick(N)
d = GCD(a, N)
if d > 1:
print("Found factors classically, re-attempt")
continue
r = FindPeriod(a, N)
print("Checking candidate period, nearby values, and multiples")
r = CheckCandidates(a, r, N, nbrhood)
if r is None:
print("Period was not found, re-attempt")
continue
if (r % 2) > 0:
print("Period was odd, re-attempt")
continue
d = ModExp(a, (r // 2), N)
if r == 0 or d == (N - 1):
print("Period was trivial, re-attempt")
continue
print("Period found\tr = " + str(r))
periods.append(r)
if len(periods) < no_of_Periods:
continue
print("\nFinding LCM of all periods")
r = 1
for period in periods:
d = GCD(period, r)
r = (r * period) // d
b = ModExp(a, (r // 2), N)
f1 = GCD(N, b + 1)
f2 = GCD(N, b - 1)
return [f1, f2]
return None
###############
### Driver-Code
def main():
N = 35 # Integer whose Prime-Factorization is to be done
attempts = 5 # Number of quantum attemtps to perform
nbrhood = 0.01 # Neighborhood size for checking candidates (as percentage of N)
periods = 2 # Number of periods to get before determining LCM
factors = ShorAlgo(N, attempts, nbrhood, periods)
if factors is not None:
print("Factors:\t" + str(factors[0]) + ", " + str(factors[1]))
if __name__ == "__main__":
main()
###############
|
code/quantum_algorithms/shors_algorithm/README.md | # Shor’s Algorithm
## Detailed Resources to Understand the Algorithm:-
+ [Quantum Computing Resources](https://www.topcoder.com/quantum-computing-for-beginners-what-you-need-to-know) - For Beginners
+ [Topcoder's Tutorial on Shor's Algorithm](https://www.topcoder.com/shors-algorithm-in-quantum-computing)
+ [Wikipedia](https://en.wikipedia.org/wiki/Grover%27s_algorithm) - For complete details of this algorithm
## Basic Info:-
Shor’s algorithm was invented by Peter Shor for integer factorization in 1994. It finds the prime factors of an integer N. Quantum Fourier Transform is the basis of the algorithm which finds the period of the function which gives the value based on the product of the prime factors.
## Complexity:-
Shor’s algorithm executes in polynomial time of O(log N) on a Quantum Computer and O((log N)3) on Classical Computers.
### Live Contest for More Problems:-
+ [Topcoder's Fujitsu challenge](https://www.topcoder.com/blog/an-inside-look-at-the-first-quantum-computing-challenge) – Quantum computing challenge using simulated annealing
+ More To Be Added
# Problem Statements
**P-1.** Implement Shor’s algorithm to prime factorise an integer N.
**Implementation:-** P1_shor_primefactorization.py
*More To Be Added*
### *Note:- Python 3.5 or Greater is Recommended for Compiling*
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/randomized_algorithms/src/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/randomized_algorithms/src/birthday_paradox/birthday_paradox.py | # Part of Cosmos by OpenGenus Foundation
import math
# Function returns number of people that should be present for a given probability, p
def compute_people(p):
return math.ceil(math.sqrt(2 * 365 * math.log(1 / (1 - p))))
# Driver code
if __name__ == "__main__":
print(compute_people(0.5))
print(compute_people(0.9))
|
code/randomized_algorithms/src/karger_minimum_cut_algorithm/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus)
Below Karger’s algorithm can be implemented in O(E) = O(V^2) time
```
1) Initialize contracted graph CG as copy of original graph
2) While there are more than 2 vertices.
a) Pick a random edge (u, v) in the contracted graph.
b) Merge (or contract) u and v into a single vertex (update
the contracted graph).
c) Remove self-loops
3) Return cut represented by two vertices.
``` |
code/randomized_algorithms/src/karger_minimum_cut_algorithm/karger_minimum_cut_algorithm.cpp | // Karger's algorithm to find Minimum Cut in an
// undirected, unweighted and connected graph.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// a structure to represent a unweighted edge in graph
struct Edge
{
int src, dest;
};
// a structure to represent a connected, undirected
// and unweighted graph as a collection of edges.
struct Graph
{
// V-> Number of vertices, E-> Number of edges
int V, E;
// graph is represented as an array of edges.
// Since the graph is undirected, the edge
// from src to dest is also edge from dest
// to src. Both are counted as 1 edge here.
Edge* edge;
};
// A structure to represent a subset for union-find
struct subset
{
int parent;
int rank;
};
// Function prototypes for union-find (These functions are defined
// after kargerMinCut() )
int find(struct subset subsets[], int i);
void Union(struct subset subsets[], int x, int y);
// A very basic implementation of Karger's randomized
// algorithm for finding the minimum cut. Please note
// that Karger's algorithm is a Monte Carlo Randomized algo
// and the cut returned by the algorithm may not be
// minimum always
int kargerMinCut(struct Graph* graph)
{
// Get data of given graph
int V = graph->V, E = graph->E;
Edge *edge = graph->edge;
// Allocate memory for creating V subsets.
struct subset *subsets = new subset[V];
// Create V subsets with single elements
for (int v = 0; v < V; ++v)
{
subsets[v].parent = v;
subsets[v].rank = 0;
}
// Initially there are V vertices in
// contracted graph
int vertices = V;
// Keep contracting vertices until there are
// 2 vertices.
while (vertices > 2)
{
// Pick a random edge
int i = rand() % E;
// Find vertices (or sets) of two corners
// of current edge
int subset1 = find(subsets, edge[i].src);
int subset2 = find(subsets, edge[i].dest);
// If two corners belong to same subset,
// then no point considering this edge
if (subset1 == subset2)
continue;
// Else contract the edge (or combine the
// corners of edge into one vertex)
else
{
printf("Contracting edge %d-%d\n",
edge[i].src, edge[i].dest);
vertices--;
Union(subsets, subset1, subset2);
}
}
// Now we have two vertices (or subsets) left in
// the contracted graph, so count the edges between
// two components and return the count.
int cutedges = 0;
for (int i = 0; i < E; i++)
{
int subset1 = find(subsets, edge[i].src);
int subset2 = find(subsets, edge[i].dest);
if (subset1 != subset2)
cutedges++;
}
return cutedges;
}
// A utility function to find set of an element i
// (uses path compression technique)
int find(struct subset subsets[], int i)
{
// find root and make root as parent of i
// (path compression)
if (subsets[i].parent != i)
subsets[i].parent =
find(subsets, subsets[i].parent);
return subsets[i].parent;
}
// A function that does union of two sets of x and y
// (uses union by rank)
void Union(struct subset subsets[], int x, int y)
{
int xroot = find(subsets, x);
int yroot = find(subsets, y);
// Attach smaller rank tree under root of high
// rank tree (Union by Rank)
if (subsets[xroot].rank < subsets[yroot].rank)
subsets[xroot].parent = yroot;
else if (subsets[xroot].rank > subsets[yroot].rank)
subsets[yroot].parent = xroot;
// If ranks are same, then make one as root and
// increment its rank by one
else
{
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
// Creates a graph with V vertices and E edges
struct Graph* createGraph(int V, int E)
{
Graph* graph = new Graph;
graph->V = V;
graph->E = E;
graph->edge = new Edge[E];
return graph;
}
// Driver program to test above functions
int main()
{
/* Let us create following unweighted graph
* 0------1
| \ |
| \ |
| \|
| 2------3 */
int V = 4; // Number of vertices in graph
int E = 5; // Number of edges in graph
struct Graph* graph = createGraph(V, E);
// add edge 0-1
graph->edge[0].src = 0;
graph->edge[0].dest = 1;
// add edge 0-2
graph->edge[1].src = 0;
graph->edge[1].dest = 2;
// add edge 0-3
graph->edge[2].src = 0;
graph->edge[2].dest = 3;
// add edge 1-3
graph->edge[3].src = 1;
graph->edge[3].dest = 3;
// add edge 2-3
graph->edge[4].src = 2;
graph->edge[4].dest = 3;
// Use a different seed value for every run.
srand(time(NULL));
printf("\nCut found by Karger's randomized algo is %d\n",
kargerMinCut(graph));
return 0;
}
|
code/randomized_algorithms/src/kth_smallest_element_algorithm/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/randomized_algorithms/src/kth_smallest_element_algorithm/kth_smallest_element.java | import java.util.*;
class Kth
{
class MinHeap
{
int[] harr;
int capacity;
int heap_size;
int parent(int i) { return (i - 1) / 2; }
int left(int i) { return ((2 * i )+ 1); }
int right(int i) { return ((2 * i) + 2); }
int getMin() { return harr[0]; }
void replaceMax(int x)
{
this.harr[0] = x;
minHeapify(0);
}
MinHeap(int a[], int size)
{
heap_size = size;
harr = a;
int i = (heap_size - 1) / 2;
while (i >= 0)
{
minHeapify(i);
i--;
}
}
int extractMin()
{
if (heap_size == 0)
return Integer.MAX_VALUE;
int root = harr[0];
if (heap_size > 1)
{
harr[0] = harr[heap_size - 1];
minHeapify(0);
}
heap_size--;
return root;
}
void minHeapify(int i)
{
int l = left(i);
int r = right(i);
int smallest = i;
if (l < heap_size && harr[l] < harr[i])
smallest = l;
if (r < heap_size && harr[r] < harr[smallest])
smallest = r;
if (smallest != i)
{
int t = harr[i];
harr[i] = harr[smallest];
harr[smallest] = t;
minHeapify(smallest);
}
}
};
int kthSmallest(int arr[], int n, int k)
{
MinHeap mh = new MinHeap(arr, n);
for (int i = 0; i < k - 1; i++)
mh.extractMin();
return mh.getMin();
}
public static void main(String[] args)
{
int arr[] = { 12, 3, 5, 7, 19 };
int n = arr.length, k = 2;
Kth kth = new Kth();
System.out.print("K'th smallest element is " +
kth.kthSmallest(arr, n, k));
}
}
|
code/randomized_algorithms/src/kth_smallest_element_algorithm/kth_smallest_element_algorithm.c | #include <stdio.h>
void swap(int *a , int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int find_element(int arr[],int n,int k)
{
for(int i=0; i<n-1; i++)
{
for(int j=i; j<n-1; j++)
{
if(arr[j]>arr[j+1])
{
swap(&arr[j],&arr[j+1]);
}
}
}
return a[k-1];
}
int main()
{
int n;
printf("Enter number of elements : ");
scanf("%d",&n);
int arr[n];
printf("Enter Elements : \n");
for (int i = 0; i < n; i++)
{
scanf("%d",&arr[i]);
}
int k;
printf("Enter k (nth smallest element to find) : ");
scanf("%d",&k);
printf("kth smallest element is %d\n",find_element(arr,n,k));
return 0;
}
|
code/randomized_algorithms/src/kth_smallest_element_algorithm/kth_smallest_element_algorithm.cpp | #include <iostream>
#include <climits>
#include <cstdlib>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
int randomPartition(int arr[], int l, int r);
// QuickSort based method. ASSUMPTION: ELEMENTS IN ARR[] ARE DISTINCT
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)
{
// Partition the array around a random element and
// get position of pivot element in sorted array
int pos = randomPartition(arr, l, r);
// If position is same as k
if (pos - l == k - 1)
return arr[pos];
if (pos - l > k - 1) // If position is more, recur for left subarray
return kthSmallest(arr, l, pos - 1, k);
// Else recur for right subarray
return kthSmallest(arr, pos + 1, r, k - pos + l - 1);
}
return INT_MAX;
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
// Standard partition process of QuickSort(). It considers the last
// element as pivot and moves all smaller element to left of it and
// greater elements to right. This function is used by randomPartition()
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;
}
// Picks a random pivot element between l and r and partitions
// arr[l..r] arount the randomly picked element using partition()
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 main()
{
int n;
int k;
int arr[1000000];
cout << "Enter the no. of elements in array" << endl;
cin >> n;
cout << "Enter the elements of the array seprated by single space" << endl;
for (int x = 0; x < n; x++)
cin >> arr[x];
cout << "Enter k (nth smallest element to be find)" << endl;
cin >> k;
cout << endl;
cout << "kth smallest element is " << kthSmallest(arr, 0, n - 1, k);
cout << endl;
return 0;
}
|
code/randomized_algorithms/src/random_from_stream/random_number_selection_from_a_stream.cpp | // Randomly select a number from stream of numbers.
// A function to randomly select a item from stream[0], stream[1], .. stream[i-1]
#include <random>
#include <iostream>
using namespace std;
int selectRandom(int x)
{
static int res; // The resultant random number
static int count = 0; //Count of numbers visited so far in stream
count++; // increment count of numbers seen so far
// If this is the first element from stream, return it
if (count == 1)
res = x;
else
{
// Generate a random number from 0 to count - 1
int i = rand() % count;
// Replace the prev random number with new number with 1/count probability
if (i == count - 1)
res = x;
}
return res;
}
int main()
{
int n;
cin >> n;
int stream[n];
for (int i = 0; i < n; i++)
cin >> stream[i];
// Use a different seed value for every run.
srand(time(NULL));
for (int i = 0; i < n; ++i)
printf("Random number from first %d numbers is %d \n",
i + 1, selectRandom(stream[i]));
return 0;
}
|
code/randomized_algorithms/src/random_node_linkedlist/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/randomized_algorithms/src/randomized_quick_sort/randomized_quicksort.c | /*
* C Program to Implement Quick Sort Using Randomization
*/
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
void random_shuffle(int arr[])
{
srand(time(NULL));
int i, j, temp;
for (i = MAX - 1; i > 0; i--)
{
j = rand()%(i + 1);
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int partion(int arr[], int p, int r)
{
int pivotIndex = p + rand()%(r - p + 1); //generates a random number as a pivot
int pivot;
int i = p - 1;
int j;
pivot = arr[pivotIndex];
swap(&arr[pivotIndex], &arr[r]);
for (j = p; j < r; j++)
{
if (arr[j] < pivot)
{
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i+1], &arr[r]);
return i + 1;
}
void quick_sort(int arr[], int p, int q)
{
int j;
if (p < q)
{
j = partion(arr, p, q);
quick_sort(arr, p, j-1);
quick_sort(arr, j+1, q);
}
}
int main()
{
int i;
int arr[MAX];
for (i = 0; i < MAX; i++)
arr[i] = i;
random_shuffle(arr); //To randomize the array
quick_sort(arr, 0, MAX-1); //function to sort the elements of array
for (i = 0; i < MAX; i++)
printf("%d \n", arr[i]);
return 0;
}
|
code/randomized_algorithms/src/randomized_quick_sort/randomized_quicksort.cpp | // implementation of quicksort using randomization
// by shobhit(dragon540)
#include <algorithm>
#include <ctime>
#include <iostream>
#include <vector>
void quicksort(std::vector<int> &vect, int low, int high);
int part(std::vector<int> &vect, int low, int high);
int main()
{
srand(time(NULL));
std::vector<int> val = {-25, 119, 32, 54, 623, 20, -2, -4, 8, 11};
// sorts the array in increasing order
quicksort(val, 0, 10);
for (int i = 0; i < 10; i++)
std::cout << val[i] << " ";
std::cout << '\n';
return 0;
}
void quicksort(std::vector<int> &vect, int low, int high)
{
if (low < high)
{
int pi = part(vect, low, high);
quicksort(vect, low, pi - 1);
quicksort(vect, pi + 1, high);
}
}
// sort a sub array partially in increasing order
int part(std::vector<int> &vect, int low, int high)
{
int pivotIndex = low + (rand() % (high - low + 1));
int pivot = vect[pivotIndex];
int l = low - 1;
std::swap(vect[pivotIndex], vect[high]);
for (int i = low; i < high; ++i)
if (vect[i] < pivot)
{
++l;
std::swap(vect[l], vect[i]);
}
std::swap(vect[l + 1], vect[high]);
return l + 1;
}
|
code/randomized_algorithms/src/reservoir_sampling/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/randomized_algorithms/src/reservoir_sampling/reservoir_sampling.cpp | // An efficient program to randomly select k items from a stream of n items
// Part of Cosmos by OpenGenus Foundation
#include <iostream>
using namespace std;
void printArray(int stream[], int n)
{
for (int i = 0; i < n; i++)
printf("%d ", stream[i]);
printf("\n");
}
// A function to randomly select k items from stream[0..n-1].
void selectKItems(int stream[], int n, int k)
{
int i; // index for elements in stream[]
// reservoir[] is the output array. Initialize it with
// first k elements from stream[]
int reservoir[k];
for (i = 0; i < k; i++)
reservoir[i] = stream[i];
// Use a different seed value so that we don't get
// same result each time we run this program
srand(time(NULL));
// Iterate from the (k+1)th element to nth element
for (; i < n; i++)
{
// Pick a random index from 0 to i.
int j = rand() % (i + 1);
// If the randomly picked index is smaller than k, then replace
// the element present at the index with new element from stream
if (j < k)
reservoir[j] = stream[i];
}
printf("Following are k randomly selected items \n");
printArray(reservoir, k);
}
// Driver program to test above function.
int main()
{
int n;
cin >> n;
int stream[n];
for (int i = 0; i < n; i++)
cin >> stream[i];
int k;
cin >> k;
selectKItems(stream, n, k);
return 0;
}
|
code/randomized_algorithms/src/reservoir_sampling/reservoir_sampling.rs | extern crate rand;
use rand::Rng;
use std::io;
fn select_random_k(arr: &Vec<i64>, k: u64) -> Vec<i64> {
let mut reservoir: Vec<i64> = vec![];
// using variable length instead of k handles the case of when k > arr.len()
let length: u64;
if (arr.len() as u64) < k {
length = arr.len() as u64;
} else {
length = k;
}
for i in 0..length {
let val = &arr[i as usize];
reservoir.push(*val);
}
let mut rng = rand::thread_rng();
for i in length..(arr.len() as u64) {
let r_num = rng.gen::<u64>() % (i as u64 + 1);
if r_num < length {
reservoir[r_num as usize] = arr[i as usize];
}
}
return reservoir;
}
fn main() {
let mut num_string = String::new();
// Reads space seperated list of n numbers
io::stdin().read_line(&mut num_string).expect("Failed to read the numbers");
let mut num_arr: Vec<i64> = vec![];
for num in num_string.split(" ") {
num_arr.push(num.trim().parse().expect("Not a number"));
}
let mut k_string = String::new();
// Reads k
io::stdin().read_line(&mut k_string).expect("Failed to read value of k");
let k: u64 = k_string.trim().parse().expect("Not a number");
println!("{:?}", select_random_k(&num_arr, k));
} |
code/randomized_algorithms/src/shuffle_an_array/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/randomized_algorithms/src/shuffle_an_array/shuffle_an_array.cpp | #include <array>
#include <iostream>
#include <iterator>
#include <random>
// Part of Cosmos by OpenGenus Foundation
template<class It, class RNG>
void shuffle_an_array(It first, It last, RNG &&rng)
{
std::uniform_int_distribution<> dist;
using ptype = std::uniform_int_distribution<>::param_type;
using std::swap;
for (; first != last; ++first)
swap(*first, *(first + dist(rng, ptype(0, last - first - 1))));
}
int main()
{
std::array<int, 10> values{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
std::minstd_rand rng(std::random_device{} ());
shuffle_an_array(values.begin(), values.end(), rng);
for (size_t i = 0; i < values.size(); ++i)
std::cout << (i > 0 ? ", " : "") << values[i];
std::cout << std::endl;
}
|
code/randomized_algorithms/src/shuffle_an_array/shuffle_an_array.java | // Part of Cosmos by OpenGenus Foundation
import java.util.Random;
import java.util.Arrays;
public class Shuffle_An_Array
{
static void randomizing(int array[], int n)
{
Random r = new Random();
for(int i = n-1;i>0;i--)
{
int j = r.nextInt(i);
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
System.out.println(Arrays.toString(array));
}
public static void main(String[]args)
{
int[] A = {1,2,3,4,5,6,7,8};
int n = A.length;
randomizing(A,n);
}
}
|
code/randomized_algorithms/src/shuffle_an_array/shuffle_an_array.js | // Part of Cosmos by OpenGenus Foundation
// This is a JavaScript implementation of Fisher-Yates shuffle based on
// [lodash/shuffle.js](https://github.com/lodash/lodash/blob/master/shuffle.js).
// This use `crypto` module if possible to provide stronger pseudo randomness.
const provideRandomSeed = (function() {
if (require && require.resolve && require.resolve("crypto")) {
const crypto = require("crypto");
return function() {
return crypto.randomBytes(1)[0] / 255;
};
} else {
return Math.random;
}
})();
/**
* Creates an array of shuffled values.
*
* @param {Array} array The array to shuffle.
* @returns {Array} Returns the new shuffled array.
* @example
*
* shuffle([1, 2, 3, 4])
* // => [3, 1, 4, 2]
*/
module.exports = function shuffle(array) {
const length = array == null ? 0 : array.length;
if (!length) {
return [];
}
let index = -1;
const lastIndex = length - 1;
const result = Array.from(array);
while (++index < length) {
const rand =
index + Math.floor(provideRandomSeed() * (lastIndex - index + 1));
const value = result[rand];
result[rand] = result[index];
result[index] = value;
}
return result;
};
|
code/randomized_algorithms/src/shuffle_an_array/shuffle_an_array.php | <?php
# Part of Cosmos by OpenGenus Foundation
trait ArrayRandomize
{
/**
* Shuffle a given array
*
* @param array $entries
* @return array
*/
public function shuffle(array $entries) : array
{
$length = count($entries);
for ($i = ($length - 1); $i >= 0; $i--) {
$randomIx = rand(0, $i);
$tmpEntry = $entries[$i];
$entries[$i] = $entries[$randomIx];
$entries[$randomIx] = $tmpEntry;
}
return $entries;
}
/**
* Shuffle a given assoc array
*
* @param array $entries
* @return array
*/
public function shuffleAssoc(array $entries) : array
{
$mixedKeys = $this->shuffle(array_keys($entries));
$mixedEntries = [];
foreach ($mixedKeys as $key) {
$mixedEntries[$key] = $entries[$key];
}
return $mixedEntries;
}
} |
code/randomized_algorithms/src/shuffle_an_array/shuffle_an_array.py | # Python Program to shuffle a given array
import random
import time
# Part of Cosmos by OpenGenus Foundation
# A function to generate a random permutation of arr[]
def randomize(arr):
random.seed(time.time()) # seed the random generator
# Start from the last element and swap one by one. We don't
# need to run for the first element that's why i > 0
for i in range(len(arr) - 1, 0, -1):
# Pick a random index from 0 to i
j = random.randint(0, i)
# Swap arr[i] with the element at random index
arr[i], arr[j] = arr[j], arr[i]
return arr
|
code/randomized_algorithms/src/shuffle_an_array/shuffle_an_array.rb | # Implementation of the algo
# Stdlib has #shuffle, use that instead
def randomize(arr, n)
n -= 1
n.downto(1).each do |i|
j = rand(i + 1)
arr[i], arr[j] = arr[j], arr[i]
end
arr
end
p randomize([1, 2, 3], 3)
|
code/randomized_algorithms/src/shuffle_an_array/shuffle_an_array.rs | extern crate rand;
use rand::Rng;
fn swap(arr: &mut Vec<i64>, i: usize) {
let a = &arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = *a;
}
fn randomize(arr: &Vec<i64>) -> Vec<i64> {
let mut rng = rand::thread_rng();
let mut temp = arr.clone();
for i in 0..arr.len() - 1 {
let random_num = rng.gen::<u8>() % 2;
if random_num == 1 {
swap(&mut temp, i);
}
}
return temp;
}
fn main() {
println!("{:?}", randomize(&vec![1, 2, 3, 4, 5]));
} |
code/randomized_algorithms/src/shuffle_an_array/shuffle_library.rb | a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a.shuffle
|
code/randomized_algorithms/test/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/search/src/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/search/src/binary_search/BinarySearch.asm | ; Author: SYEED MOHD AMEEN
; Email: [email protected]
;----------------------------------------------------------------;
; Binary Searching Subroutine ;
;----------------------------------------------------------------;
;----------------------------------------------------------------;
; FUNCTION PARAMETERS ;
;----------------------------------------------------------------;
; 1. push KEY element ;
; 2. push no. of element in Array ;
; 3. push base address of Array ;
;----------------------------------------------------------------;
BINSEARCH:
POP AX ;RETURN ADDRESS OF SUBROUTINE
POP SI ;BASE ADDRESS OF ARRAY (DATA STRUCTURE)
POP CX ;COUNTER REGISTER
POP DX ;KEY ELEMENT
PUSH AX ;RETURN ADDRESS OF SUBROUTINE
TEMP_LOW: EQU 0X1000
TEMP_HIGH: EQU 0X1002
TEMP_COUNTER: EQU 0X1004
TEMP_MID: EQU 0X1006
MOV [TEMP_LOW],0000
MOV [TEMP_HIGH],CX
REPEAT_BINSEARCH:
PUSH [TEMP_LOW] ;PUSH LOW AND HIGH INDEX TO CALCULATE MID POSITION
PUSH [TEMP_HIGH]
CALL MID_BINSEARCH
POP [TEMP_MID]
MOV BX,[TEMP_MID] ;BX = (MID INDEX POITNTER) FOR INDEX ADDRESSING
CMP [SI+BX],DX ;A[MID] == KEY (SUCESSFUL) ELSE (UNSUCESSFUL)
JNE NOFOUND_BINSEARCH
POP AX
ADD [TEMP_MID],SI ;IF SUCESSFUL RETURN ADDRESS OF KEY ELEMENT
PUSH [TEMP_MID]
PUSH AX
RET
NOFOUND_BINSEARCH:
CMP DX,[SI+BX]
JNC GREATER_BINSEARCH ;JUMP (KEY > A[MID]) UPDATE LOW INDEX POINTER
MOV [TEMP_HIGH],[TEMP_MID] ;HIGH = MID - 1
DEC [TEMP_HIGH]
JMP REPEAT_BINSEARCH
GREATER_BINSEARCH:
MOV [TEMP_LOW],[TEMP_MID] ;LOW = MID + 1
INC [TEMP_LOW]
JMP REPEAT_BINSEARCH
;-----------------------------------------------;
; MID CALCULATION SUBROUTINE ;
;-----------------------------------------------;
MID_BINSEARCH:
POP AX
POP BX ;DIVISOR
POP CX ;DIVIDEND
PUSH AX
ADD BX,CX ;ADD DIVISIOR AND DIVIDEND
MOV AX,BX
IDIV AX,+2 ;IMMEDATE DIVIDE BY 2
POP CX
PUSH AX ;PUSH MID INDEX
PUSH CX
RET
|
code/search/src/binary_search/README.md | # Binary search
The binary search algorithm is used for finding an element in a sorted array. It has the average performance O(log n).
## Procedure
1. Find middle element of the array.
2. Compare the value of the middle element with the target value.
3. If they match, it is returned.
4. If the value is less or greater than the target, the search continues in the lower or upper half of the array.
5. The same procedure as in step 2-4 continues, but with a smaller part of the array. This continues until the target element is found or until there are no elements left.
## Pseudocode (Recursive approach)
```
// initially called with low = 0, high = N-1
BinarySearch(A[0..N-1], value, low, high) {
// invariants: value > A[i] for all i < low
value < A[i] for all i > high
if (high < low)
return not_found // value would be inserted at index "low"
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid
}
```
Collaborative effort by [OpenGenus](https://github.com/opengenus)
|
code/search/src/binary_search/binary_search.c | #include <stdio.h>
/*
* Part of Cosmos by OpenGenus Foundation
*/
// A recursive binary search function. It returns
// location of x in given array arr[l..r] is present,
// otherwise -1
int recursiveBinarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l)/2;
// If the element is present at the middle
// itself
if (arr[mid] == x)
return mid;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr[mid] > x)
return recursiveBinarySearch(arr, l, mid-1, x);
// Else the element can only be present
// in right subarray
return recursiveBinarySearch(arr, mid+1, r, x);
}
// We reach here when element is not
// present in array
return -1;
}
// A iterative binary search function. It returns
// location of x in given array arr[l..r] is present,
// otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
while (l <= r)
{
int mid = l + (r-l)/2;
// If the element is present at the middle
// itself
if (arr[mid] == x)
return mid;
// If element is greater than mid, then
// it can only be present in right subarray
if (arr[mid] < x)
l = mid + 1;
// Else the element can only be present
// in right subarray
else
r = mid - 1;
}
// We reach here when element is not
// present in array
return -1;
}
int main(void)
{
int arr[] = {1, 2, 3, 5};
int size = sizeof(arr)/ sizeof(arr[0]);
int find = 3;
//Printing the position of element using recursive binary search
printf("Position of %d is %d\n", find, recursiveBinarySearch(arr, 0, size-1, find));
//Printing the position of element using iterative binary search
printf("Position of %d is %d\n", find, binarySearch(arr, 0, size-1, find));
return 0;
}
|
code/search/src/binary_search/binary_search.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*
* binary search synopsis
*
* warning: in order to follow the convention of STL, the interface is [begin, end) !!!
*
* namespace binary_search_impl
* {
* struct binary_search_tag {};
* struct recursive_binary_search_tag :public binary_search_tag {};
* struct iterative_binary_search_tag :public binary_search_tag {};
*
* // [first, last]
* template<typename _Random_Access_Iter, typename _Comp,
* typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type,
* typename _Difference
* = typename std::iterator_traits<_Random_Access_Iter>::difference_type>
* std::pair<_Random_Access_Iter, bool>
* binarySearchImpl(_Random_Access_Iter first,
* _Random_Access_Iter last,
* _Tp const &find,
* _Comp comp,
* std::random_access_iterator_tag,
* recursive_binary_search_tag);
*
* // [first, last]
* template<typename _Random_Access_Iter, typename _Comp,
* typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type,
* typename _Difference
* = typename std::iterator_traits<_Random_Access_Iter>::difference_type>
* std::pair<_Random_Access_Iter, bool>
* binarySearchImpl(_Random_Access_Iter first,
* _Random_Access_Iter last,
* _Tp const &find,
* _Comp comp,
* std::random_access_iterator_tag,
* iterative_binary_search_tag);
* } // binary_search_impl
*
* // [begin, end)
* template<typename _Random_Access_Iter,
* typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type,
* typename iterator_category
* = typename std::iterator_traits<_Random_Access_Iter>::iterator_category,
* typename _Comp>
* _Random_Access_Iter
* binarySearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find, _Comp comp);
*
* // [begin, end)
* template<typename _Random_Access_Iter,
* typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type>
* _Random_Access_Iter
* binarySearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find);
*/
#include <functional>
namespace binary_search_impl
{
struct binary_search_tag {};
struct recursive_binary_search_tag : public binary_search_tag {};
struct iterative_binary_search_tag : public binary_search_tag {};
// [first, last]
template<typename _Random_Access_Iter, typename _Comp,
typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type,
typename _Difference
= typename std::iterator_traits<_Random_Access_Iter>::difference_type>
std::pair<_Random_Access_Iter, bool>
binarySearchImpl(_Random_Access_Iter first,
_Random_Access_Iter last,
_Tp const &find,
_Comp comp,
std::random_access_iterator_tag,
recursive_binary_search_tag)
{
// verifying the base condition in order to proceed with the binary search
if (first <= last)
{
// calculating the middle most term
_Random_Access_Iter mid = first + (last - first) / 2;
// checking whether the term to be searched lies in the first half or second half of the series
if (comp(*mid, find))
return binarySearchImpl(mid + 1,
last,
find,
comp,
std::random_access_iterator_tag(),
recursive_binary_search_tag());
else if (comp(find, *mid))
return binarySearchImpl(first,
mid - 1,
find,
comp,
std::random_access_iterator_tag(),
iterative_binary_search_tag());
else
return std::make_pair(mid, true);
}
return std::make_pair(last, false);
}
// [first, last]
template<typename _Random_Access_Iter, typename _Comp,
typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type,
typename _Difference
= typename std::iterator_traits<_Random_Access_Iter>::difference_type>
std::pair<_Random_Access_Iter, bool>
binarySearchImpl(_Random_Access_Iter first,
_Random_Access_Iter last,
_Tp const &find,
_Comp comp,
std::random_access_iterator_tag,
iterative_binary_search_tag)
{
while (first <= last)
{
_Random_Access_Iter mid = first + (last - first) / 2;
if (comp(*mid, find))
first = mid + 1;
else if (comp(find, *mid))
last = mid - 1;
else
return std::make_pair(mid, true);
}
return std::make_pair(last, false);
}
} // binary_search_impl
// [begin, end)
template<typename _Random_Access_Iter,
typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type,
typename _Comp>
_Random_Access_Iter
binarySearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find, _Comp comp)
{
if (begin >= end)
return end;
auto category = typename std::iterator_traits<_Random_Access_Iter>::iterator_category();
auto tag = binary_search_impl::recursive_binary_search_tag();
auto res = binary_search_impl::binarySearchImpl(begin, end - 1, find, comp, category, tag);
if (res.second)
return res.first;
else
return end;
}
// [begin, end)
template<typename _Random_Access_Iter,
typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type>
_Random_Access_Iter
binarySearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find)
{
return binarySearch(begin, end, find, std::less<_Tp>());
}
|
code/search/src/binary_search/binary_search.cs | using System;
namespace binary_search
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[10]
{1, 10, 14, 26, 39, 44, 68, 77, 81, 92};
Console.WriteLine("Array: ");
for(int i=0; i<10; i++)
{
Console.Write(arr[i] + " ");
}
Console.WriteLine("\nInput -1 to terminate program");
int find = 0;
int res;
while(find != -1)
{
Console.Write("Input number to search: ");
find = Int32.Parse(Console.ReadLine());
if ((res = binarySearch(arr, find)) != -1)
Console.WriteLine($" + Found number {find} at index {res}");
else
Console.WriteLine(" - Number not found!");
}
}
static int binarySearch(int[] arr, int key)
{
int low = 0;
int high = arr.Length - 1;
while (low <= high)
{
int midIndex = low + (high - low) / 2;
if (arr[midIndex] == key)
return midIndex;
else if (key > arr[midIndex])
low = midIndex + 1;
else
high = midIndex - 1;
}
return -1;
}
}
}
|
code/search/src/binary_search/binary_search.ex | defmodule Cosmos.Search.BinarySearch do
def binary_search(array, key) do
bs array, key, 0, length(array)
end
defp bs([], _, _, _), do: nil
defp bs([_], _, _, _), do: 0
defp bs(_, _, min, max) when max < min, do: nil
defp bs(array, key, min, max) do
mid = div min + max, 2
{_, val} = Enum.fetch array, mid
cond do
val > key -> bs array, key, min, mid - 1
val < key -> bs array, key, min + 1, max
true -> mid
end
end
end
|
code/search/src/binary_search/binary_search.go | package main
import "fmt"
import "sort"
// Part of Cosmos by OpenGenus Foundation
func binarySearch(data []int, value int) int {
startIndex := 0
endIndex := len(data) - 1
for startIndex <= endIndex {
midIndex := (startIndex + endIndex) / 2
mid := data[midIndex]
if mid < value {
endIndex = midIndex - 1
} else if mid > value {
startIndex = midIndex + 1
} else {
return midIndex
}
}
return -1
}
func buildInSearch(data []int, value int) int {
i := sort.Search(len(data), func(i int) bool { return data[i] >= value })
if i < len(data) && data[i] == value {
return i
}
return -1
}
func main() {
values := []int{1, 2, 3, 4, 5, 12, 35, 30, 46, 84}
fmt.Println("custom implementation")
fmt.Println(binarySearch(values, 5))
fmt.Println(binarySearch(values, 7))
fmt.Println("use build-in search function")
fmt.Println(buildInSearch(values, 5))
fmt.Println(buildInSearch(values, 13))
}
|
code/search/src/binary_search/binary_search.hs | {-
Part of Cosmos by OpenGenus Foundation
-}
binarySearch :: [Int] -> Int -> Int -> Int -> Int
binarySearch arr val low high
| high < low = -1
| arr!!mid < val = binarySearch arr val (mid+1) high
| arr!!mid > val = binarySearch arr val low (mid-1)
| otherwise = mid
where
mid = (low + high) `div` 2
main = do
let arr = [3,5,12,56,92,123,156,190,201,222]
let number = 12
putStrLn("Position of "
++ show(number)
++ " is "
++ show(binarySearch arr number 0 ((length arr) - 1)))
|
code/search/src/binary_search/binary_search.java | /*
* Part of Cosmos by OpenGenus Foundation
*/
class Search
{//Implementation of Binary Search in java
static int recursiveBinarySearch(int arr[], int l, int r, int x)
{//recursive function that returns the index of element x if it is present in arr[],else returns -1
if (r>=l)
{
int mid = l + (r - l)/2; //finding out the middle index
if (arr[mid] == x)
return mid; //If x is present at the middle
if (arr[mid] > x) //If x is smaller than the element at middle,then it might be present in the left of middle.
return recursiveBinarySearch(arr, l, mid-1, x);
return recursiveBinarySearch(arr, mid+1, r, x); //else the element can only be present in the right subarray
}
return -1; //-1 is returned if the element x is not present in the array
}
static int binarySearch(int arr[], int l, int r, int x)
{//Iterative implementation of Binary Search
while (l <= r) //the loop runs till the low index(l) is less than or equal to the high index(r)
{
int mid = l + (r-l)/2; //Calculating middle index
if (arr[mid] == x)
return mid; //if the element x is present on middle index
if (arr[mid] < x) //If x greater, ignore left half
l = mid + 1;
else
r = mid - 1; // If x is smaller, ignore right half
}
return -1; //if the element is not present in the array,-1 is returned
}
public static void main(String args[])
{
int arr[] = {1, 2, 3, 5};
int size = arr.length; //stores the length of arr[]
int find = 3; //Element to be searched
System.out.println("Position of "+find+" is "+recursiveBinarySearch(arr,0,size-1,find));
System.out.println("Position of "+find+" is "+binarySearch(arr,0,size-1,find));
}
}
|
code/search/src/binary_search/binary_search.js | // implementation by looping
function binarySearchLooping(array, key) {
let lo = 0,
hi = array.length - 1;
while (lo <= hi) {
let mid = Math.floor((lo + hi) / 2, 10);
let element = array[mid];
if (element < key) {
lo = mid + 1;
} else if (element > key) {
hi = mid - 1;
} else {
return mid;
}
}
return -1;
}
// implementation by recursion
/**
*
* @param {* number[]} arr - the sorted array to be searched in
* @param {* number} value - the value to be searched
* @param {* number} low - the start index of the search range
* @param {* number} high - the end index of the search range
*/
function binarySearchByRecursion(arr, value, low = 0, high = arr.length - 1) {
const mid = Math.floor((start + end) / 2);
if (end === start + 1 && arr[mid] !== value && arr[start] !== value) {
return -1;
}
if (arr[start] === value) {
return start;
} else if (arr[end] === value) {
return end;
} else if (arr[mid] === value) {
return mid;
} else {
return arr[mid] > value
? binarySearchByRecursion(arr, value, start, mid)
: binarySearchByRecursion(arr, value, mid, end);
}
}
|
code/search/src/binary_search/binary_search.kt | // Part of Cosmos by OpenGenus Foundation
fun <T : Comparable<T>> binarySearch(a: Array<T>, key: T): Int? {
var lowerBound = 0
var upperBound = a.size
while (lowerBound < upperBound) {
val middleIndex = lowerBound + (upperBound - lowerBound) / 2
when {
a[middleIndex] == key -> return middleIndex
a[middleIndex] < key -> lowerBound = middleIndex + 1
else -> upperBound = middleIndex
}
}
return null
}
fun main(args: Array<String>) {
val sample: Array<Int> = arrayOf(13, 17, 19, 23, 29, 31, 37, 41, 43)
val key = 23
val result = binarySearch(sample, key)
println(when (result) {
null -> "$key is not in $sample"
else -> "Position of $key is $result"
})
}
|
code/search/src/binary_search/binary_search.php | <?php
/**
* Part of Cosmos by OpenGenus Foundation
*
* @param array $array
* @param int $low
* @param int $high
* @param int $search
*
* @return int
*/
function binarySearch(array $array, $low, $high, $search)
{
if ($high >= $low) {
$middle = (int) ($low + ($high - $low) / 2);
if ($array[$middle] === $search) {
return $middle;
} else if ($array[$middle] > $search) {
return binarySearch($array, $low, $middle - 1, $search);
} else {
return binarySearch($array, $middle + 1, $high, $search);
}
}
return -1;
}
if (!isset($dontPrintBinarySearchTest)) {
echo sprintf(
"Position of %d is %d\n",
$search = 33, binarySearch($array = [7, 11, 13, 33, 66], 0, count($array) - 1, $search)
);
}
|
code/search/src/binary_search/binary_search.py | """
Part of Cosmos by OpenGenus Foundation
"""
def _binary_search_recursive_impl(arr, x, left, right):
if right > left:
mid = left + int((right - left) / 2)
if arr[mid] == x:
return mid
elif arr[mid] > x:
return _binary_search_recursive_impl(arr, x, left, mid - 1)
else:
return _binary_search_recursive_impl(arr, x, mid + 1, right)
else:
return left if left in range(0, len(arr)) and arr[left] == x else -1
def binary_search_recursive(arr, x):
return _binary_search_recursive_impl(arr, x, 0, len(arr))
def _binary_search_iterative_impl(arr, x, left, right):
while left < right:
mid = left + int((right - left) / 2)
if arr[mid] == x:
return mid
elif arr[mid] > x:
right = mid - 1
else:
left = mid + 1
return left if left in range(0, len(arr)) and arr[left] == x else -1
def binary_search_iterative(arr, x):
return _binary_search_iterative_impl(arr, x, 0, len(arr))
binary_search = binary_search_iterative
|
code/search/src/binary_search/binary_search.rb | # Part of Cosmos by OpenGenus Foundation
def binary_search(arr, l, r, x)
return -1 if x.nil?
if r >= l
mid = (l + r) / 2
if arr[mid] == x
mid
elsif arr[mid] > x
binary_search(arr, l, mid - 1, x)
else
binary_search(arr, mid + 1, r, x)
end
end
end
arr = [3, 5, 12, 56, 92, 123, 156, 190, 201, 222]
number = 12
puts "Position of #{number} is #{binary_search(arr, 0, arr.length - 1, number)}"
|
code/search/src/binary_search/binary_search.rkt | #lang racket
(define (binary-search val l)
(cond [(empty? l) false]
[(equal? val (first l)) true]
[else
(define midpoint (quotient (length l) 2))
(define value-at-midpoint (first (drop l midpoint)))
(if (>= val value-at-midpoint)
(binary-search val (drop l midpoint))
(binary-search val (take l midpoint)))]))
(define test-list (build-list 10 values))
(display "Searching for 4 should be #t: ")
(displayln (binary-search 4 test-list))
(display "Searching for 1 should be #t: ")
(displayln (binary-search 1 test-list))
(display "Searching for 8 should be #t: ")
(displayln (binary-search 8 test-list))
(display "Searching for 11 should be #f: ")
(displayln (binary-search 11 test-list)) |
code/search/src/binary_search/binary_search.rs | fn main() {
let nums = vec![1, 3, 5, 7, 9];
let find_me = 5;
let result = binary_search(&nums, find_me, 0, nums.len());
println!("Given Array: {:?}", nums);
match result {
Some(index) => println!("Searched for {} and found index {}.", find_me, index),
None => println!("Searched for {} but found no occurrence.", find_me),
}
}
fn binary_search(nums: &[i64], search_value: i64, left: usize, right: usize) -> Option<usize> {
let mut left: usize = left;
let mut right: usize = right;
while left <= right {
let middle = (left + right) / 2;
if middle == nums.len() {
break;
}
if nums[middle] == search_value {
return Some(middle);
} else if nums[middle] < search_value {
left = middle + 1;
} else if nums[middle] > search_value && middle != 0 {
right = middle - 1;
} else {
break;
}
}
None
}
|
code/search/src/binary_search/binary_search.scala | package opengenus.cosmos.sorting
import scala.annotation.tailrec
object BinarySearch {
trait SearchResult
case class Found(i: Int) extends SearchResult
case object NotFound extends SearchResult
def apply[T](element: T)(collection: List[T])(implicit ord: Ordering[T]): SearchResult = {
@tailrec
def binarySearchStep(start: Int, end: Int): SearchResult = {
val mid = start + (end - start) / 2
val midValue = collection(mid)
if(midValue == element) Found(mid)
else if(start > end) NotFound
else if(ord.gt(element, midValue)) binarySearchStep(mid+1, end)
else binarySearchStep(start, mid-1)
}
binarySearchStep(0, collection.size-1)
}
}
|
code/search/src/binary_search/binary_search.sh | #!/bin/bash
#read Limit
echo Enter array limit
read limit
#read Elements
echo Enter elements
n=1
while [ $n -le $limit ]
do
read num
eval arr$n=$num
n=`expr $n + 1`
done
#read Search Key Element
echo Enter key element
read key
low=1
high=$n
found=0
#Find middle element
#for(( low=0,found=0,high=$((n-1)) ; l<=u ; ))
while [ $found -eq 0 -a $high -gt $low ]
do
mid=`expr \( $low + $high \) / 2`
eval t=\$arr$mid
if [ $key -eq $t ] #Compare the value of the middle element with the target value. MATCH
then
found=1
elif [ $key -lt $t ] #Compare the value of the middle element with the target value. LESS
then
high=`expr $mid - 1`
else
low=`expr $mid + 1` #Compare the value of the middle element with the target value. GREATER
fi
done # Repeat
if [ $found -eq 0 ]
then
echo Unsuccessfull search
else
echo Successfull search
fi
|
code/search/src/binary_search/binary_search.swift | // binary_search.swift
// Created by iraniya on 10/4/17.
// Part of Cosmos by OpenGenus Foundation
/**
Binary Search
Recursively splits the array in half until the value is found.
If there is more than one occurrence of the search key in the array, then
there is no guarantee which one it finds.
Note: The array must be sorted!
**/
import Foundation
// The recursive version of binary search.
public func binarySearch<T: Comparable>(_ a: [T], key: T, range: Range<Int>) -> Int? {
if range.lowerBound >= range.upperBound {
return nil
} else {
let midIndex = range.lowerBound + (range.upperBound - range.lowerBound) / 2
if a[midIndex] > key {
return binarySearch(a, key: key, range: range.lowerBound ..< midIndex)
} else if a[midIndex] < key {
return binarySearch(a, key: key, range: midIndex + 1 ..< range.upperBound)
} else {
return midIndex
}
}
}
/**
The iterative version of binary search.
Notice how similar these functions are. The difference is that this one
uses a while loop, while the other calls itself recursively.
**/
public func binarySearch<T: Comparable>(_ a: [T], key: T) -> Int? {
var lowerBound = 0
var upperBound = a.count
while lowerBound < upperBound {
let midIndex = lowerBound + (upperBound - lowerBound) / 2
if a[midIndex] == key {
return midIndex
} else if a[midIndex] < key {
lowerBound = midIndex + 1
} else {
upperBound = midIndex
}
}
return nil
}
let numbers = [1,2,3,4,5]
let key = 5
var find = binarySearch(numbers, key: key, range: 0 ..< numbers.count) // gives 13
print("Position of \(key) is \(find)")
//printf("Position of %d is %d\n", find, binarySearch(arr, 0, size-1, find));
|
code/search/src/binary_search/binary_search_2.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <vector>
#include <cstdlib>
#include <iostream>
#include <algorithm>
/* Utility functions */
void fill(std::vector<int> &v)
{
for (auto& elem : v)
elem = rand() % 100;
}
void printArr(std::vector<int> &v)
{
for (const auto& elem : v)
std::cout << elem << " ";
std::cout << "\n";
}
/* Binary search with fewer comparisons */
int binarySearch(std::vector<int> &v, int key)
{
int l = 0, r = v.size();
while (r - l > 1)
{
int m = l + (r - l) / 2;
if (v[m] > key)
r = m;
else
l = m;
}
return (v[l] == key) ? l : -1;
}
/* Driver program */
int main()
{
int size;
std::cout << "Enter the array size:";
std::cin >> size;
std::vector<int> v(size);
fill(v);
std::cout << "Array (sorted) : ";
sort(v.begin(), v.end());
printArr(v);
int key;
std::cout << "Search for (input search key) : ";
std::cin >> key;
std::cout << "Found " << key << " at index " << binarySearch(v, key) << "\n";
}
|
code/search/src/binary_search/binarysearchrecursion.cpp | #include <iostream>
using namespace std;
int BinarySearch(int arr[], int start, int end, int item){
if(start > end)
return -1;
int mid = start + (end-start)/2;
if (arr[mid] == item)
return mid;
else if(arr[mid] < item)
BinarySearch(arr, mid+1, end, item);
else
BinarySearch(arr, start, mid-1, item);
}
int main(){
int arr[5] = {2,4,5,6,8};
int n = 5;
int item = 6;
int index = BinarySearch(arr, 0, n-1, item);
if(index>=0)
cout << "Element Found at index - " << index;
else
cout << "Element Not Found!!";
return 0;
}
|
code/search/src/exponential_search/README.md | # cosmos
# Exponential Search
Exponential search involves two steps:
1) Find range where element is present
2) Do Binary Search in above found range.
# How to find the range where element may be present?
The idea is to start with subarray size 1 compare its last element with x, then try size 2, then 4 and so on until last element of a subarray is not greater.
Once we find an index i (after repeated doubling of i), we know that the element must be present between i/2 and i (Why i/2? because we could not find a greater value in previous iteration).
# Applications of Exponential Search:
Exponential Binary Search is particularly useful for unbounded searches, where size of array is infinite. Please refer Unbounded Binary Search for an example.
It works better than Binary Search for bounded arrays also when the element to be searched is closer to the first element.
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/search/src/exponential_search/exponential_search.c | #include <stdio.h>
int
min(int a, int b)
{
return (a < b ? a : b);
}
int
binarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return (mid);
if (arr[mid] > x)
return (binarySearch(arr, l, mid - 1, x));
return (binarySearch(arr, mid + 1, r, x));
}
return (-1);
}
int
exponentialSearch(int arr[], int n, int x)
{
if (arr[0] == x)
return (0);
int i = 1;
while (i < n && arr[i] <= x)
i = i*2;
return (binarySearch(arr, i / 2, min(i, n), x));
}
int
main()
{
int n;
printf("Enter size of Array \n");
scanf("%d", &n);
int arr[n], i;
printf("Enter %d integers in ascending order \n", n);
for(i = 0; i < n; i++)
scanf("%d", &arr[i]);
int x;
printf("Enter integer to be searched \n");
scanf("%d", &x);
int result = exponentialSearch(arr, n, x);
if (result == -1)
printf("%d is not present in array \n", x);
else
printf("%d is present at index %d \n", x, result);
return (0);
} |
code/search/src/exponential_search/exponential_search.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*
* jump search synopsis
*
* warning: in order to follow the convention of STL, the interface is [begin, end) !!!
*
* namespace exponenial_search_impl
* {
* template<typename _Random_Access_Iter, typename _Comp,
* typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type,
* typename _Difference = typename std::iterator_traits<_Random_Access_Iter>::difference_type>
* std::pair<_Random_Access_Iter, bool>
* binarySearchImpl(_Random_Access_Iter first,
* _Random_Access_Iter last,
* _Tp const &find,
* _Comp comp,
* std::random_access_iterator_tag);
*
* template<typename _Random_Access_Iter,
* typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type,
* typename _Compare>
* _Random_Access_Iter
* exponentialSearchImpl(_Random_Access_Iter begin,
* _Random_Access_Iter end,
* _Tp const &find,
* _Compare comp,
* std::random_access_iterator_tag);
* } // exponenial_search_impl
*
* template<typename _Random_Access_Iter,
* typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type,
* typename _Compare>
* _Random_Access_Iter
* exponentialSearch(_Random_Access_Iter begin,
* _Random_Access_Iter end,
* _Tp const &find,
* _Compare comp);
*
* template<typename _Random_Access_Iter,
* typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type>
* _Random_Access_Iter
* exponentialSearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find);
*/
#include <functional>
namespace exponenial_search_impl
{
template<typename _Random_Access_Iter, typename _Comp,
typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type,
typename _Difference = typename std::iterator_traits<_Random_Access_Iter>::difference_type>
std::pair<_Random_Access_Iter, bool>
binarySearchImpl(_Random_Access_Iter first,
_Random_Access_Iter last,
_Tp const &find,
_Comp comp,
std::random_access_iterator_tag)
{
while (first <= last)
{
auto mid = first + (last - first) / 2;
if (comp(*mid, find))
first = mid + 1;
else if (comp(find, *mid))
last = mid - 1;
else
return std::make_pair(mid, true);
}
return std::make_pair(last, false);
}
template<typename _Random_Access_Iter,
typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type,
typename _Compare>
_Random_Access_Iter
exponentialSearchImpl(_Random_Access_Iter begin,
_Random_Access_Iter end,
_Tp const &find,
_Compare comp,
std::random_access_iterator_tag)
{
if (begin != end)
{
if (!comp(*begin, find))
return (!comp(find, *begin)) ? begin : end;
auto blockBegin = begin;
auto offset = 1;
while (blockBegin < end && comp(*blockBegin, find))
{
std::advance(blockBegin, offset);
offset *= 2;
}
auto blockEnd = blockBegin < end ? blockBegin : end;
std::advance(blockBegin, -1 * (offset / 2));
auto res = binarySearchImpl(blockBegin,
blockEnd,
find,
comp,
std::random_access_iterator_tag());
if (res.second)
return res.first;
}
return end;
}
} // exponenial_search_impl
template<typename _Random_Access_Iter,
typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type,
typename _Compare>
_Random_Access_Iter
exponentialSearch(_Random_Access_Iter begin,
_Random_Access_Iter end,
_Tp const &find,
_Compare comp)
{
auto category = typename std::iterator_traits<_Random_Access_Iter>::iterator_category();
return exponenial_search_impl::exponentialSearchImpl(begin, end, find, comp, category);
}
template<typename _Random_Access_Iter,
typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type>
_Random_Access_Iter
exponentialSearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find)
{
return exponentialSearch(begin, end, find, std::less<_Tp>());
}
|
code/search/src/exponential_search/exponential_search.cs | // C# program to find an element x in a sorted array using Exponential search.
using System;
// Part of Cosmos by OpenGenus Foundation
class ExponentialSearch {
// Returns position of first ocurrence of x in array
static int exponentialSearch(int[] arr, int n, int x) {
// If x is present at firt location itself
if (arr[0] == x) {
return 0;
}
// Find range for binary search by
// repeated doubling
int i = 1;
while (i < n && arr[i] <= x) {
i = i * 2;
}
// Call binary search for the found range.
return Arrays.binarySearch(arr, i/2, Math.min(i, n), x);
}
// Driver method
public static void Main(String[] args)
{
int[] arr = {4, 91, 66, 89, 54, 2, 3};
int x = 66;
int result = exponentialSearch(arr, arr.length, x);
if( result < 0 ) {
Console.Write("Element is not present in array");
}
else {
Console.Write("Element is present at index " + result);
}
}
}
|
code/search/src/exponential_search/exponential_search.go | package main
import (
"fmt"
)
func binarySearch(data []int, left int, right int, value int) int {
if right >= left {
mid := left + (right-left)/2
if data[mid] == value {
return mid
}
if data[mid] > value {
return binarySearch(data, left, mid-1, value)
}
return binarySearch(data, mid+1, right, value)
}
return -1
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
// Part of Cosmos by OpenGenus Foundation
func exponentialSearch(data []int, n int, x int) int {
if data[0] == x {
return 0
}
i := 1
for i < n && data[i] <= x {
i = i * 2
}
return binarySearch(data, i/2, min(i, n), x)
}
func main() {
values := []int{1, 2, 3, 4, 5, 12, 30, 35, 46, 84}
fmt.Println(exponentialSearch(values, len(values)-1, 5))
fmt.Println(exponentialSearch(values, len(values)-1, 35))
fmt.Println(exponentialSearch(values, len(values)-1, 7))
}
|
code/search/src/exponential_search/exponential_search.java | // Java program to find an element x in a sorted array using Exponential search.
import java.util.Arrays;
// Part of Cosmos by OpenGenus Foundation
class ExponentialSearch {
// Returns position of first ocurrence of x in array
static int exponentialSearch(int arr[], int n, int x) {
// If x is present at firt location itself
if (arr[0] == x) {
return 0;
}
// Find range for binary search by
// repeated doubling
int i = 1;
while (i < n && arr[i] <= x) {
i = i * 2;
}
// Call binary search for the found range.
return Arrays.binarySearch(arr, i/2, Math.min(i, n), x);
}
// Driver method
public static void main(String args[])
{
int arr[] = {4, 91, 66, 89, 54, 2, 3};
int x = 66;
int result = exponentialSearch(arr, arr.length, x);
if( result < 0 ) {
System.out.println("Element is not present in array");
}
else {
System.out.println("Element is present at index " + result);
}
}
}
|
code/search/src/exponential_search/exponential_search.js | /* Part of Cosmos by OpenGenus Foundation */
/* Program to find an element in a sorted array using Exponential search. */
function binarySearch(arr, left, right, element) {
if (right >= left) {
const mid = left + Math.floor((right - left) / 2);
if (arr[mid] == element) {
return mid;
} else if (arr[mid] > element) {
return binarySearch(arr, left, mid - 1, element);
} else {
return binarySearch(arr, mid + 1, right, element);
}
}
return -1;
}
function exponentialSearch(arr, element) {
if (arr[0] == element) {
return 0;
}
let i = 1;
const arrLength = arr.length;
while (i < arrLength && arr[i] <= element) {
i *= 2;
}
return binarySearch(arr, i / 2, Math.min(i, arrLength), element);
}
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const element = 4;
const found = exponentialSearch(arr, element);
if (found == -1) {
console.log("Error | Not found");
} else {
console.log("Found | At position", found + 1);
}
|
code/search/src/exponential_search/exponential_search.php | <?php
$dontPrintBinarySearchTest = true;
require_once '../binary_search/binary_search.php';
/**
* Part of Cosmos by OpenGenus Foundation
*
* @param array $array
* @param int $search
*
* @return int
*/
function exponentialSearch(array $array, $search)
{
if (($count = count($array)) === 0) {
return -1;
}
$i = 1;
while ($i < $count && $array[$i] < $search) {
$i *= 2;
}
return binarySearch($array, $i / 2, min($i, $count), $search);
}
echo sprintf("Position of %d is %d\n", $search = 13, exponentialSearch($array = [7, 11, 13, 33, 66], $search));
|
code/search/src/exponential_search/exponential_search.py | """
Part of Cosmos by OpenGenus Foundation
"""
def _binary_search(arr, element, left, right):
if right > left:
mid = (left + right) >> 1
if arr[mid] == element:
return mid
elif arr[mid] > element:
return _binary_search(arr, element, left, mid - 1)
else:
return _binary_search(arr, element, mid + 1, right)
return left if left in range(0, len(arr)) and arr[left] == element else -1
def exponential_search(arr, element):
if len(arr) == 0:
return -1
if arr[0] == element:
return 0
i = 1
arrLength = len(arr)
while i < arrLength and arr[i] <= element:
i *= 2
return _binary_search(arr, element, i // 2, min(i, arrLength))
|
code/search/src/exponential_search/exponential_search.rb | def binary_search(arr, l, r, x)
return -1 if x.nil?
if r >= l
mid = (l + r) / 2
if arr[mid] == x
mid
elsif arr[mid] > x
binary_search(arr, l, mid - 1, x)
else
binary_search(arr, mid + 1, r, x)
end
end
end
def exponential_search(arr, element)
return 0 if arr[0] == element
i = 1
i *= 2 while i < arr.length && arr[i] <= element
binary_search arr, i / 2, [i, arr.length].min, element
end
puts exponential_search([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 4)
|
code/search/src/exponential_search/exponential_search.rs | fn main() {
let nums = vec![1, 3, 5, 7, 9, 11, 13, 15, 17, 19];
let find_me = 13;
let index = exponential_search(&nums, find_me);
println!("Given Array: {:?}\n", nums);
println!("Searched for {} and found index {}", find_me, index);
}
fn exponential_search(nums: &Vec<i64>, search_value: i64) -> i64 {
let size: usize = nums.len();
if size == 0 {
return -1;
}
let mut bound: usize = 1;
while bound < size && nums[bound] < search_value {
bound *= 2;
}
return binary_search(&nums, search_value, bound/2, min(bound, size))
}
fn binary_search(nums: &Vec<i64>, search_value: i64, left: usize, right: usize) -> i64 {
let mut left = left;
let mut right = right;
while left <= right {
let middle = (left + right) / 2;
if middle == nums.len() {
break;
}
if nums[middle] == search_value {
return middle as i64;
} else if nums[middle] < search_value {
left = middle + 1;
} else if nums[middle] > search_value && middle != 0 {
right = middle - 1;
} else {
break;
}
}
-1
}
fn min(x: usize, y: usize) -> usize {
if x < y {
x
} else {
y
}
}
|
code/search/src/exponential_search/exponential_search2.cpp | // C++ program to find an element x in a
// sorted array using Exponential search.
#include <cstdio>
#define min(a, b) ((a) < (b) ? (a) : (b))
using namespace std;
int binarySearch(int arr[], int, int, int);
// Returns position of first ocurrence of
// x in array
int exponentialSearch(int arr[], int n, int x)
{
// If x is present at firt location itself
if (arr[0] == x)
return 0;
// Find range for binary search by
// repeated doubling
int i = 1;
while (i < n && arr[i] <= x)
i = i * 2;
// Call binary search for the found range.
return binarySearch(arr, i / 2, min(i, n), x);
}
// A recursive binary search function. It returns
// location of x in given array arr[l..r] is
// present, otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l) / 2;
// If the element is present at the middle
// itself
if (arr[mid] == x)
return mid;
// If element is smaller than mid, then it
// can only be present n left subarray
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
// Else the element can only be present
// in right subarray
return binarySearch(arr, mid + 1, r, x);
}
// We reach here when element is not present
// in array
return -1;
}
// Driver code
int main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = exponentialSearch(arr, n, x);
(result == -1) ? printf("Element is not present in array")
: printf("Element is present at index %d",
result);
return 0;
}
|
code/search/src/fibonacci_search/fibonacci_search.c | // search | fibonacci search | c
// Part of Cosmos by OpenGenus Foundation
/*
ar -> Array name
n -> Array size
secondPreceding -> Number at second precedence
firstPreceding -> Number at first precedence
nextNum -> Fibonacci Number equal to or first greatest than the array size
range -> Eleminated range marker
*/
#include <stdio.h>
#include <stdlib.h>
int fibSearch(int ar[], int x, int n);
int min(int a, int b);
int main()
{
int n;
scanf("%d",&n);
int ar[n],i;
for(i=0;i<n;i++){
scanf("%d",&ar[i]);
}
int x;
scanf("%d",&x);
int index = fibSearch(ar,x,n);
if(index == -1){
printf("Element not found.\n");
return 0;
}
printf("Element found at index %d\n",index );
return 0;
}
int fibSearch(int ar[], int x, int n)
{
int secondPreceding = 0, firstPreceding = 1;
int nextNum = secondPreceding + firstPreceding;
while(nextNum < n){
secondPreceding = firstPreceding;
firstPreceding = nextNum;
nextNum = secondPreceding + firstPreceding;
}
int range = -1;
while(nextNum > 1){
int i = min(range + firstPreceding, n-1);
if(x < ar[i]){
nextNum = nextNum - firstPreceding;
firstPreceding = firstPreceding - secondPreceding;
secondPreceding = nextNum - firstPreceding;
}
else if(x > ar[i]){
nextNum = firstPreceding;
firstPreceding = secondPreceding;
secondPreceding = nextNum - firstPreceding;
range = i;
}
else{
return i;
}
}
if(firstPreceding && ar[range+1] == x){
return range + 1;
}
return -1;
}
int min(int a, int b)
{
if(a > b){
return b;
}
else{
return a;
}
}
|
code/search/src/fibonacci_search/fibonacci_search.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*
* fibonacci search synopsis
*
* warning: in order to follow the convention of STL, the interface is [begin, end) !!!
*
* namespace fibonacci_search_impl
* {
* template<typename _Input_Iter,
* typename _Tp = typename std::iterator_traits<_Input_Iter>::value_type, typename _Compare>
* _Input_Iter
* fibonacciSearchImpl(_Input_Iter begin,
* _Input_Iter end,
* _Tp const &find,
* _Compare comp,
* std::input_iterator_tag);
* } // fibonacci_search_impl
*
* template<typename _Input_Iter,
* typename _Tp = typename std::iterator_traits<_Input_Iter>::value_type, typename _Compare>
* _Input_Iter
* fibonacciSearch(_Input_Iter begin, _Input_Iter end, _Tp const &find, _Compare comp);
*
* template<typename _Input_Iter,
* typename _Tp = typename std::iterator_traits<_Input_Iter>::value_type>
* _Input_Iter
* fibonacciSearch(_Input_Iter begin, _Input_Iter end, _Tp const &find);
*/
#include <functional>
namespace fibonacci_search_impl
{
template<typename _Input_Iter,
typename _Tp = typename std::iterator_traits<_Input_Iter>::value_type,
typename _Compare>
_Input_Iter
fibonacciSearchImpl(_Input_Iter begin,
_Input_Iter end,
_Tp const &find,
_Compare comp,
std::input_iterator_tag)
{
if (begin == end)
return end;
size_t dist = std::distance(begin, end);
size_t fibMMm2 = 0; // (m-2)'th Fibonacci No.
size_t fibMMm1 = 1; // (m-1)'th Fibonacci No.
size_t fibM = fibMMm2 + fibMMm1;
while (fibM < dist)
{
fibMMm2 = fibMMm1;
fibMMm1 = fibM;
fibM = fibMMm2 + fibMMm1;
}
size_t offset = -1;
auto it = begin;
while (fibM > 1)
{
// prevent overflow
size_t i = std::min(offset + fibMMm2, dist - 1);
it = begin;
std::advance(it, i);
if (comp(*it, find))
{
fibM = fibMMm1;
fibMMm1 = fibMMm2;
fibMMm2 = fibM - fibMMm1;
offset = i;
}
else if (comp(find, *it))
{
fibM = fibMMm2;
fibMMm1 = fibMMm1 - fibMMm2;
fibMMm2 = fibM - fibMMm1;
}
else
return it;
}
// comparing the last element with find
it = begin;
std::advance(it, offset + 1);
if (fibMMm1 && *it == find)
return it;
return end;
}
} // fibonacci_search_impl
template<typename _Input_Iter,
typename _Tp = typename std::iterator_traits<_Input_Iter>::value_type, typename _Compare>
_Input_Iter
fibonacciSearch(_Input_Iter begin, _Input_Iter end, _Tp const &find, _Compare comp)
{
auto category = typename std::iterator_traits<_Input_Iter>::iterator_category();
return fibonacci_search_impl::fibonacciSearchImpl(begin, end, find, comp, category);
}
template<typename _Input_Iter,
typename _Tp = typename std::iterator_traits<_Input_Iter>::value_type>
_Input_Iter
fibonacciSearch(_Input_Iter begin, _Input_Iter end, _Tp const &find)
{
return fibonacciSearch(begin, end, find, std::less<_Tp>());
}
|
code/search/src/fibonacci_search/fibonacci_search.java | // search | fibonacci search | c
// Part of Cosmos by OpenGenus Foundation
/**
* Fibonacci Search is a popular algorithm which finds the position of a target value in
* a sorted array
*
* The time complexity for this search algorithm is O(log3(n))
* The space complexity for this search algorithm is O(1)
*/
public class FibonacciSearch {
/**
* @author Kanakalatha Vemuru (https://github.com/KanakalathaVemuru)
* @param array is a sorted array where the element has to be searched
* @param key is an element whose position has to be found
* @param <T> is any comparable type
* @return index of the element
*/
public <T extends Comparable<T>> int find(T[] array, T key) {
int fibMinus1 = 1;
int fibMinus2 = 0;
int fibNumber = fibMinus1 + fibMinus2;
int n = array.length;
while (fibNumber < n) {
fibMinus2 = fibMinus1;
fibMinus1 = fibNumber;
fibNumber = fibMinus2 + fibMinus1;
}
int offset = -1;
while (fibNumber > 1) {
int i = Math.min(offset + fibMinus2, n - 1);
if (array[i].compareTo(key) < 0) {
fibNumber = fibMinus1;
fibMinus1 = fibMinus2;
fibMinus2 = fibNumber - fibMinus1;
offset = i;
}
else if (array[i].compareTo(key) > 0) {
fibNumber = fibMinus2;
fibMinus1 = fibMinus1 - fibMinus2;
fibMinus2 = fibNumber - fibMinus1;
}
else {
return i;
}
}
if (fibMinus1 == 1 && array[offset + 1] == key) {
return offset + 1;
}
return -1;
}
// Driver Program
public static void main(String[] args) {
Integer[] integers = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512};
int size = integers.length;
Integer shouldBeFound = 128;
FibonacciSearch fsearch = new FibonacciSearch();
int atIndex = fsearch.find(integers, shouldBeFound);
System.out.println(
"Should be found: " + shouldBeFound + ". Found "+ integers[atIndex] + " at index "+ atIndex +". An array length " + size);
}
} |
code/search/src/fibonacci_search/fibonacci_search.js | function fibonacciSearch(ar, x, n) {
var secondPreceding = 0,
firstPreceding = 1;
var nextNum = secondPreceding + firstPreceding;
while (nextNum < n) {
secondPreceding = firstPreceding;
firstPreceding = nextNum;
nextNum = secondPreceding + firstPreceding;
}
var range = -1;
while (nextNum > 1) {
var i = min(range + firstPreceding, n - 1);
if (x < ar[i]) {
nextNum = nextNum - firstPreceding;
firstPreceding = firstPreceding - secondPreceding;
secondPreceding = nextNum - firstPreceding;
} else if (x > ar[i]) {
nextNum = firstPreceding;
firstPreceding = secondPreceding;
secondPreceding = nextNum - firstPreceding;
range = i;
} else {
return i;
}
}
if (firstPreceding && ar[range + 1] == x) {
return range + 1;
}
return -1;
}
function min(a, b) {
return a > b ? b : a;
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.