FCFS inside memory list - job-scheduling

Hi i am new in java programing. I've created a program to allocate 20 block inside 10 memory.
Here's the code
import java.util.*;
import java.io.*;
public class BestFit
{
private int[] job;//f
private int[] memBlock;//b
private int[] jobStatus;
private int[] jobAT;
static private int[] memTaken;
static int[] ff;
private int[] jobCC;
private int[] ArrivalTime;
private int[] waitingTime;
private int[] turnaroundTime;
public BestFit()
{
job = new int[]{5040,4600,1060,1950,6950,6410,2960,3070,2770,7790,5680,9150,7880,3870,7160,8880,4410,6130,6750,2560};
memBlock = new int[]{4400,6200,9300,1000,4200,8200,4600,3700,6300,2900};
memTaken = new int[20];
ff = new int[20];//to store no. of block that used by particular file
jobCC = new int[]{2,8,10,1,10,8,4,2,6,7,1,1,1,8,8,2,5,7,6,7};//cpu cycle
ArrivalTime = new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
waitingTime = new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
turnaroundTime = new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
}
public void BestFitAlgo()
{
int[] frag = new int[25];
int i,j,nb,nf,sizeDifference;
int lowest = 10000;
nf = 20;
nb = 10;
int startTime = 1;
int complete = 1;
int totalTime = 1;
int waitTime;
int tTime = 1;
Arrays.sort(memBlock);
for (i=0;i<nf;i++)
{
if (complete != 20)
{
for (j=0;j<nb;j++)
{
sizeDifference = memBlock[j] - job[i];
if (sizeDifference>=0)
if (lowest>sizeDifference)
{
ff[i] = j;//no of block = j
lowest = sizeDifference;
complete++;
System.out.println("Job: "+i+" is added to block: "+ff[i]+" and being process");
for (int k = 1;k<jobCC[i];k++)
{
startTime++;
}
if(startTime == jobCC[i])
{
waitingTime[i] = tTime - ArrivalTime[i];
turnaroundTime[i] = jobCC[i] + waitingTime[i];
System.out.println("Job: "+i+" is fully processed.Block: "+ff[i]+" is free");
System.out.println("Arrival Time: "+ArrivalTime[i]);
System.out.println("Start time: "+totalTime);
System.out.println("CPU cycle: "+jobCC[i]);
totalTime +=startTime;
startTime = 1;
tTime = totalTime;
System.out.println("Waiting time: "+waitingTime[i]);
System.out.println("Turnaround time: "+turnaroundTime[i]+"\n");
}
}
}
}
frag[i]=lowest;
lowest = 10000;
}
System.out.println("File No:\tFile_Size:\tBlock_No:\tBlock_Size:\tFragment");
for (i=0;i<nf&&ff[i]!=0;i++)
{
System.out.println(i+"\t\t"+job[i]+"\t\t"+ff[i]+"\t\t"+memBlock[ff[i]]+"\t\t"+frag[i]);
}
System.out.println("\nTotal time: "+totalTime);
}
public static void main (String[] args)
{
BestFit b = new BestFit();
b.BestFitAlgo();
}
}
For now the job can be allocated to the memory block by fcfs but the problem now is the next job wont be able to enter the memory list ( where all the block) until the previous job is done. So there are 9 free memory block everytime a job enter.
How do i make it so that job can enter the block simultaneously (with the condition the desired mem block is not occupied and based on arrival time).
I know how fcfs work but that is with only 1 memory block. I've been googling all day trying to find how fcfs work in multiple memory block but no avail.
I hope anyone can help me to understand how it work and maybe a hint on how to implement in in coding.
Thanks in advance
EDIT: i put my code instead so anyone can get a clear view of my problem.

Related

How to measure string interning?

I'm trying to measure the impact of string interning in an application.
I came up with this:
class Program
{
static void Main(string[] args)
{
_ = BenchmarkRunner.Run<Benchmark>();
}
}
[MemoryDiagnoser]
public class Benchmark
{
[Params(10000, 100000, 1000000)]
public int Count { get; set; }
[Benchmark]
public string[] NotInterned()
{
var a = new string[this.Count];
for (var i = this.Count; i-- > 0;)
{
a[i] = GetString(i);
}
return a;
}
[Benchmark]
public string[] Interned()
{
var a = new string[this.Count];
for (var i = this.Count; i-- > 0;)
{
a[i] = string.Intern(GetString(i));
}
return a;
}
private static string GetString(int i)
{
var result = (i % 10).ToString();
return result;
}
}
But I always end up with the same amount of allocated.
Is there any other measure or diagnostic that gives me the memory savings of using string.Intern()?
The main question here is what kind of impact do you want to measure? To be more specific: what are your target metrics? Here are some examples: performance metrics, memory traffic, memory footprint.
In the BenchmarkDotNet Allocated column, you get the memory traffic. string.Intern doesn't help to optimize it in your example, each (i % 10).ToString() call will allocate a new string. Thus, it's expected that BenchmarkDotNet shows the same numbers in the Allocated column.
However, string.Intern should help you to optimize the memory footprint of your application at the end (the total managed heap size, can be fetched via GC.GetTotalMemory()). It can be verified with a simple console application without BenchmarkDotNet:
using System;
namespace ConsoleApp24
{
class Program
{
private const int Count = 100000;
private static string[] notInterned, interned;
static void Main(string[] args)
{
var memory1 = GC.GetTotalMemory(true);
notInterned = NotInterned();
var memory2 = GC.GetTotalMemory(true);
interned = Interned();
var memory3 = GC.GetTotalMemory(true);
Console.WriteLine(memory2 - memory1);
Console.WriteLine(memory3 - memory2);
Console.WriteLine((memory2 - memory1) - (memory3 - memory2));
}
public static string[] NotInterned()
{
var a = new string[Count];
for (var i = Count; i-- > 0;)
{
a[i] = GetString(i);
}
return a;
}
public static string[] Interned()
{
var a = new string[Count];
for (var i = Count; i-- > 0;)
{
a[i] = string.Intern(GetString(i));
}
return a;
}
private static string GetString(int i)
{
var result = (i % 10).ToString();
return result;
}
}
}
On my machine (Linux, .NET Core 3.1), I got the following results:
802408
800024
2384
The first number and the second number are the memory footprint impacts for both cases. It's pretty huge because the string array consumes a lot of memory to keep the references to all the string instances.
The third number is the footprint difference between the footprint impact of interned and not-interned string. You may ask why it's so small. This can be easily explained: Stephen Toub implemented a special cache for single-digit strings in dotnet/coreclr#18383, it's described in his blog post:
So, it doesn't make sense to measure interning of the "0".."9" strings on .NET Core. We can easily modify our program to fix this problem:
private static string GetString(int i)
{
var result = "x" + (i % 10).ToString();
return result;
}
Here are the updated results:
4002432
800344
3202088
Now the impact difference (the third number) is pretty huge (3202088). It means that interning helped us to save 3202088 bytes in the managed heap.
So, there are the most important recommendation for your future experiments:
Carefully define metrics that you actually want to measure. Don't say "I want to find all kinds of affected metrics," any changes in the source code may affect hundreds of different metrics; it's pretty hard to measure all of them in each experiment. Carefuly think about what kind of metrics are really important for you.
Try to take the input data that are close to your actual work scenarios. Benchmarking with some "dummy" data may leads to incorrect results because there are too many tricky optimizations in runtime that works pretty well with such "dummy" cases.

How do I change the speed of an AnimationTimer in JavaFX?

I'm trying to change the speed of an AnimationTimer so the code runs slower, here is the code I have so far:
AnimationTimer timer = new AnimationTimer() {
#Override
public void handle(long now) {
if (upOrDown != 1) {
for (int i = 0; i < 4; i++) {
snakePositionDown[i] = snake[i].getX();
snakePositionDownY[i] = snake[i].getY();
}
snake[0].setY(snake[0].getY() + 25);
for (int i = 1; i < 4; i++) {
snake[i].setX(snakePositionDown[i - 1]);
snake[i].setY(snakePositionDownY[i - 1]);
}
leftOrRight = 2;
upOrDown = 0;
}
}
};
timer.start();
How would I make the AnimationTimer run slower?
Thanks in advance!
You could use a Timeline for this purpose. Adjusting the Timeline.rate property also allows you to update the "speed":
// update once every second (as long as rate remains 1)
Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), event -> {
if (upOrDown != 1) {
for (int i = 0; i < 4; i++) {
snakePositionDown[i] = snake[i].getX();
snakePositionDownY[i] = snake[i].getY();
}
snake[0].setY(snake[0].getY() + 25);
for (int i = 1; i < 4; i++) {
snake[i].setX(snakePositionDown[i - 1]);
snake[i].setY(snakePositionDownY[i - 1]);
}
leftOrRight = 2;
upOrDown = 0;
}
}));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
...
// double speed
timeline.setRate(2);
An AnimationTimer's handle() method is invoked on every "pulse" - i.e., every time a frame is rendered. By default, the JavaFX toolkit will attempt to do this 60 times per second, but that is not in any way guaranteed. It can be changed by setting a system property, and it is possible that future versions of JavaFX will attempt to execute pulses more frequently. If the FX Application Thread has a large amount of work to do, then pulses may occur less frequently than the target rate. Consequently, the code in your handle() method needs to account for the amount of time since the last update.
The parameter passed to the handle(...) method represents the current system time in nanoseconds. So a typical way to approach this is:
AnimationTimer h = new AnimationTimer() {
private long lastUpdate; // Last time in which `handle()` was called
private double speed = 50 ; // The snake moves 50 pixels per second
#Override
public void start() {
lastUpdate = System.nanoTime();
super.start();
}
#Override
public void handle(long now) {
long elapsedNanoSeconds = now - lastUpdate;
// 1 second = 1,000,000,000 (1 billion) nanoseconds
double elapsedSeconds = elapsedNanoSeconds / 1_000_000_000.0;
// ...
snake[0].setY(snake[0].getY() + elapsedSeconds * speed);
// ...
lastUpdate = now;
}
}

Class is taking more computation time if the same input is given over and over

I am working on an algorithm and it seems to be working fine, apart from one thing.
Let me first show you the code and then I will explain what the code does and what the problem is.
public Triple<List<ROUTE>, Integer, List<Customer>> LocalSearch()
{
int noImprLS = 0;
boolean initialization = false;
List<ROUTE> bestRoutes = startRoutes;
int bestProfit = profit;
List<Customer> bestU = u;
List<ROUTE> tempBestRoutes = startRoutes;
int tempBestProfit = profit;
List<Customer> tempBestU = u;
int tempBestDistance = totalDistance(tempBestRoutes);
ELIMINATOR e = new ELIMINATOR(bestU, bestRoutes, bestProfit, initialization, name, rnd);
while (noImprLS <= noImprUB)
{
System.out.print(noImprLS);
boolean improvement = false;
long starttime = System.nanoTime();
double timeE = 0;
for (int i = 1; i <= N; i++)
{
long starttimeE = System.nanoTime();
e = new ELIMINATOR(bestU, bestRoutes, bestProfit, initialization, name, rnd);
timeE = timeE + (System.nanoTime()-starttimeE)/1000000000.0;
POSTPROCEDURE pp = new POSTPROCEDURE(e.getRoutes(), profitRoutes(e.getRoutes()), e.getU(), name);
for (int p = 0; p < pp.getBestSolution().size(); p++)
{
ROUTE r = pp.getBestSolution().get(p);
addToPOOL(r);
}
int tempprofit = pp.getTP();
int tempdistance = pp.getTD();
if (tempprofit > tempBestProfit)
{
tempBestRoutes = pp.getBestSolution();
tempBestProfit = tempprofit;
tempBestU = pp.getU();
tempBestDistance = tempdistance;
}
else if (tempprofit == tempBestProfit)
{
if (tempdistance < tempBestDistance)
{
tempBestRoutes = pp.getBestSolution();
tempBestProfit = tempprofit;
tempBestU = pp.getU();
tempBestDistance = tempdistance;
}
}
}
if (tempBestProfit > bestProfit)
{
// Move to better neighbor
bestRoutes = tempBestRoutes;
bestProfit = tempBestProfit;
bestU = tempBestU;
noImprLS = 0;
improvement = true;
System.out.print(" total profit: " + bestProfit);
}
else if (tempBestProfit == bestProfit)
{
if (totalDistance(tempBestRoutes) < totalDistance(bestRoutes))
{
// Move to better neighbor
bestRoutes = tempBestRoutes;
bestProfit = tempBestProfit;
bestU = tempBestU;
noImprLS = 0;
improvement = true;
System.out.print(" total profit: " + bestProfit + " total distance: " + totalDistance(bestRoutes));
}
}
if (improvement == false)
{
noImprLS++;
}
long endtime = System.nanoTime();
double duration = (endtime - starttime)/1000000000.0;
System.out.print(" duration: " + duration + " timeE: " + timeE + "\n");
}
Explanation
I know that the code is quite lengthy, but it is all quite important. In this code, I am writing an algorithm for the Team Orienteering Problem with Time Windows (extensive case of the Vehicle Routing Problems). My aim is to find a good set of routes with maximum profit. In the example below, bestRoutes and tempBestRoutes consist of 4 different routes, profit (bestProfit/tempBestProfit) is equal to the total profit of these routes respectively, and (temp)bestU is a list of customers that are not included in my route yet.
The problem now is with ELIMINATOR. This method removes and adds some customers. The output of this class is used for PostProcedure that also changes some facts in the routes.
I hope it is kind of clear now what my code is doing. I am considering N neighbourhoods and I will choose the best one. If the best one is not better than my starting solution, I increase noImprLS with one. I keep on considering new nieghbours until my upperbound on the number of consecutive iterations without improvement is met.
Problem
The problem now is that if I have not found a better solution, and hence I keep on inserting the same routes and profit in ELIMINATOR, my computation time increases.
A few examples where duration indicates how long an iteration within the while loop takes, and timeE indicates what the total time of ELIMINATOR in the for loop is. It is clear that ELIMINATOR causees the duration to increase.
0 total profit: 800 duration: 0.486570471 timeE: 0.16644330999999998
0 total profit: 900 duration: 0.431213528 timeE: 0.11342619799999998
0 total profit: 950 duration: 0.444671005 timeE: 0.12090608200000001
0 total profit: 960 duration: 0.519406695 timeE: 0.16836757300000005
0 duration: 0.460473438 timeE: 0.137813155
1 duration: 0.572109775 timeE: 0.30774360900000003
2 duration: 0.698965292 timeE: 0.471859029
3 duration: 0.918376211 timeE: 0.686916669
4 duration: 1.165481175 timeE: 0.92621492
5 duration: 1.326080436 timeE: 1.0874366910000002
6 duration: 2.006102605 timeE: 1.674879135
7 duration: 2.787172112 timeE: 2.4276636639999993
8 duration: 2.042213493 timeE: 1.7967797849999998
9 duration: 2.652985618 timeE: 2.3503671230000003
10 duration: 2.422183993 timeE: 2.1859969810000006
The ELIMINATOR CODE:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
public class ELIMINATOR extends BASIS
{
private List<Customer> u;
private List<ROUTE> routes;
private int totalprofit;
private Random prob;
public ELIMINATOR(List<Customer> u, List<ROUTE> routes, int profit, boolean initialization, String name, Random rnd)
{
super(name);
this.u = u;
this.routes = routes;
this.totalprofit = profit;
this.prob = rnd;
if (initialization == true)
{
addCustomers();
for (ROUTE route : routes)
{
checkCorrectNess(route, "after adding procedure in eliminator");
}
}
else
{
removeCustomers();
for (ROUTE route : routes)
{
checkCorrectNess(route, "after removing procedure in eliminator");
}
addCustomers();
for (ROUTE route : routes)
{
checkCorrectNess(route, "after removing and adding procedure in eliminator");
}
}
}
public void removeCustomers()
{
double Ph = 0.1;
double Pl = 0.3;
double total_profit = totalprofit;
int num_customers = 0;
// Calculate the total profit and total number of customers in the routes
for(ROUTE route : routes)
{
num_customers = num_customers + (route.getLocations().size()-2);
}
// Calculate average profit
double average_profit = total_profit/num_customers;
// For each customer on each route, determine whether he/she will be removed
for(ROUTE r : routes)
{
List<RouteNode> route = r.getLocations();
int routesize = route.size();
int j = 1;
while (j < routesize-1)
{
boolean removed = false;
RouteNode node = route.get(j);
if (node.customer.getProfit() >= average_profit)
{
if (prob.nextDouble() < Ph)
{
removed = true;
RouteNode node_toberemoved = node;
int index_node = route.indexOf(node);
route.remove(index_node);
u.add(node.customer);
route = removal(route, node_toberemoved, index_node);
r.setLocations(route);
r.setDistance(distanceOneRoute(route));
r.setProfit(profitOneRoute(route));
checkCorrectNess(r, "remove customers eliminator");
}
}
else
{
if (prob.nextDouble() < Pl)
{
removed = true;
RouteNode node_toberemoved = node;
int index_node = route.indexOf(node);
route.remove(index_node);
u.add(node.customer);
route = removal(route, node_toberemoved, index_node);
r.setLocations(route);
r.setDistance(distanceOneRoute(route));
r.setProfit(profitOneRoute(route));
checkCorrectNess(r, "remove customers eliminator");
}
}
if (removed == false)
{
j++;
}
else
{
routesize = route.size();
total_profit = total_profit-node.customer.getProfit();
average_profit = total_profit/num_customers;
}
}
}
totalprofit = profitRoutes(routes);
}
public void addCustomers()
{
List<Customer> u_copy = new ArrayList<Customer>(u);
List<Customer> u_temp = new ArrayList<Customer>(u);
for (Customer c : u_temp)
{
boolean added = false;
for (ROUTE r : routes)
{
checkCorrectNess(r, "add customers eliminator");
if (added == true)
{
break;
}
Customer customer = c;
u_copy.remove(c);
List<RouteNode> route = r.getLocations();
for (int i = 0; i < route.size()-1; i++)
{
RouteNode possibleNode = new RouteNode();
possibleNode.customer = customer;
List<Integer> distances = calculateDistances(route.get(i), possibleNode, route.get(i+1));
// Calculate shift for customer under consideration
int arrivalTime = route.get(i).timeStartService+ route.get(i).customer.getService() + distances.get(0);
int wait = Math.max(0, customer.getOpeningTW()-arrivalTime);
int serviceDuration = customer.getService();
int shift = distances.get(0) + wait + serviceDuration + distances.get(2) - distances.get(1);
// Determine Start Service
int startServiceTime = Math.max(customer.getOpeningTW(), arrivalTime);
// Obtain waiting time of next customer
int waiting_next = route.get(i+1).wait;
// Obtain MaxShift of next customer
int maxShift = route.get(i+1).maxShift;
if (shift <= (waiting_next + maxShift) & startServiceTime <= customer.getClosingTW() )
{
// Customer can be inserted
added = true;
RouteNode newNode = new RouteNode();
newNode.customer = customer;
newNode.arrivalTime = arrivalTime;
newNode.timeStartService = startServiceTime;
newNode.shift = shift;
newNode.wait = wait;
int pos_insertion = i + 1;
route = ADD(route, newNode, pos_insertion);
r.setLocations(route);
r.setDistance(distanceOneRoute(route));
r.setProfit(profitOneRoute(route));
checkCorrectNess(r, "add customers eliminator");
// exit the last for loop
break;
}
}
}
if (added == false)
{
u_copy.add(c);
}
}
u = u_copy;
totalprofit = profitRoutes(routes);
}
/**
* Returns list of unvisited customers
* #return
*/
public List<Customer> getU()
{
return u;
}
/**
* Returns list of routes
* #return
*/
public List<ROUTE> getRoutes()
{
return routes;
}
}

Validating user's input while using a while loop

My issue is that I'm trying to validate my input by making sure that the while loop only takes a number more than 10. If not, they have to try again. But the issue I'm having is that the loop keeps repeating itself if I close the while loop.
import java.util.Scanner;
/**
* #(#)Hotel_Occupancy.java
*
* Hotel_Occupancy application
*
* #author
* #version 1.00 2013/10/28
*/
public class Hotel_Occupancy {
public static void main(String[] args) {
//Declare Variables
int floors;
int rooms;
int roomsOccupied;
int roomsVacant;
int occupancyRate;
//Create Scanner Object
Scanner keyboard = new Scanner(System.in);
//Ask user for # of floors
System.out.print("Enter floors? Input number more than 1. ");
floors = keyboard.nextInt();
while (floors < 1 && floors != 10 )
{
System.out.println("ENTER VALID NUMBER.");
System.out.println("Enter floors? Input number more than 1. ");
System.;
//Create loop with floor iteration
for (rooms = 1; rooms <= floors; rooms++)
{
System.out.println("How many rooms? ");
rooms = keyboard.nextInt();
}
for (roomsOccupied = 1; roomsOccupied <= rooms; roomsOccupied++)
{
System.out.println("How many rooms occupied? ");
roomsOccupied = keyboard.nextInt();
roomsVacant = rooms - roomsOccupied;
System.out.println("Rooms Vacant" + roomsVacant);
}
//Calculate Occupancy Rate
occupancyRate = roomsOccupied + rooms;
System.out.println("Occupancy rate is " + occupancyRate);
}
}
}
while(floor >=10){
// Do whatever you want
}
Go through this basic while loop tutorial.

How to execute multiple tests in one method?

I'm new to the Visual Studio Unit Testing Framework. I've dabbled a little in XUnit, though (DUnit to be specific).
I don't know why the following tests are failing. Based on my C# code (exhibit A), I would think my tests (exhibit B) would pass with the proverbial flying colors.
[EXHIBIT A - Pertinent code]
public class MessageClass
{
private int _messageTypeCode = 0;
private int _messageTypeSubcode;
private int _messageSequenceNumber;
private string _messageText;
public MessageClass()
{
this._messageTypeCode = 0;
this._messageTypeSubcode = 0;
this._messageSequenceNumber = 0;
this._messageText = string.Empty;
}
public void SetMessageTypeSubcode(int AMessageTypeSubcode)
{
int iMsgTypeSubCode = AMessageTypeSubcode;
if (iMsgTypeSubCode > 9999)
{
iMsgTypeSubCode = 9999;
}
else if (iMsgTypeSubCode < 0)
{
iMsgTypeSubCode = 42;
}
_messageTypeSubcode = AMessageTypeSubcode;
}
public int MessageTypeSubcode()
{
return _messageTypeSubcode;
}
[EXHIBIT B - Test code in the corresponding MessageClassTest]
[TestMethod()]
public void SetMessageTypeSubcodeTest()
{
int AMessageTypeSubcode;
// Should I put this class instantiation in MyTestInitialize?
MessageClass target = new MessageClass();
// Test 1
AMessageTypeSubcode = 0;
target.SetMessageTypeSubcode(AMessageTypeSubcode);
Assert.AreEqual(AMessageTypeSubcode, target.MessageTypeSubcode());
// Test 2 - 10000 is too much
AMessageTypeSubcode = 12345;
target.SetMessageTypeSubcode(AMessageTypeSubcode);
Assert.AreEqual(9999, target.MessageTypeSubcode());
// Test 3 - val must be positive
AMessageTypeSubcode = -77;
target.SetMessageTypeSubcode(AMessageTypeSubcode);
Assert.AreEqual(42, target.MessageTypeSubcode());
}
... It is failing on the second test. Having set the val higher than the cutoff (9999), it should be assigned that (9999) rather than 12345.
As I said, I'm new to Visual Studio Unit Testing Framework; is it not possible to have more than one test in a TestMethod? Or do I need to do something like call flush() or finish() or close() or reset() or something?
The tests are failing because the test should fail. Your method is incorrect:
_messageTypeSubcode = AMessageTypeSubcode;
Should be:
_messageTypeSubcode = iMsgTypeSubCode ;

Resources