Wednesday, 25 January 2017
First In First Out (FIFO) algorithm for demand paging in java
Least Recently Used(LRU) algorithm for demand paging implementation in Java
public class LRU { private String input; private int frameSize; private int falutCount=0; private int[] timeCount; private String[] frameStack; /** * * @param commaSepratedPages * Page String will be like '7,0,1,2,0,3,0' * @param frameSize * Frame Size that can hold Pages. */ public LRU(String commaSepratedPages,int frameSize){ this.frameSize=frameSize; timeCount=new int[frameSize]; frameStack=new String[frameSize]; input=commaSepratedPages; } /** * Number of page faults with given Frame Size and Input. * @return */ public int getPageFaults(){ falutCount=0; String[] pages=input.split(","); System.out.println("Pages :\n "+input); System.out.println("Fault Pages "); for(String page:pages){ updateStack(page); } return falutCount; } private void updateStack(String page){ boolean isFaultOccured=true; int matchIndex=0; for(int i=0;i<frameSize;i++){ if(page.equals(frameStack[i])){ timeCount[i]=0; matchIndex=i; isFaultOccured=false; break; } } if(isFaultOccured){ System.out.print(page+" "); falutCount++; matchIndex=getLeastRecentlyUsedIndex(); frameStack[matchIndex]=page; timeCount[matchIndex]=0; } upadteUsedTime(matchIndex); } private void upadteUsedTime(int pageHitIndex){ for(int i=0;i<frameSize;i++){ if(i!=pageHitIndex){ timeCount[i]++; } } } private int getLeastRecentlyUsedIndex(){ int index=0; int time=0; for(int i=0;i<frameSize;i++){ if(timeCount[i]>time){ time=timeCount[i]; index=i; } } return index; } }
Monday, 1 August 2016
Exception Handling
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ERP.Attributes
{
public class GlobalHandleErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled /*|| !filterContext.HttpContext.IsCustomErrorEnabled*/)
{
return;
}
filterContext.ExceptionHandled = true;
string spMessage = string.Empty;
Exception exception = filterContext.Exception;
if (exception is SqlException)//Get Exception Message raised by Stored procedure
{
SqlErrorCollection collection = (exception as SqlException).Errors;
for (int i = 0; i < collection.Count; i++)
{
if (!string.IsNullOrEmpty(collection[i].Procedure) && collection[i].LineNumber > 0)
{
spMessage = spMessage + collection[i].Message;
}
}
}
if (IsAjax(filterContext) && !IsAcceptTextOrHtml(filterContext))//AJAX Call
{
string message = /*exception.GetType().Name + " : " +*/ (string.IsNullOrEmpty(spMessage) ?filterContext.Exception.Message : spMessage);
filterContext.Result = new JsonResult()
{
Data = new { Success = false, ErrorMessage = message, SuccessMessage = message, Message = message },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else //Normal Call
{
string currentController = filterContext.RouteData.Values["controller"].ToString();
string currentActionName = filterContext.RouteData.Values["action"].ToString();
HandleErrorInfo handleErrorInfo = new HandleErrorInfo(exception, currentController, currentActionName);
filterContext.Result = new ViewResult()
{
ViewName = "~/Views/Shared/GlobalError.cshtml",
ViewData = new ViewDataDictionary(handleErrorInfo),
};
}
base.OnException(filterContext);
}
private bool IsAjax(ExceptionContext filterContext)
{
return filterContext.HttpContext.Request.Headers["Accept"].ToLower().Contains("application/json") ||
filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest" ||
filterContext.HttpContext.Request.IsAjaxRequest();
}
private bool IsAcceptTextOrHtml(ExceptionContext filterContext)
{
return filterContext.HttpContext.Request.Headers["Accept"].ToLower().Contains("text/html");
}
}
}
using System.Web;
using System.Web.Mvc;
namespace ERP.WebApp
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new GlobalHandleErrorAttribute());
filters.Add(new GlobalActionFilterAttribute());
}
}
}
Thursday, 11 September 2014
Game of Thrones - I (check pelidnrome string)
King Robert has 7 kingdoms under his rule. He finds out from a raven that the Dothraki are soon going to wage a war against him. But, he knows the Dothraki need to cross the narrow river to enter his dynasty. There is only one bridge that connects both sides of the river which is sealed by a huge door.The king wants to lock the door so that the Dothraki can't enter. But, to lock the door he needs a key that is an anagram of a certain palindrome string.The king has a string composed of lowercase English letters. Help him figure out if any anagram of the string can be a palindrome or not.Input Format A single line which contains the input stringConstraints 1<=length of string <= 10^5 Each character of the string is a lowercase English letter.Output Format A single line which contains YES or NO in uppercase.Sample Input : 01aaabbbbSample Output : 01YESExplanation A palindrome permutation of the given string is bbaaabb.Sample Input : 02cdefghmnopqrstuvwSample Output : 02NOExplanation You can verify that the given string has no palindrome permutation.Sample Input : 03cdcdcdcdeeeefSample Output : 03YESExplanation A palindrome permutation of the given string is ddcceefeeccdd .
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
void findPalind(char *arr)
{
int flag = 0,len,index,i,count,status[26]={};
len=strlen(arr);
for(i=0;i<len;i++)
{ index=(int)arr[i]-97;
if(status[index]==0)
status[index]=1;
else status[index]=0;
}
count=0;
for(index=0;index<26;index++)
{
if(count>1)
{
flag=1;
break;
}
if(status[index]==1)
count++;
}
if (flag==0)
printf("YES\n");
else
printf("NO\n");
}
int main() {
char arr[100001];
scanf("%s",arr);
findPalind(arr);
return 0;
}
The Love Letter Mystery Problem
James found a love letter his friend Harry has written for his girlfriend. James is a prankster, so he decides to meddle with the letter. He changes all the words in the letter intopalindromes.To do this, he follows 2 rules:(a) He can reduce the value of a letter, e.g. he can change 'd' to 'c', but he cannot change 'c' to 'd'. (b) In order to form a palindrome, if he has to repeatedly reduce the value of a letter, he can do it until the letter becomes 'a'. Once a letter has been changed to 'a', it can no longer be changed.Each reduction in the value of any letter is counted as a single operation. Find the minimum number of operations required to convert a given string into a palindrome.Input Format The first line contains an integer T, i.e., the number of test cases. The next T lines will contain a string each.Output Format A single line containing the number of minimum operations corresponding to each test case.Constraints 1 ≤ T ≤ 10 1 ≤ length of string ≤ 104 All characters are lower case English letters.Sample Input #003 abc abcba abcdSample Output #002 0 4ExplanationFor the first test case, ab*c* -> ab*b* -> ab*a*. For the second test case, abcba is a palindromic string. For the third test case, abc*d* -> abc*c* -> abc*b* -> abc*a* = ab*c*a -> ab*b*a.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int T,i,j,len,count=0;
char **s;
scanf("%d",&T);
s=(char**)malloc(sizeof(char*)*T);
for(i=0;i<T;i++)
{
s[i]=(char*)malloc(sizeof(char)*10000);
scanf("%s",s[i]);
}
for(i=0;i<T;i++)
{ count=0;
len=strlen(s[i]);
for(j=0;j<len/2;j++)
{
if(s[i][j]>s[i][len-j-1])
{
while(s[i][j]!=s[i][len-j-1])
{
s[i][j]=(char)((int)s[i][j]-1);
count++;
}
}
else
if(s[i][j]<s[i][len-j-1])
{
while(s[i][j]!=s[i][len-j-1])
{
s[i][len-j-1]=(char)((int)s[i][len-j-1]-1);
count++;
}
}
}
printf("%d\n",count);
}
return 0;
}
Cut the sticks problem
You are given N sticks, where each stick is of positive integral length. A cut operation is performed on the sticks such that all of them are reduced by the length of the smallest stick.Suppose we have 6 sticks of length5 4 4 2 2 8then in one cut operation we make a cut of length 2 from each of the 6 sticks. For next cut operation 4 sticks are left (of non-zero length), whose length are3 2 2 6Above step is repeated till no sticks are left.Given length of N sticks, print the number of sticks that are cut in subsequent cut operations.Input Format The first line contains a single integer N. The next line contains N integers: a0, a1,...aN-1 separated by space, where ai represents the length of ith stick.Output Format For each operation, print the number of sticks that are cut in separate line.Constraints 1 ≤ N ≤ 1000 1 ≤ ai ≤ 1000Sample Input #006 5 4 4 2 2 8Sample Output #006 4 2 1Sample Input #018 1 2 3 4 3 3 2 1Sample Output #018 6 4 1ExplanationSample Case #00 :sticks-length length-of-cut sticks-cut 5 4 4 2 2 8 2 6 3 2 2 _ _ 6 2 4 1 _ _ _ _ 4 1 2 _ _ _ _ _ 3 3 1 _ _ _ _ _ _ DONE DONESample Case #01sticks-length length-of-cut sticks-cut 1 2 3 4 3 3 2 1 1 8 _ 1 2 3 2 2 1 _ 1 6 _ _ 1 2 1 1 _ _ 1 4 _ _ _ 1 _ _ _ _ 1 1 _ _ _ _ _ _ _ _ DONE DONE
Programming in C :
#include < stdio.h>
#include < string.h>
#include < math.h>
#include < stdlib.h>
int main() {
int N,*a,i,j,k,min,count=0;
scanf("%d",&N);
a=(int*)malloc(sizeof(int)*N);
for(i=0;i<N;i++)
scanf("%d",&a[i]);
while(1){
min=1000;
for(i=0;i<N;i++)
{
if(a[i]==0)
{
continue;
}
else{
if(min>a[i])
min=a[i];
}
}
count=0;
for(i=0;i<N;i++){
if(a[i]==0)
continue;
else{
a[i]=a[i]-min;
count++;
}
}
if(count==0) break;
printf("%d\n",count);
if(count==1) break;
}
return 0;
}
Wednesday, 10 September 2014
Utopian Tree
Now, a new Utopian tree sapling is planted at the onset of the monsoon. Its height is 1 meter. Can you find the height of the tree after N growth cycles?
The first line contains an integer, T, the number of test cases.
T lines follow. Each line contains an integer, N, that denotes the number of cycles for that test case.
1 <= T <= 10
0 <= N <= 60
For each test case, print the height of the Utopian tree after N cycles.
2
0
1
1
2
There are 2 test cases. When N = 0, the height of the tree remains unchanged. When N = 1, the tree doubles its height as it's planted just before the onset of monsoon.
2
3
4
6
7
There are 2 testcases.
N = 3:
the height of the tree at the end of the 1st cycle = 2
the height of the tree at the end of the 2nd cycle = 3
the height of the tree at the end of the 3rd cycle = 6
the height of the tree at the end of the 4th cycle = 7
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <malloc.h>
int main() {
int T,*N,i,*O,j;
scanf("%d",&T);
N=(int*)malloc(sizeof(int)*T);
O=(int*)malloc(sizeof(int)*T);
for(i=0;i < T;i++)
scanf("%d",&N[i]);
for(i=0;i < T;i++)
{ O[i]=1;
for(j=1;j < =N[i];j++)
{
if(j%2==0)
O[i]=O[i]+1;
else O[i]=2*O[i];
}
}
for(i=0;i < T;i++)
printf("%d\n",O[i]);
return 0;
}
Service Lane
N units. The service lane consists of N segments of unit length, where each segment can have different widths.i and the exit segment as index j. Assume that the exit segment lies after the entry segment(j>i) and i ≥ 0. Calvin has to pass through all segments from index i to indexj (both inclusive).width[] of lengthN, where width[k] represents the width of kth segment of our service lane. It is guaranteed that while servicing he can pass through at most 1000 segments, including entry and exit segments.- If
width[k]is 1, only the bike can pass throughkth segment. - If
width[k]is 2, the bike and car can pass throughkth segment. - If
width[k]is 3, any of the bike, car or truck can pass throughkth segment.
The first line of input contains two integers -
N & T, where N is the length of the freeway, andT is the number of test cases. The next line has N space separated integers which represents the width array.T test cases follow. Each test case contains two integers - i & j, where i is the index of segment through which Calvin enters the service lane and j is the index of the lane segment where he exits.For each test case, print the number that represents the largest vehicle type that can pass through the service lane.
Calvin has to pass through all segments from index
i to indexj (both inclusive).2 <= N <= 100000
1 <= T <= 1000
0 <= i < j < N
2 <= j-i+1 <= min(N,1000)
1 <= width[k] <= 3, where 0 <= k < N
8 5
2 3 1 2 3 2 3 3
0 3
4 6
6 7
3 5
0 7
1
2
3
2
1
Below is the representation of lane.
|HIGHWAY|Lane| -> Width
0: | |--| 2
1: | |---| 3
2: | |-| 1
3: | |--| 2
4: | |---| 3
5: | |--| 2
6: | |---| 3
7: | |---| 3
- (0, 3): Because width[2] = 1, only the bike represented as 1 can pass through it.
- (4, 6): Here the largest allowed vehicle which can pass through the 5th segment is car and for the 4th and 6th segment it's the truck. Hence the largest vehicle allowed in these segments is a car.
- (6, 7): In this example, the vehicle enters at the 6th segment and exits at the 7th segment. Both segments allow even truck to pass through them. Hence truck is the answer.
- (3, 5): width[3] = width[5] = 2. While 4th segment allow the truck, 3rd and 5th allow upto car. So 2 will be the answer here.
- (0, 7): Bike is the only vehicle which can pass through the 2nd segment, which limits the strength of whole lane to 1.
#include < stdio.h >
#include < string.h >
#include < math.h >
#include < stdlib.h >
#include < malloc.h >
int main() {
int N,T,k,*width,**TC,i,j,t,pass,*O;
scanf("%d %d",&N,&T);
width=(int*)malloc(sizeof(int)*N);
O=(int*)malloc(sizeof(int)*T);
for(k=0;k < N;k++)
scanf("%d",&width[k]);
TC=(int**)malloc(sizeof(int*)*T);
for(k=0;k < T;k++)
{
TC[k]=(int*)malloc(sizeof(int)*2);
scanf("%d %d",&TC[k][0],&TC[k][1]);
}
for(t=0;t < T;t++)
{
i=TC[t][0];
j=TC[t][1];
pass=width[i];
for(k=i;k < =j;k++)
{
if(pass > width[k])
pass=width[k];
}
O[t]=pass;
}
for(i=0;i < T;i++)
{
if(O[i] > =3)
printf("%d\n",3);
else
printf("%d\n",O[i]);
}
return 0;
}
Programming Problem from another source website.