Sei sulla pagina 1di 19

AUTOMATA

1)There is a colony of 8 cells arranged in a straight line where each day every cell competes
with its adjacent cells(neighbour).

Each day, for each cell, if its neighbours are both active or both inactive, the cell becomes
inactive the next day,.otherwiseitbecomes active the next day.

Assumptions:

The two cells on the ends have single adjacent cell, so the other adjacent cell can be assumsed
to be always inactive.

Even after updating the cell state. consider its pervious state for updating the state of other
cells. Update the cell informationofallcells simultaneously.

Write a fuctioncellCompete which takes takes one 8 element array of integers cells
representing the current state of 8 cells and one integer days representing te number of days
to simulate.

An integer value of 1 represents an active cell and value of 0 represents an inactive cell.

program:

int* cellCompete(int* cells,int days)

solution:

#include<iostream>
using namespace std;
int main()
{
int arr[8];
int temp[8];
int i;
for(i=0;i<8;i++)
{
cin>>arr[i];
}
int d;
cin>>d;
while(d--)
{
for(i=0;i<8;i++)
{
if(i==0)
temp[i]=(arr[i+1]);
else if(i==7)
temp[i]=(arr[i-1]);
else
temp[i]=((arr[i-1])^(arr[i+1]));

}
for(i=0;i<8;i++)
{
arr[i]=temp[i];
}
}
for(i=0;i<8;i++)
{
cout<<arr[i];
}
return 0;
}

//function signature ends

TESTCASES 1:

INPUT:

[1,0,0,0,0,1,0,0],1

EXPECTED RETURN VALUE:

[0,1,0,0,1,0,1,0]

TESTCASE 2:

INPUT:

[1,1,1,0,1,1,1,1,],2

EXPECTED RETURN VALUE:

[0,0,0,0,0,1,1,0]

2) The Least-Recently-Used(LRU) cache algorithm exists the element from the cache(when
it's full) that was least-recently-used. After an element is requested from the cache, it should
be added to the cache(if not already there) and considered the most-recently-used element in
the cache.

Given the maximum size of the cache and a list of integers(to request from the cache),
calculate the number of cache misses using the LRU cache algorithm. A cache miss occur
when the requested integer does not exist in the cache.

Initially, the cache is empty.

The input to the function LruCountMiss shall consist of an integer max_cache_size, an array
pages and its length len.
The function should return an integer for the number of cache misses using the LRU cache
algorithm.

Assume that the array pages always has pages numbered from 1 to 50.

TESTCASES:

TESTCASE1:

INPUT:

3,[7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0],16

EXPECTED RETURN VALUE:

11

TESTCASE 2:

INPUT:

2,[2,3,1,3,2,1,4,3,2],9

EXPECTED RETURN VALUE:

EXPLANATION:

The following page numbers are missed one after the other 2,3,1,2,1,4,3,2.This results in 8
page misses.

CODE:
#include<iostream>
using namespace std;
int lruCountMiss(int max_cache_size, int *pages,int len)
{
int miss=0,cache[max_cache_size]; //variable miss and cache declared
for (int i=0;i<max_cache_size;i++){ /*this is for clearing value of cache i.e. to empty cache.
I used any value here*/
cache[i]=0x87787;
}
for (int i=0;i<len;i++){ //for loop for all the value from list one by one
for(int j=0;j<max_cache_size;j++){ //loop to check the cache value, if it matches the value
if (pages[i]==cache[j]){
for (int k=i; k<max_cache_size;k++){ /*if the value is already present in the cache then
shifting values from the present value.*/
cache[i]=cache[i+1];
}
cache[max_cache_size-1]=pages[i]; //updating the last value of cache
break;
}
else if(j==(max_cache_size-1)){
for (int l=0; l<max_cache_size;l++){ /*if the value is not present in the cache then shifting
values from starting.*/
cache[l]=cache[l+1];
}
cache[max_cache_size-1]=pages[i];//updating the last value of cache
miss++;
}
}}
return miss;}//returning the Miss
int main(){ //main function
cout<< "This is the Least Recently Used(LRU) cache algorithm \n";
cout<< "We are checking two cases.\n"<<"Case 1:t"<<"Array values are
[7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0] nand cache size= 3; and total values to check are 16: n We got
the miss. ";
int days,pages[]={7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0}; //array to pass through function
int *cellsptr=pages; //creating array values to pointer
cout<<"Miss =t"<<lruCountMiss(3,cellsptr,16);//passing to function
cout<<"nnCase 2:t"<<"Array values are [2,3,1,3,2,1,4,3,2] nand cache size= 2; and total
values to check are 9: n We got the miss. ";
int pages2[]={2,3,1,3,2,1,4,3,2};
int *cellsptr2=pages2; //creating array values to pointer
cout<<"Miss =t"<<lruCountMiss(2,cellsptr2,9);//passing to function
return 0;
}

3) Write a function to insert an integer into a circular linked _list whose elements are sorted
in ascending order

(smallest to largest).

The input to the function insertSortedList is a pointer start to some node in the circular list
and an integer n between 0 and 100. Return a pointer to the newly inserted node.

The structure to follow for a node of the circular linked list is_

Struct CNode ;
Typedef struct CNode cnode;
StructCNode
{
Int value;
Cnode* next;
};
Cnode* insertSortedList (cnode* start, int n
Solution in C:
#include<stdio.h>
#include<stdlib.h>
/* structure for a node */
struct Node
{
int data;
struct Node *next;
};

/* function to insert a new_node in a list in sorted way.


Note that this function expects a pointer to head node
as this can modify the head of the input linked list */
void sortedInsert(struct Node** head_ref, struct Node* new_node)
{
struct Node* current = *head_ref;
// Case 1 of the above algo
if (current == NULL)
{
new_node->next = new_node;
*head_ref = new_node;
}
// Case 2 of the above algo
else if (current->data >= new_node->data)
{
/* If value is smaller than head's value then
we need to change next of last node */
while(current->next != *head_ref)
current = current->next;
current->next = new_node;
new_node->next = *head_ref;
*head_ref = new_node;
}
// Case 3 of the above algo
else
{
/* Locate the node before the point of insertion */
while (current->next!= *head_ref &&
current->next->data < new_node->data)
current = current->next;
new_node->next = current->next;
current->next = new_node;
}
}
/* Function to print nodes in a given linked list */
void printList(struct Node *start)
{
struct Node *temp;
if(start != NULL)
{
temp = start;
printf("\n");
do {
printf("%d ", temp->data);
temp = temp->next;
} while(temp != start);
}
}
/* Driver program to test above functions */
int main()
{
int arr[] = {12, 56, 2, 11, 1, 90};
int list_size, i;
/* start with empty linked list */
struct Node *start = NULL;
struct Node *temp;
/* Create linked list from the array arr[].
Created linked list will be 1->2->11->12->56->90 */
for (i = 0; i< 6; i++)
{
temp = (struct Node *)malloc(sizeof(struct Node));
temp->data = arr[i];
sortedInsert(&start, temp);
}
printList(start);
return 0;
}
Another sol:
#include <stdio.h>
#include <stdlib.h>

struct node {
int data;
struct node * next;
}*head;
void createList(int n);
void displayList();
void insertAtBeginning(int data);
void insertAtN(int data, int position);
void insertSortedList(int data);
int main()
{
int n, data, choice=1;
while(choice != 0)
{
printf("============================================\n");
printf("CIRCULAR LINKED LIST PROGRAM\n");
printf("============================================\n");
printf("1. Create List\n");
printf("2. Display list\n");
// printf("3. Insert at beginning\n");
printf("4. Insert New Node\n");
printf("0. Exit\n");
printf("--------------------------------------------\n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter the total number of nodes in list: ");
scanf("%d", &n);
createList(n);
break;
case 2:
displayList();
break;
// case 3:
// printf("Enter data to be inserted at beginning: ");
// scanf("%d", &data);
// insertAtBeginning(data);
// break;
case 4:
printf("Enter data you want to insert: ");
scanf("%d", &data);
insertSortedList(data);
break;
case 0:
break;
default:
printf("Error! Invalid choice. Please choose between 0-4");
}
printf("\n\n\n\n\n");
}
return 0;
}
/**
* Creates a circular linked list of n nodes.
* @n Number of nodes to be created
*/
void createList(int n)
{
int i, data;
struct node *prevNode, *newNode;

if(n >= 1)
{
/*
* Creates and links the head node
*/
head = (struct node *)malloc(sizeof(struct node));

printf("Enter data of 1 node: ");


scanf("%d", &data);
head->data = data;
head->next = NULL;
prevNode = head;
/*
* Creates and links rest of the n-1 nodes
*/
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));
printf("Enter data of %d node: ", i);
scanf("%d", &data);
newNode->data = data;
newNode->next = NULL;
//Links the previous node with newly created node
prevNode->next = newNode;
//Moves the previous node ahead
prevNode = newNode;
}
//Links the last node with first node
prevNode->next = head;
printf("\nCIRCULAR LINKED LIST CREATED SUCCESSFULLY\n");
}
}
/**
* Displays the content of the list
*/
void displayList()
{
struct node *current;
int n = 1;
if(head == NULL)
{
printf("List is empty.\n");
}
else
{
current = head;
printf("DATA IN THE LIST:\n");
do {
printf("Data %d = %d\n", n, current->data);
current = current->next;
n++;
}while(current != head);
}
}
/**
* Inserts a new node at the beginning of the list
* @data Data of the first node
*/
void insertAtBeginning(int data)
{
struct node *newNode, *current;

if(head == NULL)
{
printf("List is empty.\n");
}
else
{
/*
* Creates new node, assign data and links it to head
*/
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = head;
/*
* Traverses to last node and links last node
* with first node which is new node
*/
current = head;
while(current->next != head)
{
current = current->next;
}
current->next = newNode;

/*Makes new node as head node*/


head = newNode;
printf("NODE INSERTED SUCCESSFULLY\n");
}
}
void insertSortedList(int data)
{
struct node *newNode, *current, *pre;
if(head == NULL)
{
printf("List is empty.\n");
}
else
{
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data;
current = head;
pre=head;
while(1)
{
if(current->data<newNode->data)
{
pre=current;
current=current->next;
}
else
{
pre->next=newNode;
newNode->next=current;
break;
}
}
head=newNode;
printf("NODE INSERTED SUCCESSFULLY.\n");
}
}
/**
* Inserts a new node at any position in the list
* @data Data of the new node
* @position Position where to insert new node
*/
void insertAtN(int data, int position)
{
struct node *newNode, *current;
int i;
if(head == NULL)
{
printf("List is empty.\n");
}
else if(position == 1)
{
insertAtBeginning(data);
}
else
{
/*
* Creates new node and assign data to it
*/
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data;
/*
* Traverse to n-1 node
*/
current = head;
for(i=2; i<=position-1; i++)
{
current = current->next;
}
/* Links new node with node ahead of it and previous to it*/
newNode->next = current->next;
current->next = newNode;
printf("NODE INSERTED SUCCESSFULLY.\n");
}
}
/*
Output
============================================
CIRCULAR LINKED LIST PROGRAM
============================================
1. Create List
2. Display list
3. Insert at beginning
4. Insert at any position
0. Exit
--------------------------------------------
Enter your choice : 1
Enter the total number of nodes in list: 2
Enter data of 1 node: 20
Enter data of 2 node: 40
CIRCULAR LINKED LIST CREATED SUCCESSFULLY
============================================
CIRCULAR LINKED LIST PROGRAM
============================================
1. Create List
2. Display list
3. Insert at beginning
4. Insert at any position
0. Exit
--------------------------------------------
Enter your choice : 2
DATA IN THE LIST:
Data 1 = 20
Data 2 = 40

4) A system that can run multiple concurrent jobs on a single CPU have a process of
choosing which task hast to run when, and how to break them up, called “scheduling”. The
Round-Robin policy for scheduling runs each job for a fixed amount of time before switching
to the next job. The waiting time fora job is the total time that it spends waiting to be run.
Each job arrives at particular time for scheduling and certain time to run, when a new job
arrives, It is scheduled after existing jobs already waiting for CPU time.Given list of job
submission, calculate the average waiting time for all jobs using Round-Robin policy.

The input to the function waitingTime Robin consist of two integer arrays containing job
arrival and run times, an integer n representing number of jobs and am integer q representing
the fixed amount of time used by Round-Robin policy. The list of job arrival time and run
time sorted in ascending order by arrival time. For jobs arriving at same time, process them in
the order they are found in the arrival array. You can assume that jobs arrive in such a way
that CPU is never idle.

The function should return floating point value for the average waiting time which is
calculated using round robin policy.

Assume 0<=jobs arrival time < 100 and 0<job run time <100.

Solution:
#include<iostream>
using namespace std;
void findWaitingTime(int processes[], int n, int bt[], int wt[], int quantum)
{
int rem_bt[n];
for (int i = 0 ; i < n ; i++)
rem_bt[i] = bt[i];

int t = 0;

while (1)
{
bool done = true;
for (int i = 0 ; i < n; i++)
{
if (rem_bt[i] > 0)
{
done = false;

if (rem_bt[i] > quantum)


{
t += quantum;
rem_bt[i] -= quantum;
}
else
{
t = t + rem_bt[i];
wt[i] = t - bt[i];
rem_bt[i] = 0;
}
}
}
if (done == true)
break;
}
}

void findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[])
{
for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i];
}

void waitingTimeRobin(int processes[], int bt[], int quantum, int n)


{
int wt[n], tat[n], total_wt = 0, total_tat = 0;

findWaitingTime(processes, n, bt, wt, quantum);

findTurnAroundTime(processes, n, bt, wt, tat);

cout << "Processes "<< " Burst time "<< " Waiting time " << " Turn around time\n";

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;
}

int main()
{
int n, quantum, processes[100], burst_time[100];

printf("Enter numbers of jobs: ");


scanf("%d", &n);
printf("Enter arrival time of %d jobs:\n",n);
for(int i=0;i<n;i++)
{
scanf("%d", &processes[i]);
}
printf("Enter run time of %d jobs:\n",n);
for(int i=0;i<n;i++)
{
scanf("%d", &burst_time[i]);
}
printf("Enter fixed amount of time used: ");
scanf("%d", &quantum);
waitingTimeRobin(processes, burst_time, quantum, n);
return 0;
}

5) Problem:Mooshak the mouse has been placed in a maze.There is a huge chunk of cheese
somewhere in the maze.The maze is represented as a two-dimentional array of integers,
where 0 represents walls.1repersents paths where mooshak can move and 9 represents the
huge chunk of cheese. Mooshak starts in the top-left corner at 0.0

Write a method isPath of class MazePath to determine if Mooshak can reach the huge chunk
of cheese. The input to isPath consists of a two- dimentional array gnd for the maze matrix.
the method should return 1 if there is a path from Mooshak to the cheese.and 0 if not
Mooshak is not allowed to leave the maze or climb on walls.

EX:8 by 8(8*8) matrix maze where Mooshak can get the cheese.

10111001

10001111

10000000

10109011

11101001

10101101
10000101

11111111

Test Cases:

Case 1:

Input:[[1,1,1,][9,1,1],[0,1,0]]

Expected return value :1

Explanation:

The piece of cheese is placed at(1,0) on the grid Mooshak can move from (0,0) to (1,0) to
reach it or can move from (0,0) to (0,1) to (1,1) to (1,0)

Test case 2:

Input:

[[0,0,0],[9,1,1],[0,1,1]]

Expected return value:0

Explanation:

Mooshak cannot move anywhere as there exists a wall right on (0,0).

Solution:

Solution in c:
#include<stdio.h>
// Maze size
#define N 4
bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]);
/* A utility function to print solution matrix sol[N][N] */
void printSolution(int sol[N][N])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
printf(" %d ", sol[i][j]);
printf("\n");
}
}
/* A utility function to check if x,y is valid index for N*N maze */
bool isSafe(int maze[N][N], int x, int y)
{
// if (x,y outside maze) return false
if(x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1)
return true;
return false;
}
bool solveMaze(int maze[N][N])
{
int sol[N][N] = { {0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
if(solveMazeUtil(maze, 0, 0, sol) == false)
{
printf("Solution doesn't exist");
return false;
}
printSolution(sol);
return true;
}
/* A recursive utility function to solve Maze problem */
bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N])
{
// if (x,y is goal) return true
if(x == N-1 && y == N-1)
{
sol[x][y] = 1;
return true;
}
// Check if maze[x][y] is valid
if(isSafe(maze, x, y) == true)
{
// mark x,y as part of solution path
sol[x][y] = 1;
/* Move forward in x direction */
if (solveMazeUtil(maze, x+1, y, sol) == true)
return true;
/* If moving in x direction doesn't give solution then
Move down in y direction */
if (solveMazeUtil(maze, x, y+1, sol) == true)
return true;
/* If none of the above movements work then BACKTRACK:
unmark x,y as part of solution path */
sol[x][y] = 0;
return false;
}
return false;
}
// driver program to test above function
int main()
{
int maze[N][N] = { {1, 0, 0, 0},
{1, 1, 0, 1},
{0, 1, 0, 0},
{1, 1, 1, 1}
};
solveMaze(maze);
return 0;
}
6.Problem:

