Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ==== LAB.1 RIMSKI BROEVI ===
- 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 rimski = "";
- int l=0;
- while(n!=0) {
- l++;
- int k=n%10;
- n/=10;
- if(l==1) {
- rimski=digitToRoman(k,"I","V","X")+rimski;
- }
- if(l==2) {
- rimski=digitToRoman(k,"X","L","C")+rimski;
- }
- if(l==3) {
- rimski=digitToRoman(k,"C","D","M")+rimski;
- }
- if(l==4) {
- for(int i=0;i<k;i++){
- rimski="M"+rimski;
- }
- }
- }
- return rimski;
- }
- public static String digitToRoman(int k,String str1,String str2,String str3) {
- if(k<=3) {
- String rimski="";
- for(int i=0; i<k; i++)
- rimski=str1+rimski;
- return rimski;
- }
- else if(k==4) {
- return str1+str2;
- }
- else if(k==5) {
- return str2;
- }
- else if(k>=6&&k<=8) {
- String rimski=str2;
- for(int i=0; i<k-5; i++) {
- rimski=rimski+str1;
- }
- return rimski;
- }
- else if(k==9) {
- return str1+str3;
- }
- return "";
- }
- }
- === LAB.1 SISTEM ZA BANKARSKO RABOTENJE ===
- import java.util.*;
- import java.util.stream.Collectors;
- class Account {
- private String name;
- private long id;
- private String balance;
- static long idCounter = 0;
- public Account(String _name, String _balance){
- name = _name;
- balance = _balance;
- id = idCounter;
- idCounter++;
- }
- public Account(Account a){
- name = a.name;
- balance = a.balance;
- id = a.id;
- }
- public String getName(){return name;}
- public long getId(){return id;}
- public String getBalance(){return balance;}
- public void setBalance(String _balance){balance = _balance;}
- public String toString(){
- return "Name: " + name +"\nBalance: " + balance + "\n";
- }
- public boolean equals(Account a){
- if( a == null) return false;
- if( !a.getName().equals(name)) return false;
- if( !a.getBalance().equals(balance)) return false;
- if( a.getId() != id) return false;
- return true;
- }
- }
- class Transaction{
- protected long fromId;
- protected long toId;
- protected String description;
- protected String amount;
- public Transaction(long _fromId, long _toId, String _description, String _amount){
- fromId=_fromId; toId=_toId; description=_description; amount=_amount;
- }
- public String getAmount(){return amount;}
- public String getDescription(){return description;}
- public long getFromId(){return fromId;}
- public long getToId(){return toId;}
- public String getFlatAmount(){return "";}
- public int getPercent(){return 0;}
- public boolean equals(Transaction t){
- if(fromId != t.getFromId()){return false;}
- if(toId != t.getToId()){return false;}
- if(!amount.equals(t.getAmount())){return false;}
- if(!description.equals(t.getDescription())){return false;}
- return true;
- }
- }
- class FlatAmountProvisionTransaction extends Transaction{
- private String flatAmount;
- public FlatAmountProvisionTransaction(long from_id, long to_id,String amount, String flat_amount_provision){
- super(from_id, to_id, "FlatAmount", amount);
- flatAmount = flat_amount_provision;
- }
- public String getFlatAmount(){
- return flatAmount;
- }
- public boolean equals(Transaction t){
- if(t==null){return false;}
- if(!super.equals(t)){return false;}
- if(!flatAmount.equals(t.getFlatAmount())){return false;}
- return true;
- }
- }
- class FlatPercentProvisionTransaction extends Transaction{
- private int percent;
- public FlatPercentProvisionTransaction(long from_id, long to_id, String amount, int _percent){
- super(from_id, to_id, "FlatPercent", amount);
- percent = _percent;
- }
- public int getPercent(){
- return percent;
- }
- public boolean equals(Transaction t){
- if(t==null){return false;}
- if(!super.equals(t)){return false;}
- if(percent != t.getPercent()){return false;}
- return true;
- }
- }
- class Bank{
- private String name;
- Account[] accounts;
- private double totalAmountTransferred;
- private double totalProvision;
- public Bank(String _name, Account _accounts[]){
- name = _name;
- accounts = new Account[_accounts.length];
- for(int i=0; i < _accounts.length; i++){
- accounts[i] = new Account(_accounts[i]);
- }
- totalAmountTransferred = 0;
- totalProvision = 0;
- }
- public String totalTransfers(){return String.format("%.2f$", totalAmountTransferred);}
- public String totalProvision(){return String.format("%.2f$", totalProvision);}
- public boolean equals(Bank b){
- if(b == null) {return false;}
- if(!name.equals(b.name)) { return false;}
- if(accounts.length != b.accounts.length) { return false;}
- for(int i = 0; i < accounts.length;i++){
- if( !accounts[i].equals(b.accounts[i])) {return false;}
- }
- return true;
- }
- public Account[] getAccounts(){return accounts;}
- public String toString(){
- String s = "Name: "+name+"\n\n";
- for(int i = 0; i <accounts.length;i++)
- s+=accounts[i].toString();
- return s;
- }
- public boolean makeTransaction(Transaction T){
- boolean fromHere = false, toHere = false;
- double balFrom = 0, amount = 0, balTo = 0, tax = 0;
- int indexFrom = -1, indexTo = -1;
- for(int i=0;i<accounts.length;i++){
- if(accounts[i].getId()==T.getFromId()){
- String tempFrom = accounts[i].getBalance().substring(0, accounts[i].getBalance().length()-1);
- String tempTr = T.getAmount().substring(0,T.getAmount().length()-1);
- balFrom = Double.parseDouble(tempFrom);
- amount = Double.parseDouble(tempTr);
- indexFrom = i;
- if(balFrom>amount)
- fromHere = true;
- }
- if(accounts[i].getId()==T.getToId()){
- String tempTo = accounts[i].getBalance().substring(0, accounts[i].getBalance().length()-1);
- balTo = Double.parseDouble(tempTo);
- indexTo = i;
- toHere = true;
- }
- }
- if(fromHere == true&&toHere == true){
- totalAmountTransferred += amount ;
- if(T.getDescription().equals("FlatAmount")){
- tax = Double.parseDouble(T.getFlatAmount().substring(0,T.getFlatAmount().length()-1));
- if(indexFrom == indexTo){
- balFrom = balFrom - tax;
- String newBalFrom = String.format("%.2f$", balFrom);
- accounts[indexFrom].setBalance(newBalFrom);
- }
- else{
- balTo = balTo + amount;
- String newBalTo = String.format("%.2f$", balTo);
- accounts[indexTo].setBalance(newBalTo);
- amount = amount + tax;
- balFrom = balFrom - amount;
- String newBalFrom = String.format("%.2f$", balFrom);
- accounts[indexFrom].setBalance(newBalFrom);
- }
- totalProvision += tax;
- }
- if(T.getDescription().equals("FlatPercent")){
- tax = (double)T.getPercent();
- tax = Math.floor(amount)*tax/100;
- if(indexFrom == indexTo){
- balFrom = balFrom - tax;
- String newBalFrom = String.format("%.2f$", balFrom);
- accounts[indexFrom].setBalance(newBalFrom);
- }else{
- balTo = balTo + amount;
- amount = amount + tax;
- balFrom = balFrom - amount;
- String newBalTo = String.format("%.2f$", balTo);
- accounts[indexTo].setBalance(newBalTo);
- String newBalFrom = String.format("%.2f$", balFrom);
- accounts[indexFrom].setBalance(newBalFrom);
- }
- totalProvision += tax;
- }
- return true;
- }
- return false;
- }
- }
- 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;
- }
- }
- === LAB.1 NIZA OD CELI BROEVI ===
- import java.io.ByteArrayInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.util.Arrays;
- import java.util.Random;
- import java.util.Scanner;
- import java.io.BufferedReader;
- final class IntegerArray{
- private int array[];
- public IntegerArray(int [] _array){
- array = new int [_array.length];
- for(int i = 0; i < _array.length; i++)
- array[i] = _array[i];
- }
- public int length(){
- return array.length;
- }
- public int getElementAt(int i){
- return array[i];
- }
- public int sum(){
- int sum = 0;
- for(int i = 0; i < array.length; i++)
- sum+=array[i];
- return sum;
- }
- public double average(){
- return this.sum()/(double)array.length;
- }
- public IntegerArray getSorted(){
- int temp [] = new int [array.length];
- for(int i = 0; i < array.length; i++){
- temp[i] = array[i];
- }
- for(int i=0; i < temp.length; i++){
- for(int j=1; j < temp.length-i; j++){
- if(temp[j-1] > temp[j]){
- int tempNum = temp[j-1];
- temp[j-1] = temp[j];
- temp[j] = tempNum;
- }
- }
- }
- IntegerArray ret = new IntegerArray(temp);
- return ret;
- }
- public boolean equals(IntegerArray ia){
- if(array.length != ia.length()) return false;
- for(int i = 0; i < array.length; i++){
- if(array[i] != ia.getElementAt(i))
- return false;
- }
- return true;
- }
- public IntegerArray concat(IntegerArray ia){
- int temp [] = new int [array.length+ia.length()];
- for(int i = 0; i < array.length; i++){
- temp[i] = array[i];
- }
- for(int i = 0;i < ia.length(); i++){
- temp[i+array.length] = ia.getElementAt(i);
- }
- IntegerArray ret = new IntegerArray(temp);
- return ret;
- }
- public String toString(){
- String ret = "[";
- for(int i = 0; i < array.length; i++){
- ret += array[i];
- if(i != array.length - 1)
- ret += ", ";
- }
- ret += "]";
- return ret;
- }
- }
- class ArrayReader{
- public static IntegerArray readIntegerArray(InputStream input) throws IOException{
- BufferedReader br = new BufferedReader(new InputStreamReader(input));
- String line = br.readLine();
- String [] tempInt = line.split(" ");
- int N = Integer.parseInt(tempInt[0]);
- int [] array = new int [N];
- if(tempInt.length == 1)
- {
- line = br.readLine();
- tempInt = line.split(" ");
- for(int i = 0; i<N;i++){
- array[i] = Integer.parseInt(tempInt[i]);
- }
- }
- else{
- for(int i = 0; i<N;i++){
- array[i] = Integer.parseInt(tempInt[i+1]);
- }
- }
- IntegerArray ret = new IntegerArray (array);
- return ret;
- }
- }
- public class IntegerArrayTester {
- public static void main(String[] args) throws IOException {
- 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) throws IOException {
- 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;
- }
- }
- === LAB.2 MATRICA OD REALNI BROEVI ===
- import java.util.*;
- import java.io.*;
- import java.text.DecimalFormat;
- class InsufficientElementsException extends Exception {
- public InsufficientElementsException (String message){
- super(message);
- }
- }
- class InvalidRowNumberException extends Exception{
- public InvalidRowNumberException (String message){
- super(message);
- }
- }
- class InvalidColumnNumberException extends Exception{
- public InvalidColumnNumberException (String message){
- super(message);
- }
- }
- class DoubleMatrix{
- private double [][] matrix;
- private int rows;
- private int columns;
- public DoubleMatrix(double a[], int m, int n) throws InsufficientElementsException{
- matrix = new double [m][n];
- if( a.length >= m*n){
- rows = m;
- columns = n;
- int k = a.length - m*n;
- for(int i = 0; i < m; i++){
- for(int j = 0; j < n; j++){
- matrix[i][j] = a[k];
- k++;
- }
- }
- }
- else if ( a.length < m*n) throw new InsufficientElementsException("Insufficient number of elements");
- }
- public String getDimensions(){
- return "["+rows+" x "+columns+"]";
- }
- public int rows(){
- return rows;
- }
- public int columns(){
- return columns;
- }
- public double maxElementAtRow(int row) throws InvalidRowNumberException {
- if(row<1 || row>rows)
- throw new InvalidRowNumberException("Invalid row number");
- double max = matrix[row-1][0];
- for (int i = 1; i < columns; i ++){
- if( matrix[row-1][i] > max)
- max = matrix[row-1][i];
- }
- return max;
- }
- public double maxElementAtColumn(int column) throws InvalidColumnNumberException {
- if(column<1 || column>columns)
- throw new InvalidColumnNumberException ("Invalid column number");
- double max = matrix[0][column-1];
- for (int i = 1; i < rows; i ++){
- if( matrix[i][column - 1] > max)
- max = matrix[i][column - 1];
- }
- return max;
- }
- public double sum(){
- double sum = 0;
- for(int i = 0; i < rows; i++){
- for(int j = 0; j < columns; j++){
- sum += matrix[i][j];
- }
- }
- return sum;
- }
- public double [] toSortedArray(){
- Double [] array = new Double [rows*columns];
- for(int i = 0, k =0; i < rows; i++){
- for(int j = 0; j < columns; j++, k++){
- array[k] = new Double(matrix[i][j]);
- }
- }
- Arrays.sort(array,Collections.reverseOrder());
- double [] ret = new double [rows*columns];
- for(int i = 0; i < rows*columns; i++)
- ret[i] = array[i].doubleValue();
- return ret;
- }
- public String toString()
- {
- StringBuilder s = new StringBuilder();
- for(int i=0;i<rows();i++)
- {
- for(int j=0;j<columns();j++)
- {
- s.append(String.format("%.2f",matrix[i][j]));
- if(j!=columns()-1) s.append("\t");
- }
- if(i!=rows()-1) s.append("\n");
- }
- return s.toString();
- }
- public boolean equals(Object ob){
- if (this == ob)
- return true;
- if (ob == null)
- return false;
- if (getClass() != ob.getClass())
- return false;
- DoubleMatrix other = (DoubleMatrix) ob;
- if(rows != other.rows()) return false;
- if(columns != other.columns()) return false;
- for( int i = 0; i < rows; i++){
- for(int j = 0; j < columns; j++){
- if(matrix[i][j]!=other.matrix[i][j])
- return false;
- }
- }
- return true;
- }
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + Arrays.deepHashCode(matrix);
- return result;
- }
- }
- class MatrixReader{
- public static DoubleMatrix read(InputStream input) throws Exception{
- Scanner scanner = new Scanner(input);
- int m = scanner.nextInt();
- int n = scanner.nextInt();
- double [] matrixArray = new double [m*n];
- for(int i = 0; i < m*n; i++)
- matrixArray[i]=scanner.nextDouble();
- scanner.close();
- DoubleMatrix matrix = new DoubleMatrix(matrixArray,m,n);
- return matrix;
- }
- }
- public class DoubleMatrixTester {
- public static void main(String[] args) throws Exception {
- Scanner scanner = new Scanner(System.in);
- int tests = scanner.nextInt();
- DoubleMatrix fm = null;
- double[] info = null;
- DecimalFormat format = new DecimalFormat("0.00");
- for (int t = 0; t < tests; t++) {
- String operation = scanner.next();
- switch (operation) {
- case "READ": {
- int N = scanner.nextInt();
- int R = scanner.nextInt();
- int C = scanner.nextInt();
- double[] f = new double[N];
- for (int i = 0; i < f.length; i++)
- f[i] = scanner.nextDouble();
- try {
- fm = new DoubleMatrix(f, R, C);
- info = Arrays.copyOf(f, f.length);
- } catch (InsufficientElementsException e) {
- System.out.println("Exception caught: " + e.getMessage());
- }
- break;
- }
- case "INPUT_TEST": {
- int R = scanner.nextInt();
- int C = scanner.nextInt();
- StringBuilder sb = new StringBuilder();
- sb.append(R + " " + C + "\n");
- scanner.nextLine();
- for (int i = 0; i < R; i++)
- sb.append(scanner.nextLine() + "\n");
- fm = MatrixReader.read(new ByteArrayInputStream(sb
- .toString().getBytes()));
- info = new double[R * C];
- Scanner tempScanner = new Scanner(new ByteArrayInputStream(sb
- .toString().getBytes()));
- tempScanner.nextDouble();
- tempScanner.nextDouble();
- for (int z = 0; z < R * C; z++) {
- info[z] = tempScanner.nextDouble();
- }
- tempScanner.close();
- break;
- }
- case "PRINT": {
- System.out.println(fm.toString());
- break;
- }
- case "DIMENSION": {
- System.out.println("Dimensions: " + fm.getDimensions());
- break;
- }
- case "COUNT_ROWS": {
- System.out.println("Rows: " + fm.rows());
- break;
- }
- case "COUNT_COLUMNS": {
- System.out.println("Columns: " + fm.columns());
- break;
- }
- case "MAX_IN_ROW": {
- int row = scanner.nextInt();
- try {
- System.out.println("Max in row: "
- + format.format(fm.maxElementAtRow(row)));
- } catch (InvalidRowNumberException e) {
- System.out.println("Exception caught: " + e.getMessage());
- }
- break;
- }
- case "MAX_IN_COLUMN": {
- int col = scanner.nextInt();
- try {
- System.out.println("Max in column: "
- + format.format(fm.maxElementAtColumn(col)));
- } catch (InvalidColumnNumberException e) {
- System.out.println("Exception caught: " + e.getMessage());
- }
- break;
- }
- case "SUM": {
- System.out.println("Sum: " + format.format(fm.sum()));
- break;
- }
- case "CHECK_EQUALS": {
- int val = scanner.nextInt();
- int maxOps = val % 7;
- for (int z = 0; z < maxOps; z++) {
- double work[] = Arrays.copyOf(info, info.length);
- int e1 = (31 * z + 7 * val + 3 * maxOps) % info.length;
- int e2 = (17 * z + 3 * val + 7 * maxOps) % info.length;
- if (e1 > e2) {
- double temp = work[e1];
- work[e1] = work[e2];
- work[e2] = temp;
- }
- DoubleMatrix f1 = fm;
- DoubleMatrix f2 = new DoubleMatrix(work, fm.rows(),
- fm.columns());
- System.out
- .println("Equals check 1: "
- + f1.equals(f2)
- + " "
- + f2.equals(f1)
- + " "
- + (f1.hashCode() == f2.hashCode()&&f1
- .equals(f2)));
- }
- if (maxOps % 2 == 0) {
- DoubleMatrix f1 = fm;
- DoubleMatrix f2 = new DoubleMatrix(new double[]{3.0, 5.0,
- 7.5}, 1, 1);
- System.out
- .println("Equals check 2: "
- + f1.equals(f2)
- + " "
- + f2.equals(f1)
- + " "
- + (f1.hashCode() == f2.hashCode() && f1
- .equals(f2)));
- }
- break;
- }
- case "SORTED_ARRAY": {
- double[] arr = fm.toSortedArray();
- String arrayString = "[";
- if (arr.length > 0)
- arrayString += format.format(arr[0]) + "";
- for (int i = 1; i < arr.length; i++)
- arrayString += ", " + format.format(arr[i]);
- arrayString += "]";
- System.out.println("Sorted array: " + arrayString);
- break;
- }
- }
- }
- scanner.close();
- }
- }
- === LAB.2 KONTAKTI ===
- import java.text.DecimalFormat;
- import java.util.Arrays;
- import java.util.Scanner;
- abstract class Contact{
- protected String date;
- public Contact(String _date){
- date = _date;
- }
- public boolean isNewerThan(Contact c){
- String [] dateArray = date.split("-");
- String [] dateArrayOther = c.date.split("-");
- int year = Integer.parseInt(dateArray[0]);
- int yearOther = Integer.parseInt(dateArrayOther[0]);
- if (year > yearOther) return true;
- else if (year < yearOther) return false;
- else{
- int month = Integer.parseInt(dateArray[1]);
- int monthOther = Integer.parseInt(dateArrayOther[1]);
- if (month > monthOther) return true;
- else if (month < monthOther) return false;
- else{
- int day = Integer.parseInt(dateArray[2]);
- int dayOther = Integer.parseInt(dateArrayOther[2]);
- if (day > dayOther) return true;
- else return false;
- }
- }
- }
- abstract public String getType();
- public String getEmail() {
- return "";
- }
- public String getPhone() {
- return "";
- }
- }
- class EmailContact extends Contact{
- private String email;
- public EmailContact(String _date, String _email){
- super(_date);
- email = _email;
- }
- public String getEmail(){
- return email;
- }
- public String getType(){
- return "Email";
- }
- }
- class PhoneContact extends Contact{
- enum Operator{
- VIP, ONE, TMOBILE
- }
- private String phone;
- private Operator operator;
- public PhoneContact(String _date, String _phone){
- super(_date);
- phone = _phone;
- if ( phone.charAt(2) == '0' || phone.charAt(2) == '1' || phone.charAt(2) == '2')
- operator = Operator.TMOBILE;
- else if ( phone.charAt(2) == '5' || phone.charAt(2) == '6')
- operator = Operator.ONE;
- else if ( phone.charAt(2) == '7' || phone.charAt(2) == '8')
- operator = Operator.VIP;
- }
- public String getPhone(){
- return phone;
- }
- public Operator getOperator(){
- return operator;
- }
- public String getType(){
- return "Phone";
- }
- }
- class Student{
- private String firstName;
- private String lastName;
- private String city;
- private int age;
- private long index;
- private Contact [] contacts;
- public Student(String _firstName, String _lastName, String _city, int _age, long _index){
- firstName = _firstName;
- lastName = _lastName;
- city = _city;
- age = _age;
- index = _index;
- contacts = new Contact [0];
- }
- public void addEmailContact(String date, String email){
- Contact newCon = new EmailContact (date, email);
- Contact [] temp = new Contact [contacts.length+1];
- for (int i = 0; i<contacts.length; i++)
- temp[i] = contacts[i];
- temp[contacts.length] = newCon;
- contacts = temp;
- }
- public void addPhoneContact(String date, String phone){
- Contact newCon = new PhoneContact (date, phone);
- Contact [] temp = new Contact [contacts.length+1];
- for (int i = 0; i<contacts.length; i++)
- temp[i] = contacts[i];
- temp[contacts.length] = newCon;
- contacts = temp;
- }
- public Contact [] getEmailContacts(){
- int counter = 0;
- for (int i = 0; i < contacts.length; i++){
- if ( contacts[i].getType().equals("Email"))
- counter++;
- }
- Contact [] array = new EmailContact[counter];
- int inCounter = 0;
- for (int i = 0; i < contacts.length; i++){
- if ( contacts[i].getType().equals("Email")){
- array[inCounter] = contacts[i];
- inCounter++;
- }
- }
- return array;
- }
- public Contact [] getPhoneContacts(){
- int counter = 0;
- for (int i = 0; i < contacts.length; i++){
- if ( contacts[i].getType().equals("Phone"))
- counter++;
- }
- Contact [] array = new PhoneContact[counter];
- int inCounter = 0;
- for (int i = 0; i < contacts.length; i++){
- if ( contacts[i].getType().equals("Phone")){
- array[inCounter] = contacts[i];
- inCounter++;
- }
- }
- return array;
- }
- public String getCity(){
- return city;
- }
- public String getFullName(){
- return firstName+" "+lastName;
- }
- public long getIndex(){
- return index;
- }
- public int getNumberContacts(){
- return contacts.length;
- }
- public Contact getLatestContact(){
- Contact ret = contacts[0];
- for( int i = 1; i < contacts.length; i++){
- if(contacts[i].isNewerThan(ret))
- ret = contacts[i];
- }
- return ret;
- }
- public String toString(){
- boolean firstPhone = true, firstEmail = true;
- String ret = "{\"ime\":\"" + firstName+ "\", \"prezime\":\"" + lastName
- +"\", \"vozrast\":" + age + ", \"grad\":\"" + city +
- "\", \"indeks\":" + index + ", \"telefonskiKontakti\":[";
- for(int i = 0; i < contacts.length; i++){
- if(contacts[i].getType().equals("Phone")){
- if(firstPhone == true){
- ret+="\""+contacts[i].getPhone()+"\"";
- firstPhone = false;
- }
- else{
- ret+=", \""+contacts[i].getPhone()+"\"";
- }
- }
- }
- ret += "], \"emailKontakti\":[";
- for(int i = 0; i < contacts.length; i++){
- if(contacts[i].getType().equals("Email")){
- if(firstEmail == true){
- ret+="\""+contacts[i].getEmail()+"\"";
- firstEmail = false;
- }
- else{
- ret+=", \""+contacts[i].getEmail()+"\"";
- }
- }
- }
- ret += "]}";
- return ret;
- }
- }
- class Faculty{
- private String name;
- private Student [] students;
- public Faculty (String _name, Student [] _students){
- name = _name;
- students = new Student [_students.length];
- for ( int i = 0; i < _students.length; i++){
- students[i] = _students[i];
- }
- }
- public int countStudentsFromCity( String cityName){
- int counter = 0;
- for (int i = 0; i < students.length; i++){
- if ( students[i].getCity().equals(cityName))
- counter++;
- }
- return counter;
- }
- public Student getStudent(long index){
- for (int i = 0; i < students.length; i++){
- if ( students[i].getIndex() == index)
- return students[i];
- }
- return null;
- }
- public Student countStudentsFromCity(long index){
- Student ret = null;
- for (int i = 0; i < students.length; i++){
- if ( students[i].getIndex() == index)
- ret = students[i];
- }
- return ret;
- }
- public double getAverageNumberOfContacts(){
- int sum = 0;
- for (int i = 0; i < students.length; i++){
- sum += students[i].getNumberContacts();
- }
- double average = (double)sum / students.length;
- return average;
- }
- public Student getStudentWithMostContacts(){
- Student ret = students[0];
- for (int i = 1; i < students.length; i++){
- if ( students[i].getNumberContacts() > ret.getNumberContacts())
- ret = students[i];
- else if (students[i].getNumberContacts() == ret.getNumberContacts())
- if( students[i].getIndex() > ret.getIndex() )
- ret = students[i];
- }
- return ret;
- }
- public String toString(){
- boolean firstStudent = true;
- String ret = "{\"fakultet\":\"" + name + "\", \"studenti\":[";
- for ( int i = 0; i < students.length; i++){
- if(firstStudent == true){
- ret += students[i].toString();
- firstStudent = false;
- }
- else
- ret += ", "+ students[i].toString();
- }
- ret += "]}";
- return ret;
- }
- }
- public class ContactsTester {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- int tests = scanner.nextInt();
- Faculty faculty = null;
- int rvalue = 0;
- long rindex = -1;
- DecimalFormat df = new DecimalFormat("0.00");
- for (int t = 0; t < tests; t++) {
- rvalue++;
- String operation = scanner.next();
- switch (operation) {
- case "CREATE_FACULTY": {
- String name = scanner.nextLine().trim();
- int N = scanner.nextInt();
- Student[] students = new Student[N];
- for (int i = 0; i < N; i++) {
- rvalue++;
- String firstName = scanner.next();
- String lastName = scanner.next();
- String city = scanner.next();
- int age = scanner.nextInt();
- long index = scanner.nextLong();
- if ((rindex == -1) || (rvalue % 13 == 0))
- rindex = index;
- Student student = new Student(firstName, lastName, city,
- age, index);
- students[i] = student;
- }
- faculty = new Faculty(name, students);
- break;
- }
- case "ADD_EMAIL_CONTACT": {
- long index = scanner.nextInt();
- String date = scanner.next();
- String email = scanner.next();
- rvalue++;
- if ((rindex == -1) || (rvalue % 3 == 0))
- rindex = index;
- faculty.getStudent(index).addEmailContact(date, email);
- break;
- }
- case "ADD_PHONE_CONTACT": {
- long index = scanner.nextInt();
- String date = scanner.next();
- String phone = scanner.next();
- rvalue++;
- if ((rindex == -1) || (rvalue % 3 == 0))
- rindex = index;
- faculty.getStudent(index).addPhoneContact(date, phone);
- break;
- }
- case "CHECK_SIMPLE": {
- System.out.println("Average number of contacts: "
- + df.format(faculty.getAverageNumberOfContacts()));
- rvalue++;
- String city = faculty.getStudent(rindex).getCity();
- System.out.println("Number of students from " + city + ": "
- + faculty.countStudentsFromCity(city));
- break;
- }
- case "CHECK_DATES": {
- rvalue++;
- System.out.print("Latest contact: ");
- Contact latestContact = faculty.getStudent(rindex)
- .getLatestContact();
- if (latestContact.getType().equals("Email"))
- System.out.println(((EmailContact) latestContact)
- .getEmail());
- if (latestContact.getType().equals("Phone"))
- System.out.println(((PhoneContact) latestContact)
- .getPhone()
- + " ("
- + ((PhoneContact) latestContact).getOperator()
- .toString() + ")");
- if (faculty.getStudent(rindex).getEmailContacts().length > 0&&faculty.getStudent(rindex).getPhoneContacts().length > 0) {
- System.out.print("Number of email and phone contacts: ");
- System.out
- .println(faculty.getStudent(rindex)
- .getEmailContacts().length
- + " "
- + faculty.getStudent(rindex)
- .getPhoneContacts().length);
- System.out.print("Comparing dates: ");
- int posEmail = rvalue
- % faculty.getStudent(rindex).getEmailContacts().length;
- int posPhone = rvalue
- % faculty.getStudent(rindex).getPhoneContacts().length;
- System.out.println(faculty.getStudent(rindex)
- .getEmailContacts()[posEmail].isNewerThan(faculty
- .getStudent(rindex).getPhoneContacts()[posPhone]));
- }
- break;
- }
- case "PRINT_FACULTY_METHODS": {
- System.out.println("Faculty: " + faculty.toString());
- System.out.println("Student with most contacts: "
- + faculty.getStudentWithMostContacts().toString());
- break;
- }
- }
- }
- scanner.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement