MOSS Scheduling Simulator (First in Last out) Algorithm - java

I am trying to figure out how to implement a First in Last out Algorithm for the given java class and I am slightly confused about how to approach the problem.
import java.util.Vector;
import java.io.*;
public class SchedulingAlgorithm {
public static Results Run(int runtime, Vector processVector, Results result) {
int i = 0;
int comptime = 0;
int currentProcess = 0;
int previousProcess = 0;
int size = processVector.size();
int completed = 0;
String resultsFile = "Summary-Processes";
result.schedulingType = "Batch (Nonpreemptive)";
result.schedulingName = "First-Come First-Served";
try {
//BufferedWriter out = new BufferedWriter(new FileWriter(resultsFile));
//OutputStream out = new FileOutputStream(resultsFile);
PrintStream out = new PrintStream(new FileOutputStream(resultsFile));
sProcess process = (sProcess) processVector.elementAt(currentProcess);
out.println("Process: " + currentProcess + " registered... (" + process.cputime + " " + process.ioblocking + " " + process.cpudone + " " + process.cpudone + ")");
while (comptime < runtime) {
if (process.cpudone == process.cputime) {
completed++;
out.println("Process: " + currentProcess + " completed... (" + process.cputime + " " + process.ioblocking + " " + process.cpudone + " " + process.cpudone + ")");
if (completed == size) {
result.compuTime = comptime;
out.close();
return result;
}
for (i = 0; i < size + 1; i++) {
process = (sProcess) processVector.elementAt(i);
if (process.cpudone < process.cputime) {
currentProcess = i;
}
}
process = (sProcess) processVector.elementAt(currentProcess);
out.println("Process: " + currentProcess + " registered... (" + process.cputime + " " + process.ioblocking + " " + process.cpudone + " " + process.cpudone + ")");
}
if (process.ioblocking == process.ionext) {
out.println("Process: " + currentProcess + " I/O blocked... (" + process.cputime + " " + process.ioblocking + " " + process.cpudone + " " + process.cpudone + ")");
process.numblocked++;
process.ionext = 0;
previousProcess = currentProcess;
for (i = size - 1; i >= 0; i--) {
process = (sProcess) processVector.elementAt(i);
if (process.cpudone < process.cputime && previousProcess != i) {
currentProcess = i;
}
}
process = (sProcess) processVector.elementAt(currentProcess);
out.println("Process: " + currentProcess + " registered... (" + process.cputime + " " + process.ioblocking + " " + process.cpudone + " " + process.cpudone + ")");
}
process.cpudone++;
if (process.ioblocking > 0) {
process.ionext++;
}
comptime++;
}
out.close();
} catch (IOException e) { /* Handle exceptions */ }
result.compuTime = comptime;
return result;
}
}
The goal of the new algorithm is to change the output of the processes file so that process 2 is processed first, followed process 1 and 0. The issue is that I cannot seem to find any written examples of a (First in Last out) scheduling Algorithm.
I have tried to modify the for loops in the algorithm to include a stack.push() for the currentprocess. currentprocess in this case, I believe is the value that indicates what process # is being evaluated by the program to print out the summary-results file like so.
for (i = size - 1; i >= 0; i--) {
process = (sProcess) processVector.elementAt(i);
if (process.cpudone < process.cputime && previousProcess != i) {
currentProcess = i;
stack.push(currentProcess)
}
}
Unfortunately, the results will still look like this. And the processes will always output and complete 0 first in the scheduling.
Scheduling Type: Batch (Nonpreemptive)
Scheduling Name: First-Come First-Served
Simulation Run Time: 2955
Mean: 1100
Standard Deviation: 510
Process # CPU Time IO Blocking CPU Completed CPU Blocked
0 639 (ms) 30 (ms) 639 (ms) 21 times
1 1158 (ms) 30 (ms) 1158 (ms) 38 times
2 1158 (ms) 30 (ms) 1158 (ms) 38 times
If you have anymore questions please let me know, as I am trying to rapidly complete this assignment. I will be thankful for any advice I could receive regarding this problem.

Related

Trying to mimic Splitwise app logic - suggest a better way to handle settlements

I am trying to write the basic logic used in apps like Splitwise.
Input - Transactions in the trip
a|a,b,c,d|120
b|a,b,d|210
c|a,b,c,d|40
a|a,b,c|60
a, b, c and d are friends on a trip
in the first transaction a paid 120 units for a transaction involving all four friends
in the second transaction b paid 210 units for a transaction involving only a, b and d
there are n such transactions and there can be m friends
Expected Output
a has to get 50
b has to get 80
c has to give 20
d has to give 110
d has to give 80 to b
d has to give 30 to a
c has to give 20 to a
This is what I tried. Person class is the pojo used.
public class Person {
private String name;
private Integer totalExpense;
private Integer totalSpent;
private Integer balanceAmt;
}
This is the code for settle operation.
public void settle(Map<String, Person> personMap) {
List<Person> getterList = new ArrayList<>();
List<Person> giversList = new ArrayList<>();
for (String key : personMap.keySet()) {
Person user = personMap.get(key);
int balanceAmt = user.getTotalSpent() - user.getTotalExpense();
user.setBalanceAmt(Math.abs(balanceAmt));
if (balanceAmt > 0) {
System.out.println(key + " has to get " + balanceAmt);
getterList.add(user);
} else if (balanceAmt < 0) {
System.out.println(key + " has to give " + Math.abs(balanceAmt));
giversList.add(user);
} else if (balanceAmt == 0) {
System.out.println(key + " is all settled");
}
}
getterList.sort((p2, p1) -> p1.getBalanceAmt().compareTo(p2.getBalanceAmt()));
giversList.sort((p2, p1) -> p1.getBalanceAmt().compareTo(p2.getBalanceAmt()));
giversList.forEach(giver -> {
getterList.forEach(getter -> {
if (getter.getBalanceAmt() == 0) {
return;
}
if (giver.getBalanceAmt() == getter.getBalanceAmt()) {
System.out.println(giver.getName() + " has to give " + giver.getBalanceAmt() + " to " + getter.getName());
giver.setBalanceAmt(0);
getter.setBalanceAmt(0);
} else if (giver.getBalanceAmt() > getter.getBalanceAmt()) {
System.out.println(giver.getName() + " has to give " + getter.getBalanceAmt() + " to " + getter.getName());
giver.setBalanceAmt(giver.getBalanceAmt() - getter.getBalanceAmt());
getter.setBalanceAmt(0);
} else if (giver.getBalanceAmt() < getter.getBalanceAmt()) {
System.out.println(giver.getName() + " has to give " + giver.getBalanceAmt() + " to " + getter.getName());
giver.setBalanceAmt(0);
getter.setBalanceAmt(getter.getBalanceAmt() - giver.getBalanceAmt());
}
});
});
}
The code is not good, it has too many loops.
Suggest a good method to settle the amount and come up with the second part of the output.
Reduce your bottom part's logic from O(m2) to O(m) by using two pointer.
int giverPointer = 0;
int getterPointer = 0;
while(giverPointer < giversList.size() && getterPointer < getterList.size()){
if (giversList.get(giverPointer).getBalanceAmt() == getterList.get(getterPointer).getBalanceAmt()) {
System.out.println(giversList.get(giverPointer).getName() + " has to give " + giversList.get(giverPointer).getBalanceAmt() + " to " + getterList.get(getterPointer).getName());
giversList.get(giverPointer).setBalanceAmt(0);
getterList.get(getterPointer).setBalanceAmt(0);
giverPointer++;
getterPointer++;
} else if (giversList.get(giverPointer).getBalanceAmt() > getterList.get(getterPointer).getBalanceAmt()) {
System.out.println(giversList.get(giverPointer).getName() + " has to give " + getterList.get(getterPointer).getBalanceAmt() + " to " + getterList.get(getterPointer).getName());
giversList.get(giverPointer).setBalanceAmt(giversList.get(giverPointer).getBalanceAmt() - getterList.get(getterPointer).getBalanceAmt());
getterList.get(getterPointer).setBalanceAmt(0);
getterPointer++;
} else {
System.out.println(giversList.get(giverPointer).getName() + " has to give " + giversList.get(giverPointer).getBalanceAmt() + " to " + getterList.get(getterPointer).getName());
giversList.get(giverPointer).setBalanceAmt(0);
getterList.get(getterPointer).setBalanceAmt(getterList.get(getterPointer).getBalanceAmt() - giversList.get(giverPointer).getBalanceAmt());
giverPointer++;
}
}

why does the following keep returning an out of bounds error?

Please help my figure out why this keeps throwing an out of bounds error. i tried making a separate loop keep track of AdminDecisions
String returnProfile() {
String uniPicksString ="";
String studentInfo = null;
//for(int i = 0; i<ApplicantArray.size(); i++) {
studentInfo =FAMILYNAME+ ", " + "average = " + AVERAGE + " ";
for (int j = 0; j<CHOICES.size(); j++) {
if(j<CHOICES.size() - 1) {
uniPicksString = uniPicksString + CHOICES.get(j)+ ": " + " admin decision, " ;
}else {
uniPicksString = uniPicksString + CHOICES.get(j)+ ": " + " admin decision" + "\n";
}
}
//}
return studentInfo + uniPicksString + "\n";
}
the following code shows the desired out put but i cant return it as a string
String printProof() {
// System.out.println("from inside the student class");
String temp=null;
d = new ArrayList<String>();
for(int j = 0 ; j<1; j++) {
System.out.print("\n >>printProof<< " + FAMILYNAME+", " + "average = " + AVERAGE + " ");
for (int i = 0; i<AdminDecision.size(); i++) {
//System.out.println(AdminDecision.get(i));
//temp = CHOICES.get(i)+ ": " + AdminDecision.get(i) + ", ";
if(i<CHOICES.size() - 1) {
temp = CHOICES.get(i)+ ": " + AdminDecision.get(i) + ", ";
}else {
temp = CHOICES.get(i)+ ": " + AdminDecision.get(i) + "\n";
}
System.out.print(temp + " ");
d.add(AdminDecision.get(i));
}
}
return temp + "\n";
}

Working with BigIntegers

I creating a program where it takes a base unit in the metric system. (Say grams.) And then when you select a prefix changes it to the equivalent amount. (Such as 1000 grams when you select Kilo would change it to 1 Kilogram.)
Problem is when I run the code it'll always end up as zero, which makes me think I'm manipulating the BigIntegers wrong. (I'm using VERY large numbers due to some prefixes being very small or very large beyond the usual long number.)
Here is the code:
import java.util.Scanner;
import java.math.BigInteger;
public class BaseMetricUnits {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello, World!");
float meter = 1;
float kilogram = 1;
float second = 1;
float ampere = 1;
float kelvin = 1;
float mole = 1;
float candela = 1;
PrefixConverter();
}
public static void PrefixConverter()
{
BigInteger Yocto = BigInteger.valueOf((long) 0.00000000000000000000000);
BigInteger Zepto = BigInteger.valueOf((long) 0.000000000000000000001);
BigInteger Atto = BigInteger.valueOf((long) 0.000000000000000001);
BigInteger Femto = BigInteger.valueOf((long) 0.000000000000001);
BigInteger Pico = BigInteger.valueOf((long)0.000000000001);
BigInteger Nano = BigInteger.valueOf((long)0.000000001);
BigInteger Micro = BigInteger.valueOf((long)0.000001);
BigInteger Milli = BigInteger.valueOf((long)0.001);
BigInteger Centi = BigInteger.valueOf((long)0.01);
BigInteger Deci = BigInteger.valueOf((long)0.1);
BigInteger Deca = BigInteger.valueOf((long)10);
BigInteger Hecto = BigInteger.valueOf((long)100);
BigInteger Kilo = BigInteger.valueOf((long)1000);
BigInteger Mega = BigInteger.valueOf((long)1000000);
BigInteger Giga = BigInteger.valueOf((long)1000000000);
BigInteger Tera = new BigInteger("1000000000000");
BigInteger Peta = new BigInteger("1000000000000000");
BigInteger Exa = new BigInteger("1000000000000000000");
BigInteger Zetta = new BigInteger("1000000000000000000000");
BigInteger Yotta = new BigInteger("1000000000000000000000000");
long Amount;
double Prefix;
String Units = "";
BigInteger translatedResult;
BigInteger Result;
Scanner inputDevice = new Scanner(System.in);
System.out.print("Please enter the type of unit to be used. (meters, grams, etc.) >> ");
Units = inputDevice.next();
System.out.print("Please enter an amount to be translated >> ");
Amount = inputDevice.nextLong();
System.out.print("Please choose one of the following Prefixes to translate to. ");
System.out.print(" 1 - Yocto ");
System.out.print(" 2 - Zepto ");
System.out.print(" 3 - Atto ");
System.out.print(" 4 - Femto ");
System.out.print(" 5 - Pico ");
System.out.print(" 6 - Nano ");
System.out.print(" 7 - Micro ");
System.out.print(" 8 - Milli ");
System.out.print(" 9 - Centi ");
System.out.print(" 10 - Deci ");
System.out.print(" 11 - Deca ");
System.out.print(" 12 - Hecto ");
System.out.print(" 13 - Kilo ");
System.out.print(" 14 - Mega ");
System.out.print(" 15 - Giga ");
System.out.print(" 16 - Tera ");
System.out.print(" 17 - Peta ");
System.out.print(" 18 - Exa ");
System.out.print(" 19 - Zetta ");
System.out.print(" 20 - Yotta ") ;
Prefix = inputDevice.nextDouble();
if(Prefix == 1)
{
Result = Yocto.multiply(BigInteger.valueOf(Amount));
translatedResult = Yocto.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Yocto" + Units + ".");
}
if(Prefix == 2)
{
Result = Zepto.multiply(BigInteger.valueOf(Amount));
translatedResult = Zepto.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Zepto" + Units + ".");
}
if(Prefix == 3)
{
Result = Atto.multiply(BigInteger.valueOf(Amount));
translatedResult = Atto.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Atto" + Units + ".");
}
if(Prefix == 4)
{
Result = Femto.multiply(BigInteger.valueOf(Amount));
translatedResult = Femto.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Femto" + Units + ".");
}
if(Prefix == 5)
{
Result = Pico.multiply(BigInteger.valueOf(Amount));
translatedResult = Pico.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Pico" + Units + ".");
}
if(Prefix == 6)
{
Result = Nano.multiply(BigInteger.valueOf(Amount));
translatedResult = Nano.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Nano" + Units + ".");
}
if(Prefix == 7)
{
Result = Micro.multiply(BigInteger.valueOf(Amount));
translatedResult = Micro.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Micro" + Units + ".");
}
if(Prefix == 8)
{
Result = Milli.multiply(BigInteger.valueOf(Amount));
translatedResult = Milli.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Milli" + Units + ".");
}
if(Prefix == 9)
{
Result = Centi.multiply(BigInteger.valueOf(Amount));
translatedResult = Centi.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Centi" + Units + ".");
}
if(Prefix == 10)
{
Result = Deci.multiply(BigInteger.valueOf(Amount));
translatedResult = Deci.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Deci" + Units + ".");
}
if(Prefix == 11)
{
Result = Deca.multiply(BigInteger.valueOf(Amount));
translatedResult = Deca.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Deca" + Units + ".");
}
if(Prefix == 12)
{
Result = Hecto.multiply(BigInteger.valueOf(Amount));
translatedResult = Hecto.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Hecto" + Units + ".");
}
if(Prefix == 13)
{
Result = Kilo.multiply(BigInteger.valueOf(Amount));
translatedResult = Kilo.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Kilo" + Units + ".");
}
if(Prefix == 14)
{
Result = Mega.multiply(BigInteger.valueOf(Amount));
translatedResult = Mega.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Mega" + Units + ".");
}
if(Prefix == 15)
{
Result = Giga.multiply(BigInteger.valueOf(Amount));
translatedResult = Giga.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Giga" + Units + ".");
}
if(Prefix == 16)
{
Result = Tera.multiply(BigInteger.valueOf(Amount));
translatedResult = Tera.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Tera" + Units + ".");
}
if(Prefix == 17)
{
Result = Peta.multiply(BigInteger.valueOf(Amount));
translatedResult = Peta.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Peta" + Units + ".");
}
if(Prefix == 18)
{
Result = Exa.multiply(BigInteger.valueOf(Amount));
translatedResult = Exa.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Exa" + Units + ".");
}
if(Prefix == 19)
{
Result = Zetta.multiply(BigInteger.valueOf(Amount));
translatedResult = Zetta.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Zetta" + Units + ".");
}
if(Prefix == 20)
{
Result = Yotta.multiply(BigInteger.valueOf(Amount));
translatedResult = Yotta.divide(BigInteger.valueOf(Amount));
System.out.println("You have " + Result + " " + Units + " which translates to " + translatedResult + "Yotta" + Units + ".");
}
else
{
System.out.println("Not a valid input.");
}
}
}
Thanks for your help.
BigInteger can only store integers, and so is not a suitable data type for this application. I strongly recommend replacing it with BigDecimal.
You should also use string representations of the fractions to initialize:
BigDecimal Zepto = new BigDecimal("0.000000000000000000001");
BigDecimal Atto = new BigDecimal("0.000000000000000001");
BigDecimal Femto = new BigDecimal("0.000000000000001");
BigDecimal Pico = new BigDecimal("0.000000000001");
BigDecimal Nano = new BigDecimal("0.000000001");
Comments on this answer and on the question indicate a concern with using BigDecimal to store the larger numbers. This program illustrates the fact that it is not an issue:
import java.math.BigDecimal;
public class Test {
public static void main(String[] args) {
BigDecimal googol = new BigDecimal("1e100");
System.out.println(googol);
System.out.println(googol.add(BigDecimal.ONE));
}
}
Output:
1E+100
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001

Is there any possibility to get the currentStockLevel from this method?

I need the currentStockLevel for another void Method in java, is there any possibility to get it?
I think no, because of void right?
public void receive (int currentStock)
{
String outLine;
if (currentStockLevel > 0)
outLine = productCode;
{
outLine = ". Current Stock: " + currentStockLevel;
outLine += " Current Stock changed from " + currentStockLevel;
currentStockLevel += currentStock;
outLine += " to " + currentStockLevel;
int storeCost = wholeSalePrice * currentStockLevel;
System.out.println (productCode + ":" + " Received " + currentStockLevel + "." + " Store Cost " + "$" + storeCost + "." + " New stock level: " + currentStockLevel);
}

Longest monotonic subsequence algorithm NOT longest increasing algorithm

I have some numbers at the input:
1 1 7 3 2 0 0 4 5 5 6 2 1
And I look for a longest monotonic subsequence and what is the sum of this subsequence. The result is:
6 20
I cannot find the algorithm at the internet. Do you own/found one? This is about longest monotonic not longest increasing subsequence.
Definition of monotonic: http://en.wikipedia.org/wiki/Monotonic_function
I know that someone will ask: What have you tried? So i tried writing it(please don't check it I only post it so no one asks that question above I look for different algorithm->optimal one)
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Rozwiazanie {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//2^63 > 10^16 = 10^7 * 10^9 longi starcza
//10^9 inty starcza
//int 32 bity, long 64 bity
long podsuma = 0;
int dlugosc = 0;
int maxDlugosc = 0;
long maxPodsuma = 0;
int poczatekRownych = 0;
int poprzedniWyraz = 0, aktualnyWyraz;//uwaga jakby cos nie gralo w sprawdzarce zmien typ na long
boolean czyRosnacy = false, rowny = false;
String[] splittedLinia = br.readLine().split((char) 32 + "");//moglaby byc " " ale tak na wszelki wypadek nie ma chuja zeby sie popierdolilo teraz nawet na linuxie
for (int i = 0; i < splittedLinia.length; i++) {
if (i == 0) {
aktualnyWyraz = Integer.parseInt(splittedLinia[0]);
maxDlugosc = dlugosc = 1;
maxPodsuma = podsuma = aktualnyWyraz;
if (splittedLinia.length > 1) {
int nastepnyWyraz = Integer.parseInt(splittedLinia[1]);
czyRosnacy = nastepnyWyraz > aktualnyWyraz;
rowny = nastepnyWyraz == aktualnyWyraz;
}
System.out.println("akt: " + aktualnyWyraz + " pop: " + poprzedniWyraz + " dlugosc: " + dlugosc + " " + 1);
} else {
aktualnyWyraz = Integer.parseInt(splittedLinia[i]);
System.out.println(rowny);
if (aktualnyWyraz == poprzedniWyraz && rowny) {
podsuma += aktualnyWyraz;
dlugosc++;
System.out.println("akt: " + aktualnyWyraz + " pop: " + poprzedniWyraz + " dlugosc: " + dlugosc + " " + 2);
} else if (rowny) {
rowny = false;
czyRosnacy = aktualnyWyraz > poprzedniWyraz;
System.out.println("akt: " + aktualnyWyraz + " pop: " + poprzedniWyraz + " dlugosc: " + dlugosc + " " + 3);
}
if (!rowny) {
if (aktualnyWyraz >= poprzedniWyraz && czyRosnacy) {
podsuma += aktualnyWyraz;
dlugosc++;
System.out.println("akt:" + aktualnyWyraz + " pop: " + poprzedniWyraz + " dlugosc: " + dlugosc + " " + 4);
} else if (aktualnyWyraz <= poprzedniWyraz && !czyRosnacy) {
podsuma += aktualnyWyraz;
dlugosc++;
System.out.println("akt: " + aktualnyWyraz + " pop: " + poprzedniWyraz + " dlugosc: " + dlugosc + " " + 5);
} else {
// if (aktualnyWyraz == poprzedniWyraz) {
rowny = true;
// } else {
if (maxDlugosc < dlugosc) {
maxDlugosc = dlugosc;
maxPodsuma = podsuma;
}
podsuma = poprzedniWyraz + aktualnyWyraz;
dlugosc = 2;
czyRosnacy = aktualnyWyraz > poprzedniWyraz;
rowny = aktualnyWyraz == poprzedniWyraz;
System.out.println("akt: " + aktualnyWyraz + " pop: " + poprzedniWyraz + " dlugosc: " + dlugosc + " " + 6);
//}
}
}
}
poprzedniWyraz = aktualnyWyraz;
}
System.out.println(maxDlugosc + " " + maxPodsuma);
} catch (Exception e) {
e.printStackTrace();
}
}
}
//65 87 47 5 12 74 25 32 78 44 40 77 85 4 29 57:
try this one:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Rozwiazanie {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] splittedLinia = br.readLine().split((char) 32 + "");//moglaby byc " " ale tak na wszelki wypadek nie ma chuja zeby sie popierdolilo teraz nawet na linuxie
int aktualnyWyraz = Integer.parseInt(splittedLinia[0]);//uwaga jakby cos nie gralo w sprawdzarce zmien typ na long
int poprzedniWyraz = 0;
long podsumaRosnaca = aktualnyWyraz;
long podsumaSpadajaca = aktualnyWyraz;
int dlugoscRosnaca = 1;
int dlugoscSpadajaca = 1;
int maxDlugosc = 1;
long maxPodsuma = aktualnyWyraz;
int czyRosnacy = 0; // 0 -- nie znane (jezeli w poczatku wszystkie liczby sa rowne), 1 -- rosnacy, -1 -- spadajacy
boolean rowny = false;
System.out.println("akt: " + aktualnyWyraz + " dlR: " + dlugoscRosnaca + " podsumaR: " + podsumaRosnaca + " dlP: " + dlugoscSpadajaca + " podsumaP: " + podsumaSpadajaca);
for (int i = 1; i < splittedLinia.length; i++) {
poprzedniWyraz = aktualnyWyraz;
aktualnyWyraz = Integer.parseInt(splittedLinia[i]);
if (aktualnyWyraz == poprzedniWyraz) {
podsumaRosnaca += aktualnyWyraz;
podsumaSpadajaca += aktualnyWyraz;
dlugoscRosnaca++;
dlugoscSpadajaca++;
rowny = true;
} else { // rozne liczby
if (aktualnyWyraz > poprzedniWyraz) { // rosnie
podsumaRosnaca += aktualnyWyraz;
dlugoscRosnaca++;
if (rowny) {
dlugoscSpadajaca = 1;
podsumaSpadajaca = 0;
rowny = false;
}
if (czyRosnacy < 0) {
if (dlugoscSpadajaca > maxDlugosc) {
maxDlugosc = dlugoscSpadajaca;
maxPodsuma = podsumaSpadajaca;
}
podsumaSpadajaca = 0;
dlugoscSpadajaca = 1;
}
czyRosnacy = 1;
} else { // spada
podsumaSpadajaca += aktualnyWyraz;
dlugoscSpadajaca++;
if (rowny) {
dlugoscRosnaca = 1;
podsumaRosnaca = 0;
rowny = false;
}
if (czyRosnacy == 1) {
if (dlugoscRosnaca > maxDlugosc) {
maxDlugosc = dlugoscRosnaca;
maxPodsuma = podsumaRosnaca;
}
podsumaRosnaca = 0;
dlugoscRosnaca = 1;
}
czyRosnacy = -1;
}
}
System.out.println("akt: " + aktualnyWyraz + " dlR: " + dlugoscRosnaca + " podsumaR: " + podsumaRosnaca + " dlP: " + dlugoscSpadajaca + " podsumaP: " + podsumaSpadajaca);
}
System.out.println("maxDlugosc " + maxDlugosc + " maxPodsuma " + maxPodsuma);
} catch (Exception e) {
e.printStackTrace();
}
}
}
what I had to change:
you need a counter [dlugosc] (+ sum [podsuma]) for ascending
[rosnacy] and descending [spadajacy] values, as you need to count
both when the values are the same [rowny].
I changed boolean "rowny"
[equal] to int, as I thought that there are 3 values possible:
ascending, descending or unknown. If there are several equal values
at the beginning, there's all the time "unknown".
this program needs at least one number, but therefore you don't need to check in every
iteration of the loop whether i == 0 or not.
Going through the
numbers, I have to check several things, most important is, whether
the actual value [aktualnyWyraz] and the last used value
[poprzedniWyraz] are the same (then all counters and sums have to be
changed) or different. Different can mean ascending or descending, so
we have to increment the related counters and sum up the related sum.
What happens the "opposite" variables? Well, we need to check whether
the counter is bigger then the maximum one (so maybe these values are
useful for the result) and then set them back to their start.

Categories

Resources