3
\$\begingroup\$

I wrote implementation of LRU in java and want to know if it can be improved further both in space and time complexity.

Input: Number of frames and reference string for pages.

Output: Number of page faults.

Also I am a little skeptical about its correctness because I got 6/10 in my practical lab.

Kindly ignore OOP's aspect of the program.

import java.util.*;
import java.io.*;
class Lru
{
 private static ArrayList<Integer> arl=new ArrayList<Integer>();
 private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 public static void main(String []args)throws IOException 
 {
 String [] arr;int n,f,pf=0;
 System.out.println("enter the number of frames");
 n=Integer.parseInt(br.readLine());
 System.out.println("enter the reference string");
 arr = br.readLine().split(" ");
 for(String s:arr)
 {
 f=Integer.parseInt(s);
 if(arl.size()<n)
 { ++pf;arl.add(f);}
 else if(arl.contains(f))
 {
 arl.remove(arl.indexOf(f));
 arl.add(f);
 }
 else { arl.remove(0); arl.add(f);++pf;}
 }
 System.out.println("the total no of page faults are "+pf);
 }
}
asked Oct 25, 2015 at 17:54
\$\endgroup\$
0

2 Answers 2

4
\$\begingroup\$

Bug

If the input consisted of the same page number over and over, your program would return multiple faults instead of 1, because you made this condition be first:

 if(arl.size()<n)
 { ++pf;arl.add(f);}

You should switch the first and second conditions:

 if(arl.contains(f)) {
 arl.remove(arl.indexOf(f));
 arl.add(f);
 } else if(arl.size()<n) {
 ++pf;
 arl.add(f);
 } else {
 arl.remove(0);
 arl.add(f);
 ++pf;
 }
answered Oct 25, 2015 at 18:48
\$\endgroup\$
0
3
\$\begingroup\$

Awful formatting and naming conventions, it is extremely difficult to follow the logic in your code.

  • Use more descriptive names like - pageFaults instead of pf
  • Declare variables each on separate line
  • Wrap logic with curly brackets on separate lines
  • Add comments to lines which are not clear what are you doing - to make it readable and maybe you even find the issues (if there are any) by yourself.
answered Oct 25, 2015 at 19:52
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.