Every day, Mike goes to his job by a bus, where he buys a ticket. On the ticket, there is a
letter-code that can be represented as a string of upper-case Latin letters.

Mike believes that the day will be successful in case exactly two different letters in the code
alternate. Otherwise, he believes that the day will be unlucky. Please see note section for
formal definition of alternating code.

You are given a ticket code. Please determine, whether the day will be successful for Mike or
not. Print "YES" or "NO" (without quotes) corresponding to the situation.

Input

The first line of the input contains an integer T denoting the number of test cases. The
description of T test cases follows.

The first and only line of each test case contains a single string S denoting the letter code on
the ticket.

Output

For each test case, output a single line containing "YES" (without quotes) in case the day will
be successful and "NO" otherwise.

Note

Two letters x, y where x != y are said to be alternating in a code, if code is of form


"xyxyxy...".

Constraints

1 ≤ T ≤ 100 of upper-case Latin letters

Subtask 1 (50 points):

S consists only

|S| = 2

Subtask 2 (50 points):

2 ≤ |S| ≤ 100

Example
Input:

ABABAB

ABC

Output:

YES

NO

Solution:

#include<stdio.h>
#include<string.h>
int main()
{
int t,sl,i,f;
char str[101], fc,sc;
printf("Enter number of test cases: ");
scanf("%d",&t);
while(t--)
{
printf("\n\nEnter the letter code given on the ticket: ");
scanf("%s",str);
sl=strlen(str);
fc=str[0];
sc=str[1];
f=1;
for(i=0; i<sl; i=i+2)
{
if(str[i] != fc)
{
f=0;
break;
}
}
if(f==1)
{
for(i=1; i<sl; i=i+2)
{
if(str[i] != sc)
{
f=0;
break;
}
}
}
if(fc==sc)
f=0;
if(f==1)
printf("YES\n");
if(f==0)
printf("NO\n");
}
return 0;
}

7.Problem:

Jem is famous for his laziness at school. He always leaves things to last minute. Now Jem has
N problems in the assignment of "Advanced topics in algorithm" class to solved. The
assignment is due tomorrow and as you may guess he hasn't touch any of the problems.
Fortunately he got a plan as always.

The first step will be buying a pack of Red Bull and then to work as hard as he can. Here is
how he is going to spend the remaining time:

Jem will not take a break until he finishes at least half of the remaining problems. Formally,
if N is even then he will take he first break after finishing N / 2 problems. If N is odd then the
break will be after he done (N + 1) / 2 problems. Each of his break will last for B minutes.
Initially, he takes M minutes in solving a problem, after each break he will take twice more
time in solving a problem, i.e. 2 * M minutes per problem after the first break.

Jem will start working soon and ask you to help him calculate how much time it will take
until he finish the last problem!

Input

The first line contains a single integer T represents the number of test cases in the input. Each
line in the next T line contains three integers N, B and M represents a test case.

Output

For each test case output a single line containing an integer represent how much time Jem
will need (in minutes).

Constraints

• 1 ≤ T ≤ 100

• 1 ≤ N, B, M ≤ 108

Example

Input:
2

912

123456 123456 123456

Output:

45

131351258112

Solution:

#include<math.h>
#include<stdio.h>
long long int A[11000];
int main()
{ long long int i,j,t,n,b,m,x,z,s;
printf("Enter number of testcases");
scanf("%lld",&t);
for(i=0;i<t;i++)
{
printf("enter value for number,break and minutes");
scanf("%lld%lld%lld",&n,&b,&m);
z=s=0;
while(n!=1)
{ x=n;
n=n/2;
A[z]=x-n;
z=z+1;
}
A[z]=1;
s=s+(z*b);
for(j=0;j<=z;j++)
{ s=s+(m*A[j]);
m=m*2;
}
printf("%lld\n",s);
for(j=0;j<=z;j++)
A[j]=0;
}
return 0;
}
Input:
2
912
123456 123456 123456
Output:
45
131351258112

Potrebbero piacerti anche