Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Лаб 1
- /////////
- Римски броеви Problem 1 (1 / 2)
- import java.util.Scanner;
- import java.util.stream.IntStream;
- public class RomanConverterTest {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- int n = scanner.nextInt();
- IntStream.range(0, n)
- .forEach(x -> System.out.println(RomanConverter.toRoman(scanner.nextInt())));
- scanner.close();
- }
- }
- class RomanConverter {
- /**
- * Roman to decimal converter
- *
- * @param n number in decimal format
- * @return string representation of the number in Roman numeral
- */
- public static String toRoman(int n) {
- String a=new String();
- while(n>=1000)
- {
- a=a+"M";
- n-=1000;
- }
- if(n>=900)
- {
- a=a+"CM";
- n-=900;
- }
- if(n>=500)
- {
- a=a+"D";
- n-=500;
- }
- if(n>=400)
- {
- a=a+"CD";
- n-=400;
- }
- while(n>=100)
- {
- a=a+"C";
- n-=100;
- }
- if(n>=90)
- {
- a=a+"XC";
- n-=90;
- }
- if(n>=50)
- {
- a=a+"L";
- n-=50;
- }
- if(n>=40)
- {
- a=a+"XL";
- n-=40;
- }
- while(n>=10)
- {
- a=a+"X";
- n-=10;
- }
- if(n>=9)
- {
- a=a+"IX";
- n-=9;
- }
- if(n>=5)
- {
- a=a+"V";
- n-=5;
- }
- if(n>=4)
- {
- a=a+"IV";
- n-=4;
- }
- while(n>=1)
- {
- a=a+"I";
- n-=1;
- }
- return a;
- }
- }
- //////////
- Систем за банкарско работење Problem 2 (1 / 22)
- import java.util.*;
- import java.util.stream.Collectors;
- class Account{
- private String ime;
- private long ID;
- private String saldo;
- public Account(String ime, String saldo) {
- this.ime = ime;
- this.saldo = saldo;
- Random random = new Random();
- ID = random.nextLong();
- }
- public String getBalance(){
- return saldo;
- }
- public double getdoubleBalance(){
- return Double.parseDouble(saldo.substring(0, saldo.length()-1));
- }
- public String getName(){
- return ime;
- }
- public long getId(){
- return ID;
- }
- public void setBalance(String balance)
- {
- saldo=balance;
- }
- @Override
- public String toString(){
- return String.format("Name: %s\nBalance: %s\n",ime,saldo);
- }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + (int) (ID ^ (ID >>> 32));
- result = prime * result + ((ime == null) ? 0 : ime.hashCode());
- result = prime * result + ((saldo == null) ? 0 : saldo.hashCode());
- return result;
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- Account other = (Account) obj;
- if (ID != other.ID)
- return false;
- if (ime == null) {
- if (other.ime != null)
- return false;
- } else if (!ime.equals(other.ime))
- return false;
- if (saldo == null) {
- if (other.saldo != null)
- return false;
- } else if (!saldo.equals(other.saldo))
- return false;
- return true;
- }
- }
- abstract class Transaction{
- private long IDod;
- private long IDdo;
- private String opis;
- private String iznos;
- public Transaction(long iDod, long iDdo, String opis, String iznos) {
- IDod = iDod;
- IDdo = iDdo;
- this.opis = opis;
- this.iznos = iznos;
- }
- public String getAmount(){
- return iznos;
- }
- public long getFromId(){
- return IDod;
- }
- public long getToId(){
- return IDdo;
- }
- public String getDescription(){
- return opis;
- }
- public double getdoubleAmount(){
- return Double.parseDouble(iznos.substring(0,iznos.length()-1));
- }
- public abstract double getProvision();
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + (int) (IDdo ^ (IDdo >>> 32));
- result = prime * result + (int) (IDod ^ (IDod >>> 32));
- result = prime * result + ((iznos == null) ? 0 : iznos.hashCode());
- result = prime * result + ((opis == null) ? 0 : opis.hashCode());
- return result;
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- Transaction other = (Transaction) obj;
- if (IDdo != other.IDdo)
- return false;
- if (IDod != other.IDod)
- return false;
- if (iznos == null) {
- if (other.iznos != null)
- return false;
- } else if (!iznos.equals(other.iznos))
- return false;
- if (opis == null) {
- if (other.opis != null)
- return false;
- } else if (!opis.equals(other.opis))
- return false;
- return true;
- }
- }
- class FlatAmountProvisionTransaction extends Transaction{
- private String provizija;
- public FlatAmountProvisionTransaction(long fromId, long toId,String amount, String flatProvision){
- super(fromId,toId,"FlatAmount",amount);
- provizija=flatProvision;
- }
- String getFlatAmount()
- {
- return provizija;
- }
- @Override
- public double getProvision() {
- return Double.parseDouble(provizija.substring(0,provizija.length()-1));
- }
- @Override
- public double getdoubleAmount(){
- return super.getdoubleAmount() + getProvision();
- }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = super.hashCode();
- result = prime * result + ((provizija == null) ? 0 : provizija.hashCode());
- return result;
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (!super.equals(obj))
- return false;
- if (getClass() != obj.getClass())
- return false;
- FlatAmountProvisionTransaction other = (FlatAmountProvisionTransaction) obj;
- if (provizija == null) {
- if (other.provizija != null)
- return false;
- } else if (!provizija.equals(other.provizija))
- return false;
- return true;
- }
- }
- class FlatPercentProvisionTransaction extends Transaction{
- private int provizija;
- public FlatPercentProvisionTransaction (long fromId, long toId, String amount, int centsPerDolar){
- super(fromId,toId,"FlatPercent",amount);
- provizija=centsPerDolar;
- }
- int getPercent(){
- return provizija;
- }
- @Override
- public double getProvision() {
- return provizija / 100.0 * (int)super.getdoubleAmount();
- }
- @Override
- public double getdoubleAmount() {
- return super.getdoubleAmount() + getProvision();
- }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = super.hashCode();
- result = prime * result + provizija;
- return result;
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (!super.equals(obj))
- return false;
- if (getClass() != obj.getClass())
- return false;
- FlatPercentProvisionTransaction other = (FlatPercentProvisionTransaction) obj;
- if (provizija != other.provizija)
- return false;
- return true;
- }
- }
- class Bank{
- private String ime;
- private double provizija;
- private double suma;
- private Account accs[];
- public Bank(String name,Account accounts[])
- {
- ime=name;
- accs = Arrays.copyOf(accounts, accounts.length);
- suma=0;
- provizija=0;
- }
- public Account[] getAccounts()
- {
- return accs;
- }
- public String totalProvision() {
- return String.format("%.2f$",provizija);
- }
- public String totalTransfers() {
- return String.format("%.2f$",suma);
- }
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append("Name: " + ime + "\n\n");
- for (Account a: accs)
- sb.append(a.toString());
- return sb.toString();
- }
- int findID(long a){
- for(int i=0;i<accs.length;i++)
- {
- if(a==accs[i].getId())
- {
- return i;
- }
- }
- return -1;
- }
- boolean makeTransaction(Transaction t){
- int iDFrom = findID(t.getFromId());
- int iDTo = findID(t.getToId());
- if (iDFrom == -1 || iDTo==-1)
- return false;
- double balanceFrom = accs[iDFrom].getdoubleBalance();
- double balanceTo = accs[iDTo].getdoubleBalance();
- if ( balanceFrom < t.getdoubleAmount())
- return false;
- double totalSum = t.getdoubleAmount();
- double provision = t.getProvision();
- suma += (totalSum - provision);
- provizija += provision;
- balanceFrom -= totalSum;
- if (iDFrom == iDTo) {
- balanceTo -= provision;
- }
- else {
- balanceTo += (totalSum - provision);
- }
- accs[iDFrom].setBalance(String.format("%.2f$",balanceFrom));
- accs[iDTo].setBalance(String.format("%.2f$",balanceTo));
- return true;
- }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + Arrays.hashCode(accs);
- result = prime * result + ((ime == null) ? 0 : ime.hashCode());
- long temp;
- temp = Double.doubleToLongBits(provizija);
- result = prime * result + (int) (temp ^ (temp >>> 32));
- temp = Double.doubleToLongBits(suma);
- result = prime * result + (int) (temp ^ (temp >>> 32));
- return result;
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- Bank other = (Bank) obj;
- if (!Arrays.equals(accs, other.accs))
- return false;
- if (ime == null) {
- if (other.ime != null)
- return false;
- } else if (!ime.equals(other.ime))
- return false;
- if (Double.doubleToLongBits(provizija) != Double.doubleToLongBits(other.provizija))
- return false;
- if (Double.doubleToLongBits(suma) != Double.doubleToLongBits(other.suma))
- return false;
- return true;
- }
- }
- public class BankTester {
- public static void main(String[] args) {
- Scanner jin = new Scanner(System.in);
- String test_type = jin.nextLine();
- switch (test_type) {
- case "typical_usage":
- testTypicalUsage(jin);
- break;
- case "equals":
- testEquals();
- break;
- }
- jin.close();
- }
- private static void testEquals() {
- Account a1 = new Account("Andrej", "20.00$");
- Account a2 = new Account("Andrej", "20.00$");
- Account a3 = new Account("Andrej", "30.00$");
- Account a4 = new Account("Gajduk", "20.00$");
- List<Account> all = Arrays.asList(a1, a2, a3, a4);
- if (!(a1.equals(a1)&&!a1.equals(a2)&&!a2.equals(a1)&&!a3.equals(a1)&&!a4.equals(a1)&&!a1.equals(null))) {
- System.out.println("Your account equals method does not work properly.");
- return;
- }
- Set<Long> ids = all.stream().map(Account::getId).collect(Collectors.toSet());
- if (ids.size() != all.size()) {
- System.out.println("Different accounts have the same IDS. This is not allowed");
- return;
- }
- FlatAmountProvisionTransaction fa1 = new FlatAmountProvisionTransaction(10, 20, "20.00$", "10.00$");
- FlatAmountProvisionTransaction fa2 = new FlatAmountProvisionTransaction(20, 20, "20.00$", "10.00$");
- FlatAmountProvisionTransaction fa3 = new FlatAmountProvisionTransaction(20, 10, "20.00$", "10.00$");
- FlatAmountProvisionTransaction fa4 = new FlatAmountProvisionTransaction(10, 20, "50.00$", "50.00$");
- FlatAmountProvisionTransaction fa5 = new FlatAmountProvisionTransaction(30, 40, "20.00$", "10.00$");
- FlatPercentProvisionTransaction fp1 = new FlatPercentProvisionTransaction(10, 20, "20.00$", 10);
- FlatPercentProvisionTransaction fp2 = new FlatPercentProvisionTransaction(10, 20, "20.00$", 10);
- FlatPercentProvisionTransaction fp3 = new FlatPercentProvisionTransaction(10, 10, "20.00$", 10);
- FlatPercentProvisionTransaction fp4 = new FlatPercentProvisionTransaction(10, 20, "50.00$", 10);
- FlatPercentProvisionTransaction fp5 = new FlatPercentProvisionTransaction(10, 20, "20.00$", 30);
- FlatPercentProvisionTransaction fp6 = new FlatPercentProvisionTransaction(30, 40, "20.00$", 10);
- if (fa1.equals(fa1)&&!fa2.equals(null) &&
- fa2.equals(fa1) &&
- fa1.equals(fa2) &&
- fa1.equals(fa3) &&
- !fa1.equals(fa4) &&
- !fa1.equals(fa5) &&
- !fa1.equals(fp1) &&
- fp1.equals(fp1) &&
- !fp2.equals(null) &&
- fp2.equals(fp1) &&
- fp1.equals(fp2) &&
- fp1.equals(fp3) &&
- !fp1.equals(fp4) &&
- !fp1.equals(fp5) &&
- !fp1.equals(fp6)) {
- System.out.println("Your transactions equals methods do not work properly.");
- return;
- }
- Account accounts[] = new Account[]{a1, a2, a3, a4};
- Account accounts1[] = new Account[]{a2, a1, a3, a4};
- Account accounts2[] = new Account[]{a1, a2, a3};
- Account accounts3[] = new Account[]{a1, a2, a3, a4};
- Bank b1 = new Bank("Test", accounts);
- Bank b2 = new Bank("Test", accounts1);
- Bank b3 = new Bank("Test", accounts2);
- Bank b4 = new Bank("Sample", accounts);
- Bank b5 = new Bank("Test", accounts3);
- if (!(b1.equals(b1) &&
- !b1.equals(null) &&
- !b1.equals(b2) &&
- !b2.equals(b1) &&
- !b1.equals(b3) &&
- !b3.equals(b1) &&
- !b1.equals(b4) &&
- b1.equals(b5))) {
- System.out.println("Your bank equals method do not work properly.");
- return;
- }
- accounts[2] = a1;
- if (!b1.equals(b5)) {
- System.out.println("Your bank equals method do not work properly.");
- return;
- }
- long from_id = a2.getId();
- long to_id = a3.getId();
- Transaction t = new FlatAmountProvisionTransaction(from_id, to_id, "3.00$", "3.00$");
- b1.makeTransaction(t);
- if (b1.equals(b5)) {
- System.out.println("Your bank equals method do not work properly.");
- return;
- }
- b5.makeTransaction(t);
- if (!b1.equals(b5)) {
- System.out.println("Your bank equals method do not work properly.");
- return;
- }
- System.out.println("All your equals methods work properly.");
- }
- private static void testTypicalUsage(Scanner jin) {
- String bank_name = jin.nextLine();
- int num_accounts = jin.nextInt();
- jin.nextLine();
- Account accounts[] = new Account[num_accounts];
- for (int i = 0; i < num_accounts; ++i)
- accounts[i] = new Account(jin.nextLine(), jin.nextLine());
- Bank bank = new Bank(bank_name, accounts);
- while (true) {
- String line = jin.nextLine();
- switch (line) {
- case "stop":
- return;
- case "transaction":
- String descrption = jin.nextLine();
- String amount = jin.nextLine();
- String parameter = jin.nextLine();
- int from_idx = jin.nextInt();
- int to_idx = jin.nextInt();
- jin.nextLine();
- Transaction t = getTransaction(descrption, from_idx, to_idx, amount, parameter, bank);
- System.out.println("Transaction amount: " + t.getAmount());
- System.out.println("Transaction description: " + t.getDescription());
- System.out.println("Transaction successful? " + bank.makeTransaction(t));
- break;
- case "print":
- System.out.println(bank.toString());
- System.out.println("Total provisions: " + bank.totalProvision());
- System.out.println("Total transfers: " + bank.totalTransfers());
- System.out.println();
- break;
- }
- }
- }
- private static Transaction getTransaction(String description, int from_idx, int to_idx, String amount, String o, Bank bank) {
- switch (description) {
- case "FlatAmount":
- return new FlatAmountProvisionTransaction(bank.getAccounts()[from_idx].getId(),
- bank.getAccounts()[to_idx].getId(), amount, o);
- case "FlatPercent":
- return new FlatPercentProvisionTransaction(bank.getAccounts()[from_idx].getId(),
- bank.getAccounts()[to_idx].getId(), amount, Integer.parseInt(o));
- }
- return null;
- }
- }
- /////////////////
- import java.io.ByteArrayInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.Arrays;
- import java.util.Random;
- import java.util.Scanner;
- final class IntegerArray{
- private final int a[];
- public IntegerArray(){
- a=null;
- }
- public IntegerArray(int[] b) {
- a=new int[b.length];
- for(int i=0;i<b.length;i++)
- {
- a[i]=b[i];
- }
- }
- public int length(){
- return a.length;
- }
- public int getElementAt(int i)
- {
- return a[i];
- }
- public int sum(){
- int sum=0;
- for(int i=0;i<a.length;i++)
- sum+=a[i];
- return sum;
- }
- public double average(){
- return (double)sum()/a.length;
- }
- public IntegerArray getSorted(){
- int [] b=new int[a.length];
- for(int i=0;i<a.length;i++)
- b[i]=a[i];
- Arrays.sort(b);
- return new IntegerArray(b);
- }
- public IntegerArray concat(IntegerArray ia){
- int [] b=new int[ia.length()+a.length];
- for(int i=0;i<a.length;i++)
- {
- b[i]=a[i];
- }
- for(int i=a.length,k=0;i<(ia.length()+a.length);i++,k++)
- {
- b[i]=ia.a[k];
- }
- return new IntegerArray(b);
- }
- @Override
- public String toString(){
- StringBuilder sb = new StringBuilder();
- sb.append("[");
- for(int i=0;i<a.length-1;i++){
- sb.append(a[i]);
- sb.append(", ");
- }
- sb.append(a[a.length-1]);
- sb.append("]");
- return sb.toString();
- }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + Arrays.hashCode(a);
- return result;
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- IntegerArray other = (IntegerArray) obj;
- if (!Arrays.equals(a, other.a))
- return false;
- return true;
- }
- }
- class ArrayReader{
- public static IntegerArray readIntegerArray(InputStream input){
- Scanner s = new Scanner(input);
- int N=s.nextInt();
- int[] a = new int[N];
- for(int i=0;i<N;i++)
- {
- a[i]=s.nextInt();
- }
- return new IntegerArray(a);
- }
- }
- public class IntegerArrayTester {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- String s = scanner.nextLine();
- IntegerArray ia = null;
- switch (s) {
- case "testSimpleMethods":
- ia = new IntegerArray(generateRandomArray(scanner.nextInt()));
- testSimpleMethods(ia);
- break;
- case "testConcat":
- testConcat(scanner);
- break;
- case "testEquals":
- testEquals(scanner);
- break;
- case "testSorting":
- testSorting(scanner);
- break;
- case "testReading":
- testReading(new ByteArrayInputStream(scanner.nextLine().getBytes()));
- break;
- case "testImmutability":
- int a[] = generateRandomArray(scanner.nextInt());
- ia = new IntegerArray(a);
- testSimpleMethods(ia);
- testSimpleMethods(ia);
- IntegerArray sorted_ia = ia.getSorted();
- testSimpleMethods(ia);
- testSimpleMethods(sorted_ia);
- sorted_ia.getSorted();
- testSimpleMethods(sorted_ia);
- testSimpleMethods(ia);
- a[0] += 2;
- testSimpleMethods(ia);
- ia = ArrayReader.readIntegerArray(new ByteArrayInputStream(integerArrayToString(ia).getBytes()));
- testSimpleMethods(ia);
- break;
- }
- scanner.close();
- }
- static void testReading(InputStream in) {
- IntegerArray read = ArrayReader.readIntegerArray(in);
- System.out.println(read);
- }
- static void testSorting(Scanner scanner) {
- int[] a = readArray(scanner);
- IntegerArray ia = new IntegerArray(a);
- System.out.println(ia.getSorted());
- }
- static void testEquals(Scanner scanner) {
- int[] a = readArray(scanner);
- int[] b = readArray(scanner);
- int[] c = readArray(scanner);
- IntegerArray ia = new IntegerArray(a);
- IntegerArray ib = new IntegerArray(b);
- IntegerArray ic = new IntegerArray(c);
- System.out.println(ia.equals(ib));
- System.out.println(ia.equals(ic));
- System.out.println(ib.equals(ic));
- }
- static void testConcat(Scanner scanner) {
- int[] a = readArray(scanner);
- int[] b = readArray(scanner);
- IntegerArray array1 = new IntegerArray(a);
- IntegerArray array2 = new IntegerArray(b);
- IntegerArray concatenated = array1.concat(array2);
- System.out.println(concatenated);
- }
- static void testSimpleMethods(IntegerArray ia) {
- System.out.print(integerArrayToString(ia));
- System.out.println(ia);
- System.out.println(ia.sum());
- System.out.printf("%.2f\n", ia.average());
- }
- static String integerArrayToString(IntegerArray ia) {
- StringBuilder sb = new StringBuilder();
- sb.append(ia.length()).append('\n');
- for (int i = 0; i < ia.length(); ++i)
- sb.append(ia.getElementAt(i)).append(' ');
- sb.append('\n');
- return sb.toString();
- }
- static int[] readArray(Scanner scanner) {
- int n = scanner.nextInt();
- int[] a = new int[n];
- for (int i = 0; i < n; ++i) {
- a[i] = scanner.nextInt();
- }
- return a;
- }
- static int[] generateRandomArray(int k) {
- Random rnd = new Random(k);
- int n = rnd.nextInt(8) + 2;
- int a[] = new int[n];
- for (int i = 0; i < n; ++i) {
- a[i] = rnd.nextInt(20) - 5;
- }
- return a;
- }
- }
- ///////
- Лаб 3.
- //////
- Пицерија Problem 1 (1 / 9)
- import java.util.Scanner;
- interface Item{
- public int getPrice();
- public String getType();
- }
- class OrderLockedException extends Exception{
- }
- class EmptyOrder extends Exception{
- }
- class InvalidExtraTypeException extends Exception{
- }
- class InvalidPizzaTypeException extends Exception{
- }
- class ItemOutOfStockException extends Exception{
- public ItemOutOfStockException(Item item){
- super(String.format("Nema %s", item.getType()));
- }
- }
- class ExtraItem implements Item{
- String type;
- ExtraItem(String type) throws InvalidExtraTypeException{
- if(type.compareTo("Coke")==0)
- {
- this.type=type;
- }
- else if(type.compareTo("Ketchup")==0)
- {
- this.type=type;
- }
- else{
- throw new InvalidExtraTypeException();
- }
- }
- public String getType(){return type;}
- public int getPrice(){
- if(type.compareTo("Coke")==0)
- {
- return 5;
- }
- else{
- return 3;
- }
- }
- }
- class PizzaItem implements Item{
- String type;
- PizzaItem(String type) throws InvalidPizzaTypeException{
- if(type.compareTo("Standard")==0)
- {
- this.type=type;
- }
- else if(type.compareTo("Pepperoni")==0){
- this.type=type;
- }
- else if(type.compareTo("Vegetarian")==0){
- this.type=type;
- }
- else{
- throw new InvalidPizzaTypeException();
- }
- }
- public String getType(){return type;}
- public int getPrice(){
- if(type.compareTo("Standard")==0)
- {
- return 10;
- }
- else if(type.compareTo("Pepperoni")==0){
- return 12;
- }
- else {
- return 8;
- }
- }
- }
- class Order{
- int a[];
- Item it[];
- int n;
- boolean locked;
- public Order(){
- a=new int[5];
- it=new Item[5];
- locked=false;
- n=0;
- }
- public void addItem(Item item, int count) throws ItemOutOfStockException, OrderLockedException
- {
- if(!locked){
- if(count>=10)
- throw new ItemOutOfStockException(item);
- boolean flag=false;
- for(int i=0;i<n;i++)
- {
- if (item.getType().compareTo(it[i].getType())==0)
- {
- a[i]=count;
- flag=true;
- break;
- }
- }
- if(!flag)
- {
- a[n]=count;
- it[n]=item;
- n++;
- }
- }
- else throw new OrderLockedException();
- }
- public int getPrice(){
- int s=0;
- for(int i=0;i<n;i++)
- {
- s+=it[i].getPrice()*a[i];
- }
- return s;
- }
- public void displayOrder(){
- for(int i=0;i<n;i++){
- System.out.printf("%3d.%-15sx%2d%5d$\n",i+1,it[i].getType(),a[i],it[i].getPrice()*a[i]);
- }
- System.out.printf("Total: %5d$\n",getPrice());
- }
- public void removeItem(int idx) throws ArrayIndexOutOfBoundsException,OrderLockedException
- {
- if(idx>=n)
- {
- throw new ArrayIndexOutOfBoundsException();
- }
- else{
- if(!locked){
- for(int i=idx;i<n-1;i++)
- {
- a[i]=a[i+1];
- it[i]=it[i+1];
- }
- n--;
- }
- else throw new OrderLockedException();
- }
- }
- public void lock() throws EmptyOrder
- {
- if(n==0) throw new EmptyOrder();
- else locked=true;
- }
- }
- public class PizzaOrderTest {
- public static void main(String[] args) {
- Scanner jin = new Scanner(System.in);
- int k = jin.nextInt();
- if (k == 0) { //test Item
- try {
- String type = jin.next();
- String name = jin.next();
- Item item = null;
- if (type.equals("Pizza")) item = new PizzaItem(name);
- else item = new ExtraItem(name);
- System.out.println(item.getPrice());
- } catch (Exception e) {
- System.out.println(e.getClass().getSimpleName());
- }
- }
- if (k == 1) { // test simple order
- Order order = new Order();
- while (true) {
- try {
- String type = jin.next();
- String name = jin.next();
- Item item = null;
- if (type.equals("Pizza")) item = new PizzaItem(name);
- else item = new ExtraItem(name);
- if (!jin.hasNextInt()) break;
- order.addItem(item, jin.nextInt());
- } catch (Exception e) {
- System.out.println(e.getClass().getSimpleName());
- }
- }
- jin.next();
- System.out.println(order.getPrice());
- order.displayOrder();
- while (true) {
- try {
- String type = jin.next();
- String name = jin.next();
- Item item = null;
- if (type.equals("Pizza")) item = new PizzaItem(name);
- else item = new ExtraItem(name);
- if (!jin.hasNextInt()) break;
- order.addItem(item, jin.nextInt());
- } catch (Exception e) {
- System.out.println(e.getClass().getSimpleName());
- }
- }
- System.out.println(order.getPrice());
- order.displayOrder();
- }
- if (k == 2) { // test order with removing
- Order order = new Order();
- while (true) {
- try {
- String type = jin.next();
- String name = jin.next();
- Item item = null;
- if (type.equals("Pizza")) item = new PizzaItem(name);
- else item = new ExtraItem(name);
- if (!jin.hasNextInt()) break;
- order.addItem(item, jin.nextInt());
- } catch (Exception e) {
- System.out.println(e.getClass().getSimpleName());
- }
- }
- jin.next();
- System.out.println(order.getPrice());
- order.displayOrder();
- while (jin.hasNextInt()) {
- try {
- int idx = jin.nextInt();
- order.removeItem(idx);
- } catch (Exception e) {
- System.out.println(e.getClass().getSimpleName());
- }
- }
- System.out.println(order.getPrice());
- order.displayOrder();
- }
- if (k == 3) { //test locking & exceptions
- Order order = new Order();
- try {
- order.lock();
- } catch (Exception e) {
- System.out.println(e.getClass().getSimpleName());
- }
- try {
- order.addItem(new ExtraItem("Coke"), 1);
- } catch (Exception e) {
- System.out.println(e.getClass().getSimpleName());
- }
- try {
- order.lock();
- } catch (Exception e) {
- System.out.println(e.getClass().getSimpleName());
- }
- try {
- order.removeItem(0);
- } catch (Exception e) {
- System.out.println(e.getClass().getSimpleName());
- }
- }
- }
- }
- /////////////
- Лаб 4.
- ////////////
- LocalDate Problem 1 (1 / 3)
- import java.sql.Date;
- import java.sql.Timestamp;
- import java.time.*;
- import java.time.temporal.ChronoUnit;
- import java.time.temporal.TemporalAdjusters;
- /**
- * LocalDate test
- */
- public class LocalDateTest {
- public static void main(String[] args) {
- System.out.println(create());
- System.out.println(parse());
- System.out.println(with().getYear());
- System.out.println(withAdjuster());
- System.out.println(plus());
- System.out.println(minus());
- System.out.println(plusPeriod());
- System.out.println(isAfter());
- System.out.println(until());
- }
- static LocalDate create() {
- /**
- * Create a {@link LocalDate} of 2015-06-18 by using {@link LocalDate#of}
- */
- return LocalDate.of(2015, 06, 18);
- }
- static LocalDate parse() {
- /**
- * Create a {@link LocalDate} of 2015-06-18 from String by using {@link LocalDate#parse}
- */
- return LocalDate.parse("2015-06-18");
- }
- static LocalDate with() {
- LocalDate ld = DateAndTimes.LD_20150618;
- /**
- * Create a {@link LocalDate} from {@link ld} with year 2015
- * by using {@link LocalDate#withYear} or {@link LocalDate#with}
- */
- return ld.withYear(2015);
- }
- static LocalDate withAdjuster() {
- LocalDate ld = DateAndTimes.LD_20150618;
- /**
- * Create a {@link LocalDate} from {@link ld} adjusted into first day of next year
- * by using {@link LocalDate#with} and {@link TemporalAdjusters#firstDayOfNextYear}
- */
- return ld.with(TemporalAdjusters.firstDayOfNextYear());
- }
- static LocalDate plus() {
- LocalDate ld = DateAndTimes.LD_20150618;
- /**
- * Create a {@link LocalDate} from {@link ld} with 10 month later
- * by using {@link LocalDate#plusMonths} or {@link LocalDate#plus}
- */
- return ld.plusMonths(10);
- }
- static LocalDate minus() {
- LocalDate ld = DateAndTimes.LD_20150618;
- /**
- * Create a {@link LocalDate} from {@link ld} with 10 days before
- * by using {@link LocalDate#minusDays} or {@link LocalDate#minus}
- */
- return ld.minus(10, ChronoUnit.DAYS);
- }
- static LocalDate plusPeriod() {
- LocalDate ld = DateAndTimes.LD_20150618;
- /**
- * Define a {@link Period} of 1 year 2 month 3 days
- * Create a {@link LocalDate} adding the period to {@link ld} by using {@link LocalDate#plus}
- */
- return ld.plus(Period.of(1,2,3));
- }
- static boolean isAfter() {
- LocalDate ld = DateAndTimes.LD_20150618;
- LocalDate ld2 = DateAndTimes.LD_20150807;
- /**
- * Check whether {@link ld2} is after {@link ld} or not
- * by using {@link LocalDate#isAfter} or {@link LocalDate#isBefore}
- */
- return ld2.isAfter(ld);
- }
- static Period until() {
- LocalDate ld = DateAndTimes.LD_20150618;
- LocalDate ld2 = DateAndTimes.LD_20150807;
- /**
- * Create a period from {@link ld} till {@link ld2}
- * by using {@link LocalDate#until}
- */
- return Period.between(ld, ld2);
- }
- }
- class DateAndTimes {
- public static final LocalDate LD_20150618 = LocalDate.of(2015, 6, 18);
- public static final LocalDate LD_20150807 = LocalDate.of(2015, 8, 7);
- }
- /////////
- LocalTime Problem 2 (1 / 2)
- import java.time.Duration;
- import java.time.LocalTime;
- import java.time.temporal.ChronoField;
- import java.time.temporal.ChronoUnit;
- /**
- * LocalTime API tests
- */
- public class LocalTimeTest {
- public static void main(String[] args) {
- System.out.println(localTimeOfHourToMinute());
- System.out.println(localTimeOfHourToNanoSec());
- System.out.println(localTimeParse());
- System.out.println(localTimeWith());
- System.out.println(localTimePlus());
- System.out.println(localTimeMinus());
- System.out.println(localTimeMinusDuration());
- System.out.println(localDateIsBefore());
- System.out.println(localTimeTruncatedTo());
- }
- static LocalTime localTimeOfHourToMinute() {
- /**
- * Create a {@link LocalTime} of 23:07 by using {@link LocalTime#of}
- */
- return LocalTime.of(23, 07);
- }
- static LocalTime localTimeOfHourToNanoSec() {
- /**
- * Create a {@link LocalTime} of 23:07:03.1 by using {@link LocalTime#of}
- */
- return LocalTime.of(23, 07, 03, 100000000);
- }
- static LocalTime localTimeParse() {
- /**
- * Create a {@link LocalTime} of 23:07:03.1 from String by using {@link LocalTime#parse}
- */
- return LocalTime.parse("23:07:03.1");
- }
- static LocalTime localTimeWith() {
- LocalTime lt = DateAndTimes.LT_23073050;
- /**
- * Create a {@link LocalTime} from {@link lt} with hour 21
- * by using {@link LocalTime#withHour} or {@link LocalTime#with}
- */
- return lt.withHour(21);
- }
- static LocalTime localTimePlus() {
- LocalTime lt = DateAndTimes.LT_23073050;
- /**
- * Create a {@link LocalTime} from {@link lt} with 30 minutes later
- * by using {@link LocalTime#plusMinutes} or {@link LocalTime#plus}
- */
- return lt.plusMinutes(30);
- }
- static LocalTime localTimeMinus() {
- LocalTime lt = DateAndTimes.LT_23073050;
- /**
- * Create a {@link LocalTime} from {@link lt} with 3 hours before
- * by using {@link LocalTime#minusHours} or {@link LocalTime#minus}
- */
- return lt.minusHours(3);
- }
- static LocalTime localTimeMinusDuration() {
- LocalTime lt = DateAndTimes.LT_23073050;
- /**
- * Define a {@link Duration} of 3 hours 30 minutes and 20.2 seconds
- * Create a {@link LocalTime} subtracting the duration from {@link lt} by using {@link LocalTime#minus}
- */
- return lt.minus(Duration.ofMillis((3*3600+30*60+20)*1000+200));
- }
- static boolean localDateIsBefore() {
- LocalTime lt = DateAndTimes.LT_23073050;
- LocalTime lt2 = DateAndTimes.LT_12100000;
- /**
- * Check whether {@link lt2} is before {@link lt} or not
- * by using {@link LocalTime#isAfter} or {@link LocalTime#isBefore}
- */
- return lt.isAfter(lt2);
- }
- static LocalTime localTimeTruncatedTo() {
- LocalTime lt = DateAndTimes.LT_23073050;
- /**
- * Create a {@link LocalTime} from {@link lt} truncated to minutes by using {@link LocalTime#truncatedTo}
- */
- return lt.truncatedTo(ChronoUnit.MINUTES);
- }
- static class DateAndTimes {
- public static final LocalTime LT_23073050 = LocalTime.of(23, 7, 30, 500000000);
- public static final LocalTime LT_12100000 = LocalTime.of(12, 10);
- }
- }
- ////////////////
- LocalDateTime Problem 3 (1 / 3)
- import java.time.LocalDate;
- import java.time.LocalDateTime;
- import java.time.LocalTime;
- import java.time.format.DateTimeFormatter;
- import java.time.temporal.ChronoUnit;
- import java.time.temporal.TemporalAdjuster;
- import java.time.temporal.TemporalAdjusters;
- /**
- * LocalDateTime tests
- */
- public class LocalDateTimeTest {
- public static void main(String[] args) {
- System.out.println(localDateTimeOf());
- System.out.println(localDateTimeParse());
- System.out.println(localTimeWith());
- System.out.println(localDatePlusMinus());
- System.out.println(localDateTimeFormat());
- System.out.println(toLocalDateAndTime());
- System.out.println(toLocalDateTime());
- }
- static LocalDateTime localDateTimeOf() {
- /**
- * Create a {@link LocalDateTime} of 2015-06-20 23:07:30 by using {@link LocalDateTime#of}
- */
- return LocalDateTime.of(LocalDate.of(2015, 06, 20), LocalTime.of(23, 07, 30));
- }
- static LocalDateTime localDateTimeParse() {
- /**
- * Create a {@link LocalDateTime} of 2015-06-20 23:07:30 by using {@link LocalDateTime#parse}
- */
- return LocalDateTime.parse("2015-06-20t23:07:30");
- }
- static LocalDateTime localTimeWith() {
- LocalDateTime ldt = DateAndTimes.LDT_20150618_23073050;
- /**
- * Create a {@link LocalDateTime} from {@link ldt}
- * with first day of the next month and also truncated to hours.
- */
- return ldt.with(TemporalAdjusters.firstDayOfNextMonth()).truncatedTo(ChronoUnit.HOURS);
- }
- static LocalDateTime localDatePlusMinus() {
- LocalDateTime ldt = DateAndTimes.LDT_20150618_23073050;
- /**
- * Create a {@link LocalDateTime} from {@link ldt} with 10 month later and 5 hours before
- * by using {@link LocalDateTime#plus*} or {@link LocalDateTime#minus*}
- */
- return ldt.plus(10, ChronoUnit.MONTHS).minus(5, ChronoUnit.HOURS);
- }
- static String localDateTimeFormat() {
- LocalDateTime ldt = DateAndTimes.LDT_20150618_23073050;
- /**
- * Format {@link ldt} to a {@link String} as "2015_06_18_23_07_30"
- * by using {@link LocalDateTime#format} and {@link DateTimeFormatter#ofPattern}
- */
- return ldt.format(DateTimeFormatter.ofPattern("2015_06_18_23_07_30"));
- }
- static String toLocalDateAndTime() {
- LocalDateTime ldt = DateAndTimes.LDT_20150618_23073050;
- /**
- * Create a {@link LocalDate} and a {@link LocalTime} from {@link ldt}
- * by using {@link LocalDateTime#toLocalDate} and {@link LocalDateTime#toLocalTime}
- */
- LocalDate localDate = ldt.toLocalDate();
- LocalTime localTime = ldt.toLocalTime();
- return localDate.toString() + localTime.toString();
- }
- static String toLocalDateTime() {
- LocalDate ld = DateAndTimes.LD_20150618;
- LocalTime lt = DateAndTimes.LT_23073050;
- /**
- * Create two equal {@link LocalDateTime} from {@link ld} and {@link lt}
- * by using {@link LocalDate#atTime} and {@link LocalTime#atDate}
- */
- LocalDateTime localDateTime1 = ld.atTime(lt);
- LocalDateTime localDateTime2 = lt.atDate(ld);
- return localDateTime1.toString() + " " + localDateTime2.toString();
- }
- static class DateAndTimes {
- public static final LocalDate LD_20150618 = LocalDate.of(2015, 6, 18);
- public static final LocalTime LT_23073050 = LocalTime.of(23, 7, 30, 500000000);
- public static final LocalDateTime LDT_20150618_23073050 = LocalDateTime.of(2015, 6, 18, 23, 7, 30, 500000000);
- }
- }
- /////////
- ZonedDateTime Problem 4 (1 / 1)
- import java.time.LocalDate;
- import java.time.LocalDateTime;
- import java.time.LocalTime;
- import java.time.ZoneId;
- import java.time.ZonedDateTime;
- import java.time.format.DateTimeFormatter;
- /**
- * ZonedDateTime tests
- */
- public class ZonedDateTimeTest {
- public static void main(String[] args) {
- System.out.println(zonedDateTimeOf());
- System.out.println(zonedDateTimeParse());
- System.out.println(zonedDateTimeFormat());
- System.out.println(toPST());
- System.out.println(sameInstantAs());
- System.out.println(sameLocalAs());
- }
- static ZonedDateTime zonedDateTimeOf() {
- /**
- * Create a {@link ZonedDateTime} with time of 2015-07-10 2:14:25.000 as Japan Standard Time
- * by using {@link ZonedDateTime#of} and {@link ZoneId#of}
- */
- return ZonedDateTime.of(LocalDate.of(2015, 07, 10), LocalTime.of(2, 14, 25,000), ZoneId.of("Asia/Tokyo"));
- }
- static ZonedDateTime zonedDateTimeParse() {
- /**
- * Create a {@link ZonedDateTime} with time of 2015-06-18 23:07:25.000 as Japan Standard Time
- * by using {@link ZonedDateTime#parse}
- */
- return ZonedDateTime.parse("2015-06-18t23:07:25+09:00[Asia/Tokyo]");
- }
- static String zonedDateTimeFormat() {
- ZonedDateTime zdt = DateAndTimes.ZDT_20150618_23073050;
- /**
- * Format {@link zdt} to a {@link String} as "2015_06_18_23_07_30_JST"
- * by using {@link ZonedDateTime#format}
- */
- return zdt.format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss_z"));
- }
- static ZonedDateTime toPST() {
- LocalDateTime ldt = DateAndTimes.LDT_20150618_23073050;
- /**
- * Create a {@link ZonedDateTime} from {@link ldt} with Pacific Standard Time
- */
- ZoneId zone=ZoneId.of("America/Los_Angeles");
- return ZonedDateTime.of(ldt, zone);
- }
- static ZonedDateTime sameInstantAs() {
- ZonedDateTime zdt = DateAndTimes.ZDT_20150618_23073050;
- /**
- * Create a {@link ZonedDateTime} same instant as {@link zdt} with Pacific Standard Time
- * by using {@link ZonedDateTime#withZoneSameInstant}
- */
- return zdt.withZoneSameInstant(ZoneId.of(("America/Los_Angeles")));
- }
- static ZonedDateTime sameLocalAs() {
- ZonedDateTime zdt = DateAndTimes.ZDT_20150618_23073050;
- /**
- * Create a {@link ZonedDateTime} same local time as {@link zdt} with Pacific Standard Time
- * by using {@link ZonedDateTime#withZoneSameLocal}
- */
- return zdt.withZoneSameLocal(ZoneId.of(("America/Los_Angeles")));
- }
- static class DateAndTimes {
- public static final LocalDateTime LDT_20150618_23073050 = LocalDateTime.of(2015, 6, 18, 23, 7, 30, 500000000);
- public static final ZonedDateTime
- ZDT_20150618_23073050 = ZonedDateTime.of(LDT_20150618_23073050, ZoneId.of("Asia/Tokyo"));
- }
- }
- ///////////
- Лаб 5.
- ///////
- Комплексни броеви Problem 1 (1 / 2)
- import java.util.Collections;
- import java.util.LinkedList;
- import java.util.Scanner;
- class ComplexNumber<T extends Number,U extends Number> implements Comparable<ComplexNumber> {
- T real;
- U imaginary;
- public ComplexNumber(T real, U imaginary) {
- this.real = real;
- this.imaginary = imaginary;
- }
- T getReal(){return real;}
- U getImaginary(){return imaginary;}
- public double modul(){
- return Math.sqrt(real.doubleValue()*real.doubleValue()+imaginary.doubleValue()*imaginary.doubleValue());
- }
- @Override
- public int compareTo(ComplexNumber c) {
- if (modul()>c.modul())return 1;
- else if(modul()==c.modul())return 0;
- else return -1;
- }
- public String toString(){
- if(imaginary.doubleValue()>=0)
- return String.format("%.2f+%.2fi",real.doubleValue(),imaginary.doubleValue());
- else
- return String.format("%.2f%.2fi",real.doubleValue(),imaginary.doubleValue());
- }
- }
- public class ComplexNumberTest {
- public static void main(String[] args) {
- Scanner jin = new Scanner(System.in);
- int k = jin.nextInt();
- if ( k == 0 ) { //test simple functions int
- int r = jin.nextInt();int i = jin.nextInt();
- ComplexNumber<Integer, Integer> c = new ComplexNumber<Integer, Integer>(r, i);
- System.out.println(c);
- System.out.println(c.getReal());
- System.out.println(c.getImaginary());
- System.out.println(c.modul());
- }
- if ( k == 1 ) { //test simple functions float
- float r = jin.nextFloat();
- float i = jin.nextFloat();
- ComplexNumber<Float, Float> c = new ComplexNumber<Float, Float>(r, i);
- System.out.println(c);
- System.out.println(c.getReal());
- System.out.println(c.getImaginary());
- System.out.println(c.modul());
- }
- if ( k == 2 ) { //compareTo int
- LinkedList<ComplexNumber<Integer,Integer>> complex = new LinkedList<ComplexNumber<Integer,Integer>>();
- while ( jin.hasNextInt() ) {
- int r = jin.nextInt(); int i = jin.nextInt();
- complex.add(new ComplexNumber<Integer, Integer>(r, i));
- }
- System.out.println(complex);
- Collections.sort(complex);
- System.out.println(complex);
- }
- if ( k == 3 ) { //compareTo double
- LinkedList<ComplexNumber<Double,Double>> complex = new LinkedList<ComplexNumber<Double,Double>>();
- while ( jin.hasNextDouble() ) {
- double r = jin.nextDouble(); double i = jin.nextDouble();
- complex.add(new ComplexNumber<Double, Double>(r, i));
- }
- System.out.println(complex);
- Collections.sort(complex);
- System.out.println(complex);
- }
- if ( k == 4 ) { //compareTo mixed
- LinkedList<ComplexNumber<Double,Integer>> complex = new LinkedList<ComplexNumber<Double,Integer>>();
- while ( jin.hasNextDouble() ) {
- double r = jin.nextDouble(); int i = jin.nextInt();
- complex.add(new ComplexNumber<Double, Integer>(r, i));
- }
- System.out.println(complex);
- Collections.sort(complex);
- System.out.println(complex);
- }
- }
- }
- ////////////////
- Генерички распоредувач Problem 2 (1 / 27)
- import java.time.Instant;
- import java.time.LocalDateTime;
- import java.time.Period;
- import java.time.ZoneId;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.List;
- import java.util.Scanner;
- import java.util.stream.Collectors;
- import java.util.Comparator;
- public class SchedulerTest {
- static final LocalDateTime TIME = LocalDateTime.of(2016, 10, 25, 10, 15);
- public static void main(String[] args) {
- Scanner jin = new Scanner(System.in);
- int k = jin.nextInt();
- if (k == 0) { //test Timestamp with String
- Timestamp<String> t = new Timestamp<>(TIME, jin.next());
- System.out.println(t);
- System.out.println(t.getTime());
- System.out.println(t.getElement());
- }
- if (k == 1) { //test Timestamp with ints
- Timestamp<Integer> t1 = new Timestamp<>(TIME, jin.nextInt());
- System.out.println(t1);
- System.out.println(t1.getTime());
- System.out.println(t1.getElement());
- Timestamp<Integer> t2 = new Timestamp<>(TIME.plusDays(10), jin.nextInt());
- System.out.println(t2);
- System.out.println(t2.getTime());
- System.out.println(t2.getElement());
- System.out.println(t1.compareTo(t2));
- System.out.println(t2.compareTo(t1));
- System.out.println(t1.equals(t2));
- System.out.println(t2.equals(t1));
- }
- if (k == 2) {//test Timestamp with String, complex
- Timestamp<String> t1 = new Timestamp<>(ofEpochMS(jin.nextLong()), jin.next());
- System.out.println(t1);
- System.out.println(t1.getTime());
- System.out.println(t1.getElement());
- Timestamp<String> t2 = new Timestamp<>(ofEpochMS(jin.nextLong()), jin.next());
- System.out.println(t2);
- System.out.println(t2.getTime());
- System.out.println(t2.getElement());
- System.out.println(t1.compareTo(t2));
- System.out.println(t2.compareTo(t1));
- System.out.println(t1.equals(t2));
- System.out.println(t2.equals(t1));
- }
- if (k == 3) { //test Scheduler with String
- Scheduler<String> scheduler = new Scheduler<>();
- LocalDateTime now = LocalDateTime.now();
- scheduler.add(new Timestamp<>(now.minusHours(2), jin.next()));
- scheduler.add(new Timestamp<>(now.minusHours(1), jin.next()));
- scheduler.add(new Timestamp<>(now.minusHours(4), jin.next()));
- scheduler.add(new Timestamp<>(now.plusHours(2), jin.next()));
- scheduler.add(new Timestamp<>(now.plusHours(4), jin.next()));
- scheduler.add(new Timestamp<>(now.plusHours(1), jin.next()));
- scheduler.add(new Timestamp<>(now.plusHours(5), jin.next()));
- System.out.println(scheduler.next().getElement());
- System.out.println(scheduler.last().getElement());
- List<Timestamp<String>> result = scheduler.getAll(now.minusHours(3), now.plusHours(4).plusMinutes(15));
- String out = result.stream()
- .sorted()
- .map(Timestamp::getElement)
- .collect(Collectors.joining(", "));
- System.out.println(out);
- }
- if (k == 4) {//test Scheduler with ints complex
- Scheduler<Integer> scheduler = new Scheduler<>();
- int counter = 0;
- ArrayList<Timestamp<Integer>> forRemoval = new ArrayList<>();
- while (jin.hasNextLong()) {
- Timestamp<Integer> ti = new Timestamp<>(ofEpochMS(jin.nextLong()), jin.nextInt());
- if ((counter & 7) == 0) {
- forRemoval.add(ti);
- }
- scheduler.add(ti);
- ++counter;
- }
- jin.next();
- while (jin.hasNextLong()) {
- LocalDateTime left = ofEpochMS(jin.nextLong());
- LocalDateTime right = ofEpochMS(jin.nextLong());
- List<Timestamp<Integer>> res = scheduler.getAll(left, right);
- Collections.sort(res);
- System.out.println(left + " <: " + print(res) + " >: " + right);
- }
- System.out.println("test");
- List<Timestamp<Integer>> res = scheduler.getAll(ofEpochMS(0), ofEpochMS(Long.MAX_VALUE));
- Collections.sort(res);
- System.out.println(print(res));
- forRemoval.forEach(scheduler::remove);
- res = scheduler.getAll(ofEpochMS(0), ofEpochMS(Long.MAX_VALUE));
- Collections.sort(res);
- System.out.println(print(res));
- }
- }
- private static LocalDateTime ofEpochMS(long ms) {
- return LocalDateTime.ofInstant(Instant.ofEpochMilli(ms), ZoneId.systemDefault());
- }
- private static <T> String print(List<Timestamp<T>> res) {
- if (res == null || res.size() == 0) return "NONE";
- return res.stream()
- .map(each -> each.getElement().toString())
- .collect(Collectors.joining(", "));
- }
- }
- class Timestamp <T> implements Comparable<Timestamp<T>>{
- private LocalDateTime time;
- private T element;
- public Timestamp(LocalDateTime time, T element) {
- this.time = time;
- this.element = element;
- }
- public LocalDateTime getTime() {
- return time;
- }
- public T getElement() {
- return element;
- }
- public int compareTo(Timestamp t)
- {
- if(t.time.isAfter(time))
- return -1;
- else if(t.time.isBefore(time))
- return 1;
- else return 0;
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- Timestamp other = (Timestamp) obj;
- /*if (element == null) {
- if (other.element != null)
- return false;
- } else if (!element.equals(other.element))
- return false;*/
- if (time == null) {
- if (other.time != null)
- return false;
- } else if (!time.equals(other.time))
- return false;
- return true;
- }
- public String toString(){
- return String.format("%s %s",time,element);
- }
- }
- class Scheduler<T>{
- private Timestamp<T> [] ts;
- int count;
- public Scheduler(){
- ts=new Timestamp[947];
- count=0;
- }
- public void add(Timestamp<T> t)
- {
- ts[count]=t;
- count++;
- }
- public boolean remove(Timestamp<T> t)
- {
- for(int i=0;i<count;i++)
- {
- if(t.equals(ts[i]))
- {
- for(int j=i;j<count-1;j++)
- {
- ts[j]=ts[j+1];
- }
- ts[count-1]=null;
- count--;
- return true;
- }
- }
- return false;
- }
- public Timestamp<T> next(){
- Timestamp<T> tmp=null;
- LocalDateTime now=LocalDateTime.now();
- for(int i=1;i<count;i++)
- {
- if(ts[i].getTime().isAfter(now))
- {
- if(tmp==null)
- {
- tmp=ts[i];
- }
- else if(ts[i].getTime().isBefore(tmp.getTime()))
- {
- tmp=ts[i];
- }
- }
- }
- return tmp;
- }
- public Timestamp<T> last(){
- Timestamp<T> tmp=null;
- LocalDateTime now=LocalDateTime.now();
- for(int i=1;i<count;i++)
- {
- if(ts[i].getTime().isBefore(now))
- {
- if(tmp==null)
- {
- tmp=ts[i];
- }
- if(ts[i].getTime().isAfter(tmp.getTime()))
- {
- tmp=ts[i];
- }
- }
- }
- return tmp;
- }
- List<Timestamp<T>>getAll(LocalDateTime begin, LocalDateTime end)
- {
- List list=new ArrayList<>();
- for(int i=0;i<count;i++)
- {
- if(ts[i].getTime().isAfter(begin)&&ts[i].getTime().isBefore(end))
- {
- list.add(ts[i]);
- }
- }
- return list;
- }
- }
- ////////////
- Генерички ред Problem 3 (1 / 2)
- import java.util.LinkedList;
- import java.util.Scanner;
- class EmptyQueueException extends Exception{
- }
- class Node<T>
- {
- private T element;
- private Node<T> next;
- public Node(T element, Node<T> next) {
- this.element = element;
- this.next = next;
- }
- public T getElement() {
- return element;
- }
- public Node<T> getNext() {
- return next;
- }
- public void setNext(Node<T> next) {
- this.next = next;
- }
- }
- class Queue<T>{
- private Node<T> first,last;
- public Queue()
- {
- first=null;
- last=null;
- }
- public boolean isEmpty()
- {
- if(first==null)
- return true;
- else return false;
- }
- public void enqueue(T element){
- if(first==null)
- {
- first=new Node<T>(element,null);
- last=first;
- }
- else
- {
- last.setNext(new Node<T>(element,null));
- last=last.getNext();
- }
- }
- public T dequeue()throws EmptyQueueException
- {
- if(isEmpty())throw new EmptyQueueException();
- T out=first.getElement();
- first=first.getNext();
- return out;
- }
- public T peek()throws EmptyQueueException
- {
- if(isEmpty())throw new EmptyQueueException();
- T out=first.getElement();
- return out;
- }
- public T inspect() throws EmptyQueueException
- {
- if(isEmpty())throw new EmptyQueueException();
- T out=last.getElement();
- return out;
- }
- public int count(){
- int br=0;
- if(first!=null)
- {
- Node<T> tmp=first;
- while(tmp!=null)
- {
- br++;
- tmp=tmp.getNext();
- }
- }
- return br;
- }
- }
- public class QueueTest {
- public static void main(String[] args) throws EmptyQueueException {
- Scanner jin = new Scanner(System.in);
- int k = jin.nextInt();
- if ( k == 0 ) { //Simple test case with one int element
- int t = jin.nextInt();
- Queue<Integer> queue = new Queue<Integer>();
- System.out.println("Queue empty? - "+queue.isEmpty());
- System.out.println("Queue count? - "+queue.count());
- System.out.println("Queue enqueue "+t);
- queue.enqueue(t);
- System.out.println("Queue empty? - "+queue.isEmpty());
- System.out.println("Queue count? - "+queue.count());
- System.out.println("Queue dequeue? - "+queue.dequeue());
- System.out.println("Queue empty? - "+queue.isEmpty());
- System.out.println("Queue count? - "+queue.count());
- }
- if ( k == 1 ) { //a more complex test with strings
- Queue<String> queue = new Queue<String>();
- int counter = 0;
- while ( jin.hasNextInt() ) {
- String t = jin.next();
- queue.enqueue(t);
- ++counter;
- }
- for ( int i = 0 ; i < counter ; ++i ) {
- System.out.println(queue.dequeue());
- }
- queue.enqueue(jin.next());
- System.out.println("Queue inspect? - "+queue.inspect());
- System.out.println("Queue peek? - "+queue.peek());
- queue.enqueue(queue.dequeue());
- queue.enqueue(jin.next());
- System.out.println("Queue inspect? - "+queue.inspect());
- System.out.println("Queue peek? - "+queue.peek());
- }
- if ( k == 2 ) {
- Queue<String> queue = new Queue<String>();
- String next = "";
- int counter = 0;
- while ( true ) {
- next = jin.next();
- if ( next.equals("stop") ) break;
- queue.enqueue(next);
- ++counter;
- }
- while ( !queue.isEmpty() ) {
- if ( queue.count()<counter) System.out.print(" ");
- System.out.print(queue.dequeue());
- }
- }
- if ( k == 3 ) { //random testing
- Queue<Double> queue = new Queue<Double>();
- LinkedList<Double> java_queue = new LinkedList<Double>();
- boolean flag = true;
- int n = jin.nextInt();
- for ( int i = 0 ; i < n ; ++i ) {
- double q = Math.random();
- if ( q < 0.5 ) {
- double t = Math.random();
- queue.enqueue(t);
- java_queue.addFirst(t);
- }
- if ( q < 0.8&&q >= 0.5 ) {
- if ( ! java_queue.isEmpty() ) {
- double t1 = java_queue.removeLast();
- double t2 = queue.dequeue();
- flag &= t1==t2;
- }
- else {
- flag &= java_queue.isEmpty()==queue.isEmpty();
- }
- }
- if ( q < 0.9 && q >= 0.8 ) {
- if ( ! java_queue.isEmpty() ) {
- double t1 = java_queue.peekLast();
- double t2 = queue.peek();
- flag &= t1==t2;
- }
- else {
- flag &= java_queue.isEmpty()==queue.isEmpty();
- }
- }
- if ( q < 1 && q >= 0.9 ) {
- if ( ! java_queue.isEmpty() ) {
- double t1 = java_queue.peekFirst();
- double t2 = queue.inspect();
- flag &= t1==t2;
- }
- else {
- flag &= java_queue.isEmpty()==queue.isEmpty();
- }
- }
- flag &= java_queue.size()==queue.count();
- }
- System.out.println("Compared to the control queue the results were the same? - "+flag);
- }
- if ( k == 4 ) { //performance testing
- Queue<Double> queue = new Queue<Double>();
- int n = jin.nextInt();
- for ( int i = 0 ; i < n ; ++i ) {
- if ( Math.random() < 0.5 ) {
- queue.enqueue(Math.random());
- }
- else {
- if ( ! queue.isEmpty() ) {
- queue.dequeue();
- }
- }
- }
- System.out.println("You implementation finished in less then 3 seconds, well done!");
- }
- if ( k == 5 ) { //Exceptions testing
- Queue<String> queue = new Queue<String>();
- try {
- queue.dequeue();
- }
- catch ( Exception e ) {
- System.out.println(e.getClass().getSimpleName());
- }
- try {
- queue.peek();
- }
- catch ( Exception e ) {
- System.out.println(e.getClass().getSimpleName());
- }
- try {
- queue.inspect();
- }
- catch ( Exception e ) {
- System.out.println(e.getClass().getSimpleName());
- }
- }
- }
- }
- /////////////////
- Генерички контејнер со променлива должина Problem 4 (2 / 21)
- import java.util.Scanner;
- import java.util.Arrays;
- import java.util.LinkedList;
- class ResizableArray<T> {
- private T [] niza;
- private int size;
- public ResizableArray() {
- niza= (T[])new Object[100];
- size=0;
- }
- public void addElement(T element) {
- if (size==niza.length) niza=Arrays.copyOf(niza,niza.length+1);
- niza[size++]=element;
- }
- public boolean removeElement (T element) {
- for (int i=0;i<size;i++)
- {
- if (niza[i].equals(element))
- {
- for (int j=i;j<size-1;j++) {
- niza[i]=niza[j+1];
- }
- size--;
- return true;
- }
- }
- return false;
- }
- public int count() {
- return size;
- }
- public boolean contains(T element) {
- for (int i=0;i<size;i++)
- {
- if(niza[i].equals(element)) {
- return true;
- }
- }
- return false;
- }
- public boolean isEmpty() {
- if(niza.length==0) return false;
- else return true;
- }
- public T elementAt(int index) throws ArrayIndexOutOfBoundsException {
- if(index<0||index>=size) throw new ArrayIndexOutOfBoundsException();
- else return niza[index];
- }
- public Object[] toArray() {
- return niza;
- }
- public static <T> void copyAll(ResizableArray<? super T> dest , ResizableArray<? extends T>src) {
- for(int i = 0, j = dest.size; i < src.size; i++,j++)
- dest.niza[j] = src.niza[i];
- dest.size = dest.size+ src.size;
- }
- }
- class IntegerArray extends ResizableArray<Integer> {
- public double sum() {
- int s=0;
- for (int i=0;i<count();i++) {
- s=s+elementAt(i);
- } return s;
- }
- public double mean() {
- return sum()/count();
- }
- public int countNonZero () {
- int br=0;
- for (int i=0;i<count();i++) {
- if (elementAt(i)!=0) {
- br++;
- }
- }
- return br;
- }
- public IntegerArray increment(int offset) {
- IntegerArray tmp = new IntegerArray();
- for(int i = 0; i < count(); ++i)
- tmp.addElement(elementAt(i) + offset);
- return tmp;
- }
- public IntegerArray distinct() {
- IntegerArray tmp = new IntegerArray();
- IntegerArray.copyAll(tmp, this);
- for (int i=0;i<tmp.count();i++) {
- for (int j=0;j<i;j++) {
- if (tmp.elementAt(i)==tmp.elementAt(j))
- {
- tmp.removeElement(tmp.elementAt(j));
- i--;
- j--;
- }
- }
- }
- return tmp;
- }
- }
- public class ResizableArrayTest {
- public static void main(String[] args) {
- Scanner jin = new Scanner(System.in);
- int test = jin.nextInt();
- if ( test == 0 ) { //test ResizableArray on ints
- ResizableArray<Integer> a = new ResizableArray<Integer>();
- System.out.println(a.count());
- int first = jin.nextInt();
- a.addElement(first);
- System.out.println(a.count());
- int last = first;
- while ( jin.hasNextInt() ) {
- last = jin.nextInt();
- a.addElement(last);
- }
- System.out.println(a.count());
- System.out.println(a.contains(first));
- System.out.println(a.contains(last));
- System.out.println(a.removeElement(first));
- System.out.println(a.contains(first));
- System.out.println(a.count());
- }
- if ( test == 1 ) { //test ResizableArray on strings
- ResizableArray<String> a = new ResizableArray<String>();
- System.out.println(a.count());
- String first = jin.next();
- a.addElement(first);
- System.out.println(a.count());
- String last = first;
- for ( int i = 0 ; i < 4 ; ++i ) {
- last = jin.next();
- a.addElement(last);
- }
- System.out.println(a.count());
- System.out.println(a.contains(first));
- System.out.println(a.contains(last));
- System.out.println(a.removeElement(first));
- System.out.println(a.contains(first));
- System.out.println(a.count());
- ResizableArray<String> b = new ResizableArray<String>();
- ResizableArray.copyAll(b, a);
- System.out.println(b.count());
- System.out.println(a.count());
- System.out.println(a.contains(first));
- System.out.println(a.contains(last));
- System.out.println(b.contains(first));
- System.out.println(b.contains(last));
- ResizableArray.copyAll(b, a);
- System.out.println(b.count());
- System.out.println(a.count());
- System.out.println(a.contains(first));
- System.out.println(a.contains(last));
- System.out.println(b.contains(first));
- System.out.println(b.contains(last));
- System.out.println(b.removeElement(first));
- System.out.println(b.contains(first));
- System.out.println(b.removeElement(first));
- System.out.println(b.contains(first));
- System.out.println(a.removeElement(first));
- ResizableArray.copyAll(b, a);
- System.out.println(b.count());
- System.out.println(a.count());
- System.out.println(a.contains(first));
- System.out.println(a.contains(last));
- System.out.println(b.contains(first));
- System.out.println(b.contains(last));
- }
- if ( test == 2 ) { //test IntegerArray
- IntegerArray a = new IntegerArray();
- System.out.println(a.isEmpty());
- while ( jin.hasNextInt() ) {
- a.addElement(jin.nextInt());
- }
- jin.next();
- System.out.println(a.sum());
- System.out.println(a.mean());
- System.out.println(a.countNonZero());
- System.out.println(a.count());
- IntegerArray b = a.distinct();
- System.out.println(b.sum());
- IntegerArray c = a.increment(5);
- System.out.println(c.sum());
- if ( a.sum() > 100 )
- ResizableArray.copyAll(a, a);
- else
- ResizableArray.copyAll(a, b);
- System.out.println(a.sum());
- System.out.println(a.removeElement(jin.nextInt()));
- System.out.println(a.sum());
- System.out.println(a.removeElement(jin.nextInt()));
- System.out.println(a.sum());
- System.out.println(a.removeElement(jin.nextInt()));
- System.out.println(a.sum());
- System.out.println(a.contains(jin.nextInt()));
- System.out.println(a.contains(jin.nextInt()));
- }
- if ( test == 3 ) { //test insanely large arrays
- LinkedList<ResizableArray<Integer>> resizable_arrays = new LinkedList<ResizableArray<Integer>>();
- for ( int w = 0 ; w < 500 ; ++w ) {
- ResizableArray<Integer> a = new ResizableArray<Integer>();
- int k = 2000;
- int t = 1000;
- for ( int i = 0 ; i < k ; ++i ) {
- a.addElement(i);
- }
- a.removeElement(0);
- for ( int i = 0 ; i < t ; ++i ) {
- a.removeElement(k-i-1);
- }
- resizable_arrays.add(a);
- }
- System.out.println("You implementation finished in less then 3 seconds, well done!");
- }
- }
- }
- ////////////////
- Лаб 6.
- ////////////
- Супер-стринг Problem 1 (2 / 9)
- import java.util.LinkedList;
- import java.util.Scanner;
- import java.util.Stack;
- class SuperString{
- private LinkedList<String> superstring;
- private Stack<String> last;
- public SuperString() {
- superstring=new LinkedList<String>();
- last=new Stack<String>();
- }
- public void append(String s)
- {
- superstring.add(s);
- last.push(s);
- }
- public void insert(String s)
- {
- superstring.addFirst(s);
- last.push(s);
- }
- public boolean contains(String s)
- {
- return toString().contains(s);
- }
- public String toString()
- {
- StringBuilder sb=new StringBuilder();
- superstring.forEach(temp->sb.append(temp));
- return sb.toString();
- }
- public static String wordreverse(String s)
- {
- StringBuilder sb=new StringBuilder();
- for(int i=s.length()-1;i>=0;i--)
- {
- sb.append(s.charAt(i));
- }
- return sb.toString();
- }
- public void removeLast(int k)
- {
- for(int i=0;i<k;i++)
- {
- String lastword=last.pop();
- superstring.remove(wordreverse(lastword));
- superstring.remove(lastword);
- }
- }
- public void reverse()
- {
- LinkedList<String> revs=new LinkedList<String>();
- superstring.forEach(temp->revs.addFirst(wordreverse(temp)));
- superstring=revs;
- }
- }
- public class SuperStringTest {
- public static void main(String[] args) {
- Scanner jin = new Scanner(System.in);
- int k = jin.nextInt();
- if ( k == 0 ) {
- SuperString s = new SuperString();
- while ( true ) {
- int command = jin.nextInt();
- if ( command == 0 ) {//append(String s)
- s.append(jin.next());
- }
- if ( command == 1 ) {//insert(String s)
- s.insert(jin.next());
- }
- if ( command == 2 ) {//contains(String s)
- System.out.println(s.contains(jin.next()));
- }
- if ( command == 3 ) {//reverse()
- s.reverse();
- }
- if ( command == 4 ) {//toString()
- System.out.println(s);
- }
- if ( command == 5 ) {//removeLast(int k)
- s.removeLast(jin.nextInt());
- }
- if ( command == 6 ) {//end
- break;
- }
- }
- }
- }
- }
- ////////////////
- Листа на цели броеви Problem 2 (1 / 7)
- import java.util.ArrayList;
- import java.util.Scanner;
- class IntegerList{
- private ArrayList<Integer> integerlist;
- public IntegerList()
- {
- integerlist=new ArrayList<Integer>();
- }
- public IntegerList(Integer [] a)
- {
- integerlist=new ArrayList<Integer>(a.length);
- for(int i=0;i<a.length;i++)
- integerlist.add(a[i]);
- }
- private void addlargeridx(int el,int idx)
- {
- int length=integerlist.size();
- while(idx!=length)
- {
- integerlist.add(0);
- length++;
- }
- integerlist.add(el);
- }
- public void add(int el,int idx)
- {
- if(idx>=integerlist.size())
- addlargeridx(el,idx);
- else
- integerlist.add(idx, el);
- }
- public int remove(int idx) throws ArrayIndexOutOfBoundsException
- {
- if(idx<0)
- throw new ArrayIndexOutOfBoundsException();
- return integerlist.remove(idx);
- }
- public void set(int el,int idx)throws ArrayIndexOutOfBoundsException
- {
- if(idx<0)
- throw new ArrayIndexOutOfBoundsException();
- integerlist.set(idx, el);
- }
- public int get(int idx)throws ArrayIndexOutOfBoundsException
- {
- if(idx<0)
- throw new ArrayIndexOutOfBoundsException();
- return integerlist.get(idx);
- }
- public int size()
- {
- return integerlist.size();
- }
- public int count(int el)
- {
- //long n=integerlist.stream().filter(s->s.equals(el)).count();
- int c=0;
- for(Integer integ : integerlist)
- if(integ.equals(el))
- c++;
- return c;
- }
- public void removeDuplicates()
- {
- for(int i=0;i<integerlist.size()-1;i++)
- for(int j=i+1;j<integerlist.size();j++)
- if(integerlist.get(i).equals(integerlist.get(j)))
- {
- integerlist.remove(i);
- i--;
- break;
- }
- }
- public int sumFirst(int k)
- {
- int sum=0;
- int l=Math.min(k,integerlist.size());
- for(int i=0;i<l;i++)
- sum+=integerlist.get(i);
- return sum;
- }
- public int sumLast(int k)
- {
- int sum=0;
- int n=integerlist.size();
- int l=Math.max(n-k,0);
- for(int i=l;i<n;i++)
- sum+=integerlist.get(i);
- return sum;
- }
- public void shiftRight(int idx,int k)throws ArrayIndexOutOfBoundsException
- {
- if(idx<0)
- throw new ArrayIndexOutOfBoundsException();
- int el=integerlist.remove(idx);
- integerlist.add((idx+k)%(integerlist.size()+1), el);
- }
- public void shiftLeft(int idx,int k)throws ArrayIndexOutOfBoundsException
- {
- if(idx<0)
- throw new ArrayIndexOutOfBoundsException();
- int el=integerlist.remove(idx);
- int id1=k%(integerlist.size()+1);
- integerlist.add((idx-id1+integerlist.size()+1)%(integerlist.size()+1), el);
- }
- public IntegerList addValue(int value)
- {
- Integer a[]=new Integer[integerlist.size()];
- for(int i=0;i<integerlist.size();i++)
- a[i]=integerlist.get(i)+value;
- return new IntegerList(a);
- }
- }
- public class IntegerListTest {
- public static void main(String[] args) {
- Scanner jin = new Scanner(System.in);
- int k = jin.nextInt();
- if ( k == 0 ) { //test standard methods
- int subtest = jin.nextInt();
- if ( subtest == 0 ) {
- IntegerList list = new IntegerList();
- while ( true ) {
- int num = jin.nextInt();
- if ( num == 0 ) {
- list.add(jin.nextInt(), jin.nextInt());
- }
- if ( num == 1 ) {
- list.remove(jin.nextInt());
- }
- if ( num == 2 ) {
- print(list);
- }
- if ( num == 3 ) {
- break;
- }
- }
- }
- if ( subtest == 1 ) {
- int n = jin.nextInt();
- Integer a[] = new Integer[n];
- for ( int i = 0 ; i < n ; ++i ) {
- a[i] = jin.nextInt();
- }
- IntegerList list = new IntegerList(a);
- print(list);
- }
- }
- if ( k == 1 ) { //test count,remove duplicates, addValue
- int n = jin.nextInt();
- Integer a[] = new Integer[n];
- for ( int i = 0 ; i < n ; ++i ) {
- a[i] = jin.nextInt();
- }
- IntegerList list = new IntegerList(a);
- while ( true ) {
- int num = jin.nextInt();
- if ( num == 0 ) { //count
- System.out.println(list.count(jin.nextInt()));
- }
- if ( num == 1 ) {
- list.removeDuplicates();
- }
- if ( num == 2 ) {
- print(list.addValue(jin.nextInt()));
- }
- if ( num == 3 ) {
- list.add(jin.nextInt(), jin.nextInt());
- }
- if ( num == 4 ) {
- print(list);
- }
- if ( num == 5 ) {
- break;
- }
- }
- }
- if ( k == 2 ) { //test shiftRight, shiftLeft, sumFirst , sumLast
- int n = jin.nextInt();
- Integer a[] = new Integer[n];
- for ( int i = 0 ; i < n ; ++i ) {
- a[i] = jin.nextInt();
- }
- IntegerList list = new IntegerList(a);
- while ( true ) {
- int num = jin.nextInt();
- if ( num == 0 ) { //count
- list.shiftLeft(jin.nextInt(), jin.nextInt());
- }
- if ( num == 1 ) {
- list.shiftRight(jin.nextInt(), jin.nextInt());
- }
- if ( num == 2 ) {
- System.out.println(list.sumFirst(jin.nextInt()));
- }
- if ( num == 3 ) {
- System.out.println(list.sumLast(jin.nextInt()));
- }
- if ( num == 4 ) {
- print(list);
- }
- if ( num == 5 ) {
- break;
- }
- }
- }
- }
- public static void print(IntegerList il) {
- if ( il.size() == 0 ) System.out.print("EMPTY");
- for ( int i = 0 ; i < il.size() ; ++i ) {
- if ( i > 0 ) System.out.print(" ");
- System.out.print(il.get(i));
- }
- System.out.println();
- }
- }
- /////////////
- Лаб 7.
- /////////////
- Генерички магацин (Stack) Problem 1 (1 / 2)
- import java.util.Date;
- import java.util.EmptyStackException;
- import java.util.LinkedList;
- import java.util.Scanner;
- class Stack<T>{
- private T []stack;
- private int n;
- public Stack()
- {
- stack=(T[])new Object[100000];
- n=0;
- }
- public void push(T element)
- {
- stack[n++]=element;
- }
- public T peek() throws EmptyStackException
- {
- if(isEmpty())
- throw new EmptyStackException();
- return stack[n-1];
- }
- public T pop() throws EmptyStackException
- {
- if(isEmpty())
- throw new EmptyStackException();
- T pop=stack[n-1];
- stack[n-1]=null;
- n--;
- return pop;
- }
- public boolean isEmpty()
- {
- return n==0;
- }
- }
- public class StackTest {
- public static void main(String[] args) {
- Scanner jin = new Scanner(System.in);
- int k = jin.nextInt();
- System.out.println("Test#"+k);
- if ( k == 0 ) {
- System.out.println("testing: Stack::push(T) , Stack::pop():T , T is Integer");
- int n = jin.nextInt();
- Stack<Integer> stack = new Stack<Integer>();
- System.out.println("Pushing elements:");
- for ( int i = 1 ; i <= n ; ++i ) {
- if ( i > 1 ) System.out.print(" ");System.out.print(i);
- stack.push(i);
- }
- System.out.println();
- System.out.println("Poping elements:");
- for ( int i = n ; i >= 1 ; --i ) {
- if ( i < n ) System.out.print(" ");
- System.out.print(stack.pop());
- }
- System.out.println();
- }
- if ( k == 1 ) {
- System.out.println("testing: Stack::push(T) , Stack::pop():T , T is String");
- int n = jin.nextInt();
- Stack<String> stack = new Stack<String>();
- System.out.println("Pushing elements:");
- for ( int i = 0 ; i < n ; ++i ) {
- if ( i > 0 ) System.out.print(" ");
- String next = jin.next();System.out.print(next);
- stack.push(next);
- }
- System.out.println();
- System.out.println("Poping elements:");
- for ( int i = 0 ; i < n ; ++i ) {
- if ( i > 0 ) System.out.print(" ");
- System.out.print(stack.pop());
- }
- }
- if ( k == 2 ) {
- System.out.println("testing: Stack::push(T) , Stack::pop():T , Stack::isEmpty():boolean, T is Double");
- Stack<Double> stack = new Stack<Double>();
- System.out.println("Pushing elements:");
- boolean flag = false;
- while ( jin.hasNextDouble() ) {
- double d = jin.nextDouble();
- stack.push(d);
- if ( flag ) System.out.print(" ");
- System.out.printf("%.2f",d);
- flag = true;
- }
- int i = 0;
- System.out.println();
- System.out.println("Poping elements:");
- while ( ! stack.isEmpty() ) {
- if ( i > 0 ) System.out.print(" ");++i;
- System.out.printf("%.2f",stack.pop());
- }
- }
- if ( k == 3 ) {
- System.out.println("testing: Stack::push(T) , Stack::pop():T , Stack::isEmpty():boolean , Stack::peek():T , T is Long");
- int n = jin.nextInt();
- Stack<Long> stack = new Stack<Long>();
- LinkedList<Long> control_stack = new LinkedList<Long>();
- boolean exact = true;
- for ( int i = 0 ; exact&&i < n ; ++i ) {
- if ( Math.random() < 0.5 ) {//add
- long to_add = (long)(Math.random()*456156168);
- stack.push(to_add);control_stack.addFirst(to_add);
- }
- else {
- exact &= control_stack.isEmpty()==stack.isEmpty();
- if ( exact&&! stack.isEmpty() ) {
- if ( Math.random() > 0.7 ) exact &= control_stack.removeFirst().equals(stack.pop());
- else exact &= control_stack.peekFirst().equals(stack.peek());
- }
- }
- }
- System.out.println("Your stack outputs compared to the built in java stack were the same? "+exact);
- }
- if ( k == 4 ) {
- System.out.println("testing: Stack::pop():T , Stack::isEmpty():boolean , Stack::peek():T , T is Long");
- Stack<Date> test_stack = new Stack<Date>();
- System.out.println("Stack empty? "+test_stack.isEmpty());
- try {
- test_stack.pop();
- System.out.println("NO exeption was thrown when trying to pop from an empty stack!");
- } catch(Exception e) {
- System.out.print("Exeption thrown when trying to pop from an empty stack ");
- System.out.println(e.getClass().getSimpleName());
- }
- try {
- test_stack.peek();
- System.out.println("NO exeption was thrown when trying to peek in an empty stack!");
- } catch(Exception e) {
- System.out.print("Exeption thrown when trying to peek in an empty stack ");
- System.out.println(e.getClass().getSimpleName());
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement