Validating user's input while using a while loop - validation

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.

Related

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

Algorithm to divide up linked objects (like contiguous US states) by some metric?

Use case: consider the 50 US states on a map, with each state corresponding to some cost function (i.e., market size). Is there an algorithm (and ideal an R/Python package) that divides the 50 states into N groups such that the variation in the sum of the cost function in each group is minimized? The only constraint is that all states in each group are contiguous (i.e., they form one large mass / connected to each other)
There is a related question with a smaller search space that might possibly be more tractable, or at least easier to code for. Given N groups, pick N states and call them roots. One way to divide states into groups is to say that the group associated with a root is the set of states closer to this root than to any other root. To allow you to fine tune this a bit, have a constant K for each root, and divide up states according to the sum of the distance to the root and the constant K for that root.
Groups created in this way always consist of contiguous states, because if a state is in a group, all of the states on the shortest path from that state to the root of the group are also in that group. If one of them was not in that group, that state would have a shorter path to a different root, which means that the original state would also have a shorter path, via that intermediate state, to the different root, which is a contradiction.
This still isn't a tractable problem, but you call hill-climb on the constants to try and even out the allocations, and you can hill-climb on the choice of roots. If you hill-climb from multiple random starts, you can hope that you will get some decent answers, and you might hope to get an idea of how good your best answer seen so far is by looking at the other hilltops found - I would be optimistic if the best answer seen occurred multiple times.
Here follows some Java with comments trimmed due to limits on bodies
import java.util.ArrayList;
import java.util.Arrays;
import java.awt.BorderLayout;
import java.io.BufferedReader;
import java.util.Collections;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.io.File;
import java.io.FileReader;
import java.awt.Graphics;
import java.util.HashMap;
import java.util.HashSet;
import java.io.IOException;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.awt.Rectangle;
import javax.swing.SwingUtilities;
public class States
{
/** Info held for State */
private static class StateInfo
{
private final String m_name;
/** abbreviation of state - drawn on graph */
private final String m_abbreviation;
private final double m_latitudeDegrees;
private final double m_longitudeDegrees;
private int m_currentX;
private int m_currentY;
/** 0-up number allocated and offset in ArrayList */
private final int m_number;
/** link to neighbouring states */
private final ArrayList m_neighbours =
new ArrayList();
/** colour to print in. Modified when states are grouped */
private Color m_color = Color.BLACK;
/** weight when computing variance */
private double m_weight = 1.0;
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append(m_abbreviation + " color " + m_color);
return sb.toString();
}
public StateInfo(String name, String abbreviation,
double latitudeDegrees, double longitudeDegrees, int number)
{
m_name = name;
m_abbreviation = abbreviation;
m_latitudeDegrees = latitudeDegrees;
m_longitudeDegrees = longitudeDegrees;
m_number = number;
}
public double getLatitudeDegrees()
{
return m_latitudeDegrees;
}
public double getLongitudeDegrees()
{
return m_longitudeDegrees;
}
public String getAbbreviation()
{
return m_abbreviation;
}
public void addNeighbour(StateInfo si)
{
m_neighbours.add(si);
}
public List getNeighbours()
{
return Collections.unmodifiableList(m_neighbours);
}
public void setCurrentPos(int x, int y)
{
m_currentX = x;
m_currentY = y;
}
public int getX()
{
return m_currentX;
}
public int getY()
{
return m_currentY;
}
public int getNumber()
{
return m_number;
}
public Color getColor()
{
return m_color;
}
public void setColor(Color newValue)
{
m_color = newValue;
}
public double getWeight()
{
return m_weight;
}
public void setWeight(double newValue)
{
m_weight = newValue;
}
}
public static class StatePanel extends JPanel
{
#Override
public void paint(Graphics g)
{
Rectangle rect = getBounds();
double minLat = Double.MAX_VALUE;
double maxLat = -Double.MAX_VALUE;
double minLon = Double.MAX_VALUE;
double maxLon = -Double.MAX_VALUE;
for (StateInfo si: m_stateInfo)
{
double lat = si.getLatitudeDegrees();
double lon = si.getLongitudeDegrees();
if (lat maxLat)
{
maxLat = lat;
}
if (lon maxLon)
{
maxLon = lon;
}
}
int numStates = m_stateInfo.size();
double gapAdd = 1.0 / (double)(numStates + 1);
double gapFactor = (numStates - 1) / (double)(numStates + 1);
for (StateInfo si: m_stateInfo)
{
double x = (si.getLongitudeDegrees() - minLon) / (maxLon - minLon);
x = x * gapFactor + gapAdd;
double y = (maxLat - si.getLatitudeDegrees()) / (maxLat - minLat);
y = y * gapFactor + gapAdd;
int xpos = (int)Math.round(rect.x + x * rect.width);
int ypos = (int)Math.round(rect.y + y * rect.height);
g.setColor(si.getColor());
g.drawString(si.getAbbreviation(), xpos, ypos);
si.setCurrentPos(xpos, ypos);
}
g.setColor(Color.BLACK);
for (StateInfo si: m_stateInfo)
{
int xp = si.getX();
int yp = si.getY();
for (StateInfo ti: si.getNeighbours())
{
if (si.getNumber() rows = new ArrayList();
for (;;)
{
String line = br.readLine();
if (line == null)
{
break;
}
int len = line.length();
int l1 = len - 1;
ArrayList cells = new ArrayList();
StringBuilder currentCell = new StringBuilder();
for (int i = 0; i = l1)
{
throw new IllegalArgumentException("Unterminated quote in line " + line);
}
ch = line.charAt(++i);
if (ch != '"')
{
currentCell.append(ch);
continue;
}
if ((i >= l1) || (line.charAt(i + 1) != '"'))
{
break;
}
currentCell.append(ch);
i++;
}
}
if (len > 0)
{
cells.add(currentCell.toString());
}
String[] row = new String[cells.size()];
row = cells.toArray(row);
rows.add(row);
}
String[][] result = new String[rows.size()][];
result = rows.toArray(result);
return result;
}
finally
{
fr.close();
}
}
/** Read locations of states and links between them from file */
public void readLocations(String filename, String linkFile) throws Exception
{
// First two lines of file are
// # State,Latitude,Longitude,Abbreviation,Population
// Alabama,32.806671,-86.79113,AL,4.859
// Population is in millions. File is result of hand-editing together info from web
String[][] data = readCsv(new File(filename));
m_stateInfo = new ArrayList();
m_stateInfoByAbbreviation = new HashMap();
int num = 0;
for (String[] row: data)
{
if (row.length rootOffsetByColor = new HashMap();
for (int i = 0; i reducedWeights[i])
{
reducedWeights[i] = reduced;
}
}
if (secondBest totalByColor = new HashMap();
for (;;)
{
allocateViaDistance(m_roots, initialWeights, m_colors);
double varianceHere = getVariance(totalByColor);
double total = 0.0;
for (Double d: totalByColor.values())
{
total += d.doubleValue();
}
double target = total / m_roots.length;
minimumNecessary(m_roots, initialWeights, m_colors, decrease, increase);
boolean improved = false;
// Don't need to change weight[0] as we can regard everything else as
// compared to that as a standard
for (int i = 1; i totalByColor)
{
totalByColor.clear();
for (StateInfo si: m_stateInfo)
{
Color key = si.getColor();
Double d = new Double(0.0);
if (totalByColor.containsKey(key))
{
d = totalByColor.get(key);
}
totalByColor.put(key, new Double(d.doubleValue() + si.getWeight()));
}
int numUsed = totalByColor.size();
if (numUsed totalByColor = new HashMap();
return getVariance(totalByColor);
}
public StateInfo getState(String abbreviation)
{
return m_stateInfoByAbbreviation.get(abbreviation);
}
public void setColorsRoots(Color[] colors, StateInfo[] roots)
{
m_roots = roots;
m_colors = colors;
}
public StateInfo[] getRoots()
{
return m_roots;
}
public double climbRoots(double[] weights)
{
for (;;)
{
double current = getVariance();
boolean improved = false;
for (int i = 0; i chosen = new HashSet();
m_roots = new StateInfo[weights.length];
for (int j = 0; j m_stateInfo;
private Map m_stateInfoByAbbreviation;
private double[][] m_distances;
private StateInfo[] m_roots;
private Color[] m_colors;
}
/** compute all-pairs distances (Floyd - Warshall) */
public static void allPairs(double[][] distances)
{
int pass = 0;
for (boolean changed = true; changed;)
{
changed = false;
System.err.println("Pass " + (pass++));
for (int i = 0; i totalByColor = new HashMap();
var = sp.getVariance(totalByColor);
System.out.println("Multiple start Climbed to variance " + var);
System.out.println("Roots " + Arrays.toString(sp.getRoots()));
System.out.println("Totals " + totalByColor.values());
}
System.out.println("Allocated result is " + sp.getVariance());
}
catch (Exception ex)
{
System.err.println("Exception setting up: " + ex);
ex.printStackTrace();
return;
}
sp.setPreferredSize(new Dimension(400, 400));
JFrame w = new JFrame();
w.setTitle("States");
Container cp = w.getContentPane();
cp.setLayout(new BorderLayout());
cp.add(sp, BorderLayout.CENTER);
w.pack();
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
w.setVisible(true);
}
};
SwingUtilities.invokeAndWait(r);
}
}
Here's some example code of how you can generate all possible groups of states up to a reasonable number, trick is representing the ith state by two to the power of i. And a group of states is a 64 bit integer with bits corresponding to its states.
data = """AK WA
AL FL
AL GA
AL MS
AL TN
AR LA
AR MO
AR MS
AR OK
AR TN
AR TX
AZ CA
AZ CO
AZ NM
AZ NV
AZ UT
CA HI
CA NV
CA OR
CO KS
CO NE
CO NM
CO OK
CO UT
CO WY
CT MA
CT NY
CT RI
DC MD
DC VA
DE MD
DE NJ
DE PA
FL GA
GA NC
GA SC
GA TN
IA IL
IA MN
IA MO
IA NE
IA SD
IA WI
ID MT
ID NV
ID OR
ID UT
ID WA
ID WY
IL IN
IL KY
IL MO
IL WI
IN KY
IN MI
IN OH
KS MO
KS NE
KS OK
KY MO
KY OH
KY TN
KY VA
KY WV
LA MS
LA TX
MA NH
MA NY
MA RI
MA VT
MD PA
MD VA
MD WV
ME NH
MI OH
MI WI
MN ND
MN SD
MN WI
MO NE
MO OK
MO TN
MS TN
MT ND
MT SD
MT WY
NC SC
NC TN
NC VA
ND SD
NE SD
NE WY
NH VT
NJ NY
NJ PA
NM OK
NM TX
NM UT
NV OR
NV UT
NY PA
NY VT
OH PA
OH WV
OK TX
OR WA
PA WV
SD WY
TN VA
UT WY
VA WV""".splitlines()
edges = [line.split() for line in data]
states = sorted(set([node for pair in edges for node in pair]))
state_map = {}
groups = [set() for _ in range(52)]
neighbours = [[] for _ in range(52)]
for i, state in enumerate(states):
state_map[state] = i
state_map[i] = state
groups[1].add(1 << i)
for a, b in edges:
i, j = state_map[a], state_map[b]
neighbours[i].append(j)
neighbours[j].append(i)
for group_size in range(2, 20):
prev_groups = groups[group_size-1]
print "group size: %d, count: %d" % (group_size - 1, len(prev_groups))
current_groups = groups[group_size]
for group in prev_groups:
for i in range(51):
state = 1 << i
if state & group == 0:
for j in neighbours[i]:
if group & (1 << j) > 0:
current_groups.add(group | (1<<i))
group size: 1, count: 51
group size: 2, count: 111
group size: 3, count: 323
group size: 4, count: 1063
group size: 5, count: 3714
group size: 6, count: 13219
group size: 7, count: 46858
group size: 8, count: 163360
group size: 9, count: 556059
group size: 10, count: 1838076
group size: 11, count: 5873753
group size: 12, count: 18076855
group size: 13, count: 53409207

FCFS inside memory list

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.

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

C#. Search array of strings for longest element

I want to know how I can get out everyone of the the longest persons if there are several with the same length?
If only one person is the longest, then it works fine and the longest person with it´s name will show in MessageBox. But if there are more than one who are the longest, this code will not work...
public partial class Form1 : Form
{
int[] längdArray = new int[5];
string[] namnArray = new string[5];
int namn = 0;
int längd = 0;
public Form1()
{
InitializeComponent();
}
private void btnVisa_Click(object sender, EventArgs e)
{
int längst = 0;
int längdvärdet = 0;
int längdindex = 0;
string name = textBox1.Text;
namnArray[namn] = name;
namn = namn + 1;
textBox1.Clear();
int centimeter = int.Parse(textBox2.Text);
längdArray[längd] = centimeter;
längd++;
textBox2.Clear();
listBox1.Items.Add(name + " " + centimeter + " centimeter ");
if (längd == 5)
{
btnVisa.Enabled = false;
foreach (int antalLängder in längdArray)
{
if (antalLängder > längst)
{
längst = antalLängder;
längdvärdet = längdindex;
}
längdindex++;
}
string test = namnArray[längdvärdet]
MessageBox.Show(" Längsta person är " + test + " som är " + längst + " centimeter lång ");
}
Define behavior you want your app to present when there is more than one person. Should all display, or any one, or other? Try to use object constructions, it's easier to operate on them. C# is an object-oriented language. Put name and length in one structure then use LINQ.

Resources