Advertisement
Guest User

Untitled

a guest
Aug 18th, 2017
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 79.39 KB | None | 0 0
  1. Лаб 1
  2. /////////
  3.  
  4. Римски броеви Problem 1 (1 / 2)
  5.  
  6. import java.util.Scanner;
  7. import java.util.stream.IntStream;
  8.  
  9. public class RomanConverterTest {
  10. public static void main(String[] args) {
  11. Scanner scanner = new Scanner(System.in);
  12. int n = scanner.nextInt();
  13. IntStream.range(0, n)
  14. .forEach(x -> System.out.println(RomanConverter.toRoman(scanner.nextInt())));
  15. scanner.close();
  16. }
  17. }
  18.  
  19.  
  20. class RomanConverter {
  21.  
  22. /**
  23. * Roman to decimal converter
  24. *
  25. * @param n number in decimal format
  26. * @return string representation of the number in Roman numeral
  27. */
  28. public static String toRoman(int n) {
  29. String a=new String();
  30. while(n>=1000)
  31. {
  32. a=a+"M";
  33. n-=1000;
  34. }
  35. if(n>=900)
  36. {
  37. a=a+"CM";
  38. n-=900;
  39. }
  40. if(n>=500)
  41. {
  42. a=a+"D";
  43. n-=500;
  44. }
  45. if(n>=400)
  46. {
  47. a=a+"CD";
  48. n-=400;
  49. }
  50. while(n>=100)
  51. {
  52. a=a+"C";
  53. n-=100;
  54. }
  55. if(n>=90)
  56. {
  57. a=a+"XC";
  58. n-=90;
  59. }
  60. if(n>=50)
  61. {
  62. a=a+"L";
  63. n-=50;
  64. }
  65. if(n>=40)
  66. {
  67. a=a+"XL";
  68. n-=40;
  69. }
  70. while(n>=10)
  71. {
  72. a=a+"X";
  73. n-=10;
  74. }
  75. if(n>=9)
  76. {
  77. a=a+"IX";
  78. n-=9;
  79. }
  80. if(n>=5)
  81. {
  82. a=a+"V";
  83. n-=5;
  84. }
  85. if(n>=4)
  86. {
  87. a=a+"IV";
  88. n-=4;
  89. }
  90. while(n>=1)
  91. {
  92. a=a+"I";
  93. n-=1;
  94. }
  95. return a;
  96. }
  97.  
  98. }
  99.  
  100.  
  101. //////////
  102. Систем за банкарско работење Problem 2 (1 / 22)
  103.  
  104. import java.util.*;
  105. import java.util.stream.Collectors;
  106. class Account{
  107. private String ime;
  108. private long ID;
  109. private String saldo;
  110. public Account(String ime, String saldo) {
  111. this.ime = ime;
  112. this.saldo = saldo;
  113. Random random = new Random();
  114. ID = random.nextLong();
  115. }
  116. public String getBalance(){
  117. return saldo;
  118. }
  119. public double getdoubleBalance(){
  120. return Double.parseDouble(saldo.substring(0, saldo.length()-1));
  121. }
  122. public String getName(){
  123. return ime;
  124. }
  125. public long getId(){
  126. return ID;
  127. }
  128. public void setBalance(String balance)
  129. {
  130. saldo=balance;
  131. }
  132. @Override
  133. public String toString(){
  134. return String.format("Name: %s\nBalance: %s\n",ime,saldo);
  135. }
  136. @Override
  137. public int hashCode() {
  138. final int prime = 31;
  139. int result = 1;
  140. result = prime * result + (int) (ID ^ (ID >>> 32));
  141. result = prime * result + ((ime == null) ? 0 : ime.hashCode());
  142. result = prime * result + ((saldo == null) ? 0 : saldo.hashCode());
  143. return result;
  144. }
  145. @Override
  146. public boolean equals(Object obj) {
  147. if (this == obj)
  148. return true;
  149. if (obj == null)
  150. return false;
  151. if (getClass() != obj.getClass())
  152. return false;
  153. Account other = (Account) obj;
  154. if (ID != other.ID)
  155. return false;
  156. if (ime == null) {
  157. if (other.ime != null)
  158. return false;
  159. } else if (!ime.equals(other.ime))
  160. return false;
  161. if (saldo == null) {
  162. if (other.saldo != null)
  163. return false;
  164. } else if (!saldo.equals(other.saldo))
  165. return false;
  166. return true;
  167. }
  168.  
  169.  
  170.  
  171. }
  172. abstract class Transaction{
  173. private long IDod;
  174. private long IDdo;
  175. private String opis;
  176. private String iznos;
  177. public Transaction(long iDod, long iDdo, String opis, String iznos) {
  178. IDod = iDod;
  179. IDdo = iDdo;
  180. this.opis = opis;
  181. this.iznos = iznos;
  182. }
  183. public String getAmount(){
  184. return iznos;
  185. }
  186. public long getFromId(){
  187. return IDod;
  188. }
  189. public long getToId(){
  190. return IDdo;
  191. }
  192. public String getDescription(){
  193. return opis;
  194. }
  195. public double getdoubleAmount(){
  196. return Double.parseDouble(iznos.substring(0,iznos.length()-1));
  197. }
  198. public abstract double getProvision();
  199. @Override
  200. public int hashCode() {
  201. final int prime = 31;
  202. int result = 1;
  203. result = prime * result + (int) (IDdo ^ (IDdo >>> 32));
  204. result = prime * result + (int) (IDod ^ (IDod >>> 32));
  205. result = prime * result + ((iznos == null) ? 0 : iznos.hashCode());
  206. result = prime * result + ((opis == null) ? 0 : opis.hashCode());
  207. return result;
  208. }
  209. @Override
  210. public boolean equals(Object obj) {
  211. if (this == obj)
  212. return true;
  213. if (obj == null)
  214. return false;
  215. if (getClass() != obj.getClass())
  216. return false;
  217. Transaction other = (Transaction) obj;
  218. if (IDdo != other.IDdo)
  219. return false;
  220. if (IDod != other.IDod)
  221. return false;
  222. if (iznos == null) {
  223. if (other.iznos != null)
  224. return false;
  225. } else if (!iznos.equals(other.iznos))
  226. return false;
  227. if (opis == null) {
  228. if (other.opis != null)
  229. return false;
  230. } else if (!opis.equals(other.opis))
  231. return false;
  232. return true;
  233. }
  234.  
  235. }
  236. class FlatAmountProvisionTransaction extends Transaction{
  237. private String provizija;
  238. public FlatAmountProvisionTransaction(long fromId, long toId,String amount, String flatProvision){
  239. super(fromId,toId,"FlatAmount",amount);
  240. provizija=flatProvision;
  241. }
  242. String getFlatAmount()
  243. {
  244. return provizija;
  245. }
  246. @Override
  247. public double getProvision() {
  248. return Double.parseDouble(provizija.substring(0,provizija.length()-1));
  249. }
  250. @Override
  251. public double getdoubleAmount(){
  252. return super.getdoubleAmount() + getProvision();
  253. }
  254. @Override
  255. public int hashCode() {
  256. final int prime = 31;
  257. int result = super.hashCode();
  258. result = prime * result + ((provizija == null) ? 0 : provizija.hashCode());
  259. return result;
  260. }
  261. @Override
  262. public boolean equals(Object obj) {
  263. if (this == obj)
  264. return true;
  265. if (!super.equals(obj))
  266. return false;
  267. if (getClass() != obj.getClass())
  268. return false;
  269. FlatAmountProvisionTransaction other = (FlatAmountProvisionTransaction) obj;
  270. if (provizija == null) {
  271. if (other.provizija != null)
  272. return false;
  273. } else if (!provizija.equals(other.provizija))
  274. return false;
  275. return true;
  276. }
  277.  
  278. }
  279. class FlatPercentProvisionTransaction extends Transaction{
  280. private int provizija;
  281. public FlatPercentProvisionTransaction (long fromId, long toId, String amount, int centsPerDolar){
  282. super(fromId,toId,"FlatPercent",amount);
  283. provizija=centsPerDolar;
  284. }
  285. int getPercent(){
  286. return provizija;
  287. }
  288. @Override
  289. public double getProvision() {
  290. return provizija / 100.0 * (int)super.getdoubleAmount();
  291. }
  292.  
  293. @Override
  294. public double getdoubleAmount() {
  295. return super.getdoubleAmount() + getProvision();
  296. }
  297. @Override
  298. public int hashCode() {
  299. final int prime = 31;
  300. int result = super.hashCode();
  301. result = prime * result + provizija;
  302. return result;
  303. }
  304. @Override
  305. public boolean equals(Object obj) {
  306. if (this == obj)
  307. return true;
  308. if (!super.equals(obj))
  309. return false;
  310. if (getClass() != obj.getClass())
  311. return false;
  312. FlatPercentProvisionTransaction other = (FlatPercentProvisionTransaction) obj;
  313. if (provizija != other.provizija)
  314. return false;
  315. return true;
  316. }
  317.  
  318. }
  319. class Bank{
  320. private String ime;
  321. private double provizija;
  322. private double suma;
  323. private Account accs[];
  324. public Bank(String name,Account accounts[])
  325. {
  326. ime=name;
  327. accs = Arrays.copyOf(accounts, accounts.length);
  328. suma=0;
  329. provizija=0;
  330. }
  331. public Account[] getAccounts()
  332. {
  333. return accs;
  334. }
  335.  
  336. public String totalProvision() {
  337. return String.format("%.2f$",provizija);
  338. }
  339. public String totalTransfers() {
  340. return String.format("%.2f$",suma);
  341. }
  342. @Override
  343. public String toString() {
  344. StringBuilder sb = new StringBuilder();
  345. sb.append("Name: " + ime + "\n\n");
  346. for (Account a: accs)
  347. sb.append(a.toString());
  348. return sb.toString();
  349. }
  350. int findID(long a){
  351. for(int i=0;i<accs.length;i++)
  352. {
  353. if(a==accs[i].getId())
  354. {
  355. return i;
  356. }
  357. }
  358. return -1;
  359. }
  360. boolean makeTransaction(Transaction t){
  361.  
  362. int iDFrom = findID(t.getFromId());
  363. int iDTo = findID(t.getToId());
  364. if (iDFrom == -1 || iDTo==-1)
  365. return false;
  366.  
  367. double balanceFrom = accs[iDFrom].getdoubleBalance();
  368. double balanceTo = accs[iDTo].getdoubleBalance();
  369. if ( balanceFrom < t.getdoubleAmount())
  370. return false;
  371.  
  372. double totalSum = t.getdoubleAmount();
  373. double provision = t.getProvision();
  374.  
  375. suma += (totalSum - provision);
  376. provizija += provision;
  377. balanceFrom -= totalSum;
  378. if (iDFrom == iDTo) {
  379. balanceTo -= provision;
  380. }
  381. else {
  382. balanceTo += (totalSum - provision);
  383. }
  384.  
  385. accs[iDFrom].setBalance(String.format("%.2f$",balanceFrom));
  386. accs[iDTo].setBalance(String.format("%.2f$",balanceTo));
  387. return true;
  388. }
  389. @Override
  390. public int hashCode() {
  391. final int prime = 31;
  392. int result = 1;
  393. result = prime * result + Arrays.hashCode(accs);
  394. result = prime * result + ((ime == null) ? 0 : ime.hashCode());
  395. long temp;
  396. temp = Double.doubleToLongBits(provizija);
  397. result = prime * result + (int) (temp ^ (temp >>> 32));
  398. temp = Double.doubleToLongBits(suma);
  399. result = prime * result + (int) (temp ^ (temp >>> 32));
  400. return result;
  401. }
  402. @Override
  403. public boolean equals(Object obj) {
  404. if (this == obj)
  405. return true;
  406. if (obj == null)
  407. return false;
  408. if (getClass() != obj.getClass())
  409. return false;
  410. Bank other = (Bank) obj;
  411. if (!Arrays.equals(accs, other.accs))
  412. return false;
  413. if (ime == null) {
  414. if (other.ime != null)
  415. return false;
  416. } else if (!ime.equals(other.ime))
  417. return false;
  418. if (Double.doubleToLongBits(provizija) != Double.doubleToLongBits(other.provizija))
  419. return false;
  420. if (Double.doubleToLongBits(suma) != Double.doubleToLongBits(other.suma))
  421. return false;
  422. return true;
  423. }
  424.  
  425.  
  426.  
  427. }
  428.  
  429. public class BankTester {
  430.  
  431. public static void main(String[] args) {
  432. Scanner jin = new Scanner(System.in);
  433. String test_type = jin.nextLine();
  434. switch (test_type) {
  435. case "typical_usage":
  436. testTypicalUsage(jin);
  437. break;
  438. case "equals":
  439. testEquals();
  440. break;
  441. }
  442. jin.close();
  443. }
  444.  
  445. private static void testEquals() {
  446. Account a1 = new Account("Andrej", "20.00$");
  447. Account a2 = new Account("Andrej", "20.00$");
  448. Account a3 = new Account("Andrej", "30.00$");
  449. Account a4 = new Account("Gajduk", "20.00$");
  450. List<Account> all = Arrays.asList(a1, a2, a3, a4);
  451. if (!(a1.equals(a1)&&!a1.equals(a2)&&!a2.equals(a1)&&!a3.equals(a1)&&!a4.equals(a1)&&!a1.equals(null))) {
  452. System.out.println("Your account equals method does not work properly.");
  453. return;
  454. }
  455. Set<Long> ids = all.stream().map(Account::getId).collect(Collectors.toSet());
  456. if (ids.size() != all.size()) {
  457. System.out.println("Different accounts have the same IDS. This is not allowed");
  458. return;
  459. }
  460. FlatAmountProvisionTransaction fa1 = new FlatAmountProvisionTransaction(10, 20, "20.00$", "10.00$");
  461. FlatAmountProvisionTransaction fa2 = new FlatAmountProvisionTransaction(20, 20, "20.00$", "10.00$");
  462. FlatAmountProvisionTransaction fa3 = new FlatAmountProvisionTransaction(20, 10, "20.00$", "10.00$");
  463. FlatAmountProvisionTransaction fa4 = new FlatAmountProvisionTransaction(10, 20, "50.00$", "50.00$");
  464. FlatAmountProvisionTransaction fa5 = new FlatAmountProvisionTransaction(30, 40, "20.00$", "10.00$");
  465. FlatPercentProvisionTransaction fp1 = new FlatPercentProvisionTransaction(10, 20, "20.00$", 10);
  466. FlatPercentProvisionTransaction fp2 = new FlatPercentProvisionTransaction(10, 20, "20.00$", 10);
  467. FlatPercentProvisionTransaction fp3 = new FlatPercentProvisionTransaction(10, 10, "20.00$", 10);
  468. FlatPercentProvisionTransaction fp4 = new FlatPercentProvisionTransaction(10, 20, "50.00$", 10);
  469. FlatPercentProvisionTransaction fp5 = new FlatPercentProvisionTransaction(10, 20, "20.00$", 30);
  470. FlatPercentProvisionTransaction fp6 = new FlatPercentProvisionTransaction(30, 40, "20.00$", 10);
  471. if (fa1.equals(fa1)&&!fa2.equals(null) &&
  472. fa2.equals(fa1) &&
  473. fa1.equals(fa2) &&
  474. fa1.equals(fa3) &&
  475. !fa1.equals(fa4) &&
  476. !fa1.equals(fa5) &&
  477. !fa1.equals(fp1) &&
  478. fp1.equals(fp1) &&
  479. !fp2.equals(null) &&
  480. fp2.equals(fp1) &&
  481. fp1.equals(fp2) &&
  482. fp1.equals(fp3) &&
  483. !fp1.equals(fp4) &&
  484. !fp1.equals(fp5) &&
  485. !fp1.equals(fp6)) {
  486. System.out.println("Your transactions equals methods do not work properly.");
  487. return;
  488. }
  489. Account accounts[] = new Account[]{a1, a2, a3, a4};
  490. Account accounts1[] = new Account[]{a2, a1, a3, a4};
  491. Account accounts2[] = new Account[]{a1, a2, a3};
  492. Account accounts3[] = new Account[]{a1, a2, a3, a4};
  493.  
  494. Bank b1 = new Bank("Test", accounts);
  495. Bank b2 = new Bank("Test", accounts1);
  496. Bank b3 = new Bank("Test", accounts2);
  497. Bank b4 = new Bank("Sample", accounts);
  498. Bank b5 = new Bank("Test", accounts3);
  499.  
  500. if (!(b1.equals(b1) &&
  501. !b1.equals(null) &&
  502. !b1.equals(b2) &&
  503. !b2.equals(b1) &&
  504. !b1.equals(b3) &&
  505. !b3.equals(b1) &&
  506. !b1.equals(b4) &&
  507. b1.equals(b5))) {
  508. System.out.println("Your bank equals method do not work properly.");
  509. return;
  510. }
  511. accounts[2] = a1;
  512. if (!b1.equals(b5)) {
  513. System.out.println("Your bank equals method do not work properly.");
  514. return;
  515. }
  516. long from_id = a2.getId();
  517. long to_id = a3.getId();
  518. Transaction t = new FlatAmountProvisionTransaction(from_id, to_id, "3.00$", "3.00$");
  519. b1.makeTransaction(t);
  520. if (b1.equals(b5)) {
  521. System.out.println("Your bank equals method do not work properly.");
  522. return;
  523. }
  524. b5.makeTransaction(t);
  525. if (!b1.equals(b5)) {
  526. System.out.println("Your bank equals method do not work properly.");
  527. return;
  528. }
  529. System.out.println("All your equals methods work properly.");
  530. }
  531.  
  532. private static void testTypicalUsage(Scanner jin) {
  533. String bank_name = jin.nextLine();
  534. int num_accounts = jin.nextInt();
  535. jin.nextLine();
  536. Account accounts[] = new Account[num_accounts];
  537. for (int i = 0; i < num_accounts; ++i)
  538. accounts[i] = new Account(jin.nextLine(), jin.nextLine());
  539. Bank bank = new Bank(bank_name, accounts);
  540. while (true) {
  541. String line = jin.nextLine();
  542. switch (line) {
  543. case "stop":
  544. return;
  545. case "transaction":
  546. String descrption = jin.nextLine();
  547. String amount = jin.nextLine();
  548. String parameter = jin.nextLine();
  549. int from_idx = jin.nextInt();
  550. int to_idx = jin.nextInt();
  551. jin.nextLine();
  552. Transaction t = getTransaction(descrption, from_idx, to_idx, amount, parameter, bank);
  553. System.out.println("Transaction amount: " + t.getAmount());
  554. System.out.println("Transaction description: " + t.getDescription());
  555. System.out.println("Transaction successful? " + bank.makeTransaction(t));
  556. break;
  557. case "print":
  558. System.out.println(bank.toString());
  559. System.out.println("Total provisions: " + bank.totalProvision());
  560. System.out.println("Total transfers: " + bank.totalTransfers());
  561. System.out.println();
  562. break;
  563. }
  564. }
  565. }
  566.  
  567. private static Transaction getTransaction(String description, int from_idx, int to_idx, String amount, String o, Bank bank) {
  568. switch (description) {
  569. case "FlatAmount":
  570. return new FlatAmountProvisionTransaction(bank.getAccounts()[from_idx].getId(),
  571. bank.getAccounts()[to_idx].getId(), amount, o);
  572. case "FlatPercent":
  573. return new FlatPercentProvisionTransaction(bank.getAccounts()[from_idx].getId(),
  574. bank.getAccounts()[to_idx].getId(), amount, Integer.parseInt(o));
  575. }
  576. return null;
  577. }
  578.  
  579.  
  580. }
  581.  
  582. /////////////////
  583.  
  584. import java.io.ByteArrayInputStream;
  585. import java.io.IOException;
  586. import java.io.InputStream;
  587. import java.util.Arrays;
  588. import java.util.Random;
  589. import java.util.Scanner;
  590.  
  591. final class IntegerArray{
  592. private final int a[];
  593. public IntegerArray(){
  594. a=null;
  595. }
  596. public IntegerArray(int[] b) {
  597. a=new int[b.length];
  598. for(int i=0;i<b.length;i++)
  599. {
  600. a[i]=b[i];
  601. }
  602. }
  603. public int length(){
  604. return a.length;
  605. }
  606. public int getElementAt(int i)
  607. {
  608. return a[i];
  609. }
  610. public int sum(){
  611. int sum=0;
  612. for(int i=0;i<a.length;i++)
  613. sum+=a[i];
  614. return sum;
  615. }
  616. public double average(){
  617. return (double)sum()/a.length;
  618. }
  619. public IntegerArray getSorted(){
  620. int [] b=new int[a.length];
  621. for(int i=0;i<a.length;i++)
  622. b[i]=a[i];
  623. Arrays.sort(b);
  624. return new IntegerArray(b);
  625. }
  626. public IntegerArray concat(IntegerArray ia){
  627. int [] b=new int[ia.length()+a.length];
  628. for(int i=0;i<a.length;i++)
  629. {
  630. b[i]=a[i];
  631. }
  632. for(int i=a.length,k=0;i<(ia.length()+a.length);i++,k++)
  633. {
  634.  
  635. b[i]=ia.a[k];
  636. }
  637. return new IntegerArray(b);
  638. }
  639. @Override
  640. public String toString(){
  641. StringBuilder sb = new StringBuilder();
  642. sb.append("[");
  643. for(int i=0;i<a.length-1;i++){
  644. sb.append(a[i]);
  645. sb.append(", ");
  646. }
  647. sb.append(a[a.length-1]);
  648. sb.append("]");
  649. return sb.toString();
  650. }
  651. @Override
  652. public int hashCode() {
  653. final int prime = 31;
  654. int result = 1;
  655. result = prime * result + Arrays.hashCode(a);
  656. return result;
  657. }
  658. @Override
  659. public boolean equals(Object obj) {
  660. if (this == obj)
  661. return true;
  662. if (obj == null)
  663. return false;
  664. if (getClass() != obj.getClass())
  665. return false;
  666. IntegerArray other = (IntegerArray) obj;
  667. if (!Arrays.equals(a, other.a))
  668. return false;
  669. return true;
  670. }
  671.  
  672. }
  673. class ArrayReader{
  674. public static IntegerArray readIntegerArray(InputStream input){
  675. Scanner s = new Scanner(input);
  676. int N=s.nextInt();
  677. int[] a = new int[N];
  678.  
  679. for(int i=0;i<N;i++)
  680. {
  681. a[i]=s.nextInt();
  682. }
  683. return new IntegerArray(a);
  684. }
  685. }
  686. public class IntegerArrayTester {
  687.  
  688. public static void main(String[] args) {
  689. Scanner scanner = new Scanner(System.in);
  690. String s = scanner.nextLine();
  691. IntegerArray ia = null;
  692. switch (s) {
  693. case "testSimpleMethods":
  694. ia = new IntegerArray(generateRandomArray(scanner.nextInt()));
  695. testSimpleMethods(ia);
  696. break;
  697. case "testConcat":
  698. testConcat(scanner);
  699. break;
  700. case "testEquals":
  701. testEquals(scanner);
  702. break;
  703. case "testSorting":
  704. testSorting(scanner);
  705. break;
  706. case "testReading":
  707. testReading(new ByteArrayInputStream(scanner.nextLine().getBytes()));
  708. break;
  709. case "testImmutability":
  710. int a[] = generateRandomArray(scanner.nextInt());
  711. ia = new IntegerArray(a);
  712. testSimpleMethods(ia);
  713. testSimpleMethods(ia);
  714. IntegerArray sorted_ia = ia.getSorted();
  715. testSimpleMethods(ia);
  716. testSimpleMethods(sorted_ia);
  717. sorted_ia.getSorted();
  718. testSimpleMethods(sorted_ia);
  719. testSimpleMethods(ia);
  720. a[0] += 2;
  721. testSimpleMethods(ia);
  722. ia = ArrayReader.readIntegerArray(new ByteArrayInputStream(integerArrayToString(ia).getBytes()));
  723. testSimpleMethods(ia);
  724. break;
  725. }
  726. scanner.close();
  727. }
  728.  
  729. static void testReading(InputStream in) {
  730. IntegerArray read = ArrayReader.readIntegerArray(in);
  731. System.out.println(read);
  732. }
  733.  
  734. static void testSorting(Scanner scanner) {
  735. int[] a = readArray(scanner);
  736. IntegerArray ia = new IntegerArray(a);
  737. System.out.println(ia.getSorted());
  738. }
  739.  
  740. static void testEquals(Scanner scanner) {
  741. int[] a = readArray(scanner);
  742. int[] b = readArray(scanner);
  743. int[] c = readArray(scanner);
  744. IntegerArray ia = new IntegerArray(a);
  745. IntegerArray ib = new IntegerArray(b);
  746. IntegerArray ic = new IntegerArray(c);
  747. System.out.println(ia.equals(ib));
  748. System.out.println(ia.equals(ic));
  749. System.out.println(ib.equals(ic));
  750. }
  751.  
  752. static void testConcat(Scanner scanner) {
  753. int[] a = readArray(scanner);
  754. int[] b = readArray(scanner);
  755. IntegerArray array1 = new IntegerArray(a);
  756. IntegerArray array2 = new IntegerArray(b);
  757. IntegerArray concatenated = array1.concat(array2);
  758. System.out.println(concatenated);
  759. }
  760.  
  761. static void testSimpleMethods(IntegerArray ia) {
  762. System.out.print(integerArrayToString(ia));
  763. System.out.println(ia);
  764. System.out.println(ia.sum());
  765. System.out.printf("%.2f\n", ia.average());
  766. }
  767.  
  768.  
  769. static String integerArrayToString(IntegerArray ia) {
  770. StringBuilder sb = new StringBuilder();
  771. sb.append(ia.length()).append('\n');
  772. for (int i = 0; i < ia.length(); ++i)
  773. sb.append(ia.getElementAt(i)).append(' ');
  774. sb.append('\n');
  775. return sb.toString();
  776. }
  777.  
  778. static int[] readArray(Scanner scanner) {
  779. int n = scanner.nextInt();
  780. int[] a = new int[n];
  781. for (int i = 0; i < n; ++i) {
  782. a[i] = scanner.nextInt();
  783. }
  784. return a;
  785. }
  786.  
  787.  
  788. static int[] generateRandomArray(int k) {
  789. Random rnd = new Random(k);
  790. int n = rnd.nextInt(8) + 2;
  791. int a[] = new int[n];
  792. for (int i = 0; i < n; ++i) {
  793. a[i] = rnd.nextInt(20) - 5;
  794. }
  795. return a;
  796. }
  797.  
  798. }
  799.  
  800. ///////
  801.  
  802. Лаб 3.
  803.  
  804. //////
  805.  
  806. Пицерија Problem 1 (1 / 9)
  807.  
  808.  
  809. import java.util.Scanner;
  810. interface Item{
  811. public int getPrice();
  812. public String getType();
  813. }
  814.  
  815. class OrderLockedException extends Exception{
  816. }
  817. class EmptyOrder extends Exception{
  818. }
  819. class InvalidExtraTypeException extends Exception{
  820. }
  821. class InvalidPizzaTypeException extends Exception{
  822. }
  823. class ItemOutOfStockException extends Exception{
  824. public ItemOutOfStockException(Item item){
  825. super(String.format("Nema %s", item.getType()));
  826. }
  827. }
  828. class ExtraItem implements Item{
  829. String type;
  830. ExtraItem(String type) throws InvalidExtraTypeException{
  831. if(type.compareTo("Coke")==0)
  832. {
  833. this.type=type;
  834. }
  835. else if(type.compareTo("Ketchup")==0)
  836. {
  837. this.type=type;
  838. }
  839. else{
  840. throw new InvalidExtraTypeException();
  841. }
  842. }
  843. public String getType(){return type;}
  844. public int getPrice(){
  845. if(type.compareTo("Coke")==0)
  846. {
  847. return 5;
  848. }
  849. else{
  850. return 3;
  851. }
  852.  
  853. }
  854. }
  855. class PizzaItem implements Item{
  856. String type;
  857. PizzaItem(String type) throws InvalidPizzaTypeException{
  858. if(type.compareTo("Standard")==0)
  859. {
  860. this.type=type;
  861. }
  862. else if(type.compareTo("Pepperoni")==0){
  863. this.type=type;
  864. }
  865. else if(type.compareTo("Vegetarian")==0){
  866. this.type=type;
  867. }
  868. else{
  869. throw new InvalidPizzaTypeException();
  870. }
  871. }
  872. public String getType(){return type;}
  873. public int getPrice(){
  874. if(type.compareTo("Standard")==0)
  875. {
  876. return 10;
  877. }
  878. else if(type.compareTo("Pepperoni")==0){
  879. return 12;
  880. }
  881. else {
  882. return 8;
  883. }
  884. }
  885. }
  886. class Order{
  887. int a[];
  888. Item it[];
  889. int n;
  890. boolean locked;
  891. public Order(){
  892. a=new int[5];
  893. it=new Item[5];
  894. locked=false;
  895. n=0;
  896. }
  897. public void addItem(Item item, int count) throws ItemOutOfStockException, OrderLockedException
  898. {
  899. if(!locked){
  900. if(count>=10)
  901. throw new ItemOutOfStockException(item);
  902. boolean flag=false;
  903. for(int i=0;i<n;i++)
  904. {
  905. if (item.getType().compareTo(it[i].getType())==0)
  906. {
  907. a[i]=count;
  908. flag=true;
  909. break;
  910. }
  911. }
  912. if(!flag)
  913. {
  914. a[n]=count;
  915. it[n]=item;
  916. n++;
  917. }
  918. }
  919. else throw new OrderLockedException();
  920. }
  921. public int getPrice(){
  922. int s=0;
  923. for(int i=0;i<n;i++)
  924. {
  925. s+=it[i].getPrice()*a[i];
  926. }
  927. return s;
  928. }
  929. public void displayOrder(){
  930. for(int i=0;i<n;i++){
  931. System.out.printf("%3d.%-15sx%2d%5d$\n",i+1,it[i].getType(),a[i],it[i].getPrice()*a[i]);
  932. }
  933. System.out.printf("Total: %5d$\n",getPrice());
  934. }
  935. public void removeItem(int idx) throws ArrayIndexOutOfBoundsException,OrderLockedException
  936. {
  937. if(idx>=n)
  938. {
  939. throw new ArrayIndexOutOfBoundsException();
  940. }
  941. else{
  942. if(!locked){
  943. for(int i=idx;i<n-1;i++)
  944. {
  945. a[i]=a[i+1];
  946. it[i]=it[i+1];
  947. }
  948. n--;
  949. }
  950. else throw new OrderLockedException();
  951. }
  952. }
  953. public void lock() throws EmptyOrder
  954. {
  955. if(n==0) throw new EmptyOrder();
  956. else locked=true;
  957. }
  958. }
  959. public class PizzaOrderTest {
  960.  
  961. public static void main(String[] args) {
  962. Scanner jin = new Scanner(System.in);
  963. int k = jin.nextInt();
  964. if (k == 0) { //test Item
  965. try {
  966. String type = jin.next();
  967. String name = jin.next();
  968. Item item = null;
  969. if (type.equals("Pizza")) item = new PizzaItem(name);
  970. else item = new ExtraItem(name);
  971. System.out.println(item.getPrice());
  972. } catch (Exception e) {
  973. System.out.println(e.getClass().getSimpleName());
  974. }
  975. }
  976. if (k == 1) { // test simple order
  977. Order order = new Order();
  978. while (true) {
  979. try {
  980. String type = jin.next();
  981. String name = jin.next();
  982. Item item = null;
  983. if (type.equals("Pizza")) item = new PizzaItem(name);
  984. else item = new ExtraItem(name);
  985. if (!jin.hasNextInt()) break;
  986. order.addItem(item, jin.nextInt());
  987. } catch (Exception e) {
  988. System.out.println(e.getClass().getSimpleName());
  989. }
  990. }
  991. jin.next();
  992. System.out.println(order.getPrice());
  993. order.displayOrder();
  994. while (true) {
  995. try {
  996. String type = jin.next();
  997. String name = jin.next();
  998. Item item = null;
  999. if (type.equals("Pizza")) item = new PizzaItem(name);
  1000. else item = new ExtraItem(name);
  1001. if (!jin.hasNextInt()) break;
  1002. order.addItem(item, jin.nextInt());
  1003. } catch (Exception e) {
  1004. System.out.println(e.getClass().getSimpleName());
  1005. }
  1006. }
  1007. System.out.println(order.getPrice());
  1008. order.displayOrder();
  1009. }
  1010. if (k == 2) { // test order with removing
  1011. Order order = new Order();
  1012. while (true) {
  1013. try {
  1014. String type = jin.next();
  1015. String name = jin.next();
  1016. Item item = null;
  1017. if (type.equals("Pizza")) item = new PizzaItem(name);
  1018. else item = new ExtraItem(name);
  1019. if (!jin.hasNextInt()) break;
  1020. order.addItem(item, jin.nextInt());
  1021. } catch (Exception e) {
  1022. System.out.println(e.getClass().getSimpleName());
  1023. }
  1024. }
  1025. jin.next();
  1026. System.out.println(order.getPrice());
  1027. order.displayOrder();
  1028. while (jin.hasNextInt()) {
  1029. try {
  1030. int idx = jin.nextInt();
  1031. order.removeItem(idx);
  1032. } catch (Exception e) {
  1033. System.out.println(e.getClass().getSimpleName());
  1034. }
  1035. }
  1036. System.out.println(order.getPrice());
  1037. order.displayOrder();
  1038. }
  1039. if (k == 3) { //test locking & exceptions
  1040. Order order = new Order();
  1041. try {
  1042. order.lock();
  1043. } catch (Exception e) {
  1044. System.out.println(e.getClass().getSimpleName());
  1045. }
  1046. try {
  1047. order.addItem(new ExtraItem("Coke"), 1);
  1048. } catch (Exception e) {
  1049. System.out.println(e.getClass().getSimpleName());
  1050. }
  1051. try {
  1052. order.lock();
  1053. } catch (Exception e) {
  1054. System.out.println(e.getClass().getSimpleName());
  1055. }
  1056. try {
  1057. order.removeItem(0);
  1058. } catch (Exception e) {
  1059. System.out.println(e.getClass().getSimpleName());
  1060. }
  1061. }
  1062. }
  1063.  
  1064. }
  1065.  
  1066. /////////////
  1067. Лаб 4.
  1068. ////////////
  1069.  
  1070. LocalDate Problem 1 (1 / 3)
  1071.  
  1072. import java.sql.Date;
  1073. import java.sql.Timestamp;
  1074. import java.time.*;
  1075. import java.time.temporal.ChronoUnit;
  1076. import java.time.temporal.TemporalAdjusters;
  1077.  
  1078. /**
  1079. * LocalDate test
  1080. */
  1081. public class LocalDateTest {
  1082. public static void main(String[] args) {
  1083. System.out.println(create());
  1084. System.out.println(parse());
  1085. System.out.println(with().getYear());
  1086. System.out.println(withAdjuster());
  1087. System.out.println(plus());
  1088. System.out.println(minus());
  1089. System.out.println(plusPeriod());
  1090. System.out.println(isAfter());
  1091. System.out.println(until());
  1092. }
  1093.  
  1094. static LocalDate create() {
  1095.  
  1096. /**
  1097. * Create a {@link LocalDate} of 2015-06-18 by using {@link LocalDate#of}
  1098. */
  1099. return LocalDate.of(2015, 06, 18);
  1100. }
  1101.  
  1102. static LocalDate parse() {
  1103. /**
  1104. * Create a {@link LocalDate} of 2015-06-18 from String by using {@link LocalDate#parse}
  1105. */
  1106. return LocalDate.parse("2015-06-18");
  1107. }
  1108.  
  1109. static LocalDate with() {
  1110. LocalDate ld = DateAndTimes.LD_20150618;
  1111. /**
  1112. * Create a {@link LocalDate} from {@link ld} with year 2015
  1113. * by using {@link LocalDate#withYear} or {@link LocalDate#with}
  1114. */
  1115. return ld.withYear(2015);
  1116. }
  1117.  
  1118. static LocalDate withAdjuster() {
  1119. LocalDate ld = DateAndTimes.LD_20150618;
  1120. /**
  1121. * Create a {@link LocalDate} from {@link ld} adjusted into first day of next year
  1122. * by using {@link LocalDate#with} and {@link TemporalAdjusters#firstDayOfNextYear}
  1123. */
  1124.  
  1125. return ld.with(TemporalAdjusters.firstDayOfNextYear());
  1126. }
  1127.  
  1128. static LocalDate plus() {
  1129. LocalDate ld = DateAndTimes.LD_20150618;
  1130.  
  1131. /**
  1132. * Create a {@link LocalDate} from {@link ld} with 10 month later
  1133. * by using {@link LocalDate#plusMonths} or {@link LocalDate#plus}
  1134. */
  1135. return ld.plusMonths(10);
  1136. }
  1137.  
  1138. static LocalDate minus() {
  1139. LocalDate ld = DateAndTimes.LD_20150618;
  1140.  
  1141. /**
  1142. * Create a {@link LocalDate} from {@link ld} with 10 days before
  1143. * by using {@link LocalDate#minusDays} or {@link LocalDate#minus}
  1144. */
  1145. return ld.minus(10, ChronoUnit.DAYS);
  1146. }
  1147.  
  1148. static LocalDate plusPeriod() {
  1149. LocalDate ld = DateAndTimes.LD_20150618;
  1150.  
  1151. /**
  1152. * Define a {@link Period} of 1 year 2 month 3 days
  1153. * Create a {@link LocalDate} adding the period to {@link ld} by using {@link LocalDate#plus}
  1154. */
  1155. return ld.plus(Period.of(1,2,3));
  1156. }
  1157.  
  1158. static boolean isAfter() {
  1159. LocalDate ld = DateAndTimes.LD_20150618;
  1160. LocalDate ld2 = DateAndTimes.LD_20150807;
  1161.  
  1162. /**
  1163. * Check whether {@link ld2} is after {@link ld} or not
  1164. * by using {@link LocalDate#isAfter} or {@link LocalDate#isBefore}
  1165. */
  1166. return ld2.isAfter(ld);
  1167. }
  1168.  
  1169. static Period until() {
  1170. LocalDate ld = DateAndTimes.LD_20150618;
  1171. LocalDate ld2 = DateAndTimes.LD_20150807;
  1172.  
  1173. /**
  1174. * Create a period from {@link ld} till {@link ld2}
  1175. * by using {@link LocalDate#until}
  1176. */
  1177. return Period.between(ld, ld2);
  1178. }
  1179.  
  1180. }
  1181.  
  1182. class DateAndTimes {
  1183. public static final LocalDate LD_20150618 = LocalDate.of(2015, 6, 18);
  1184. public static final LocalDate LD_20150807 = LocalDate.of(2015, 8, 7);
  1185. }
  1186.  
  1187.  
  1188. /////////
  1189. LocalTime Problem 2 (1 / 2)
  1190.  
  1191. import java.time.Duration;
  1192. import java.time.LocalTime;
  1193. import java.time.temporal.ChronoField;
  1194. import java.time.temporal.ChronoUnit;
  1195.  
  1196. /**
  1197. * LocalTime API tests
  1198. */
  1199. public class LocalTimeTest {
  1200. public static void main(String[] args) {
  1201. System.out.println(localTimeOfHourToMinute());
  1202. System.out.println(localTimeOfHourToNanoSec());
  1203. System.out.println(localTimeParse());
  1204. System.out.println(localTimeWith());
  1205. System.out.println(localTimePlus());
  1206. System.out.println(localTimeMinus());
  1207. System.out.println(localTimeMinusDuration());
  1208. System.out.println(localDateIsBefore());
  1209. System.out.println(localTimeTruncatedTo());
  1210. }
  1211.  
  1212. static LocalTime localTimeOfHourToMinute() {
  1213. /**
  1214. * Create a {@link LocalTime} of 23:07 by using {@link LocalTime#of}
  1215. */
  1216. return LocalTime.of(23, 07);
  1217. }
  1218.  
  1219. static LocalTime localTimeOfHourToNanoSec() {
  1220. /**
  1221. * Create a {@link LocalTime} of 23:07:03.1 by using {@link LocalTime#of}
  1222. */
  1223. return LocalTime.of(23, 07, 03, 100000000);
  1224. }
  1225.  
  1226. static LocalTime localTimeParse() {
  1227. /**
  1228. * Create a {@link LocalTime} of 23:07:03.1 from String by using {@link LocalTime#parse}
  1229. */
  1230. return LocalTime.parse("23:07:03.1");
  1231. }
  1232.  
  1233. static LocalTime localTimeWith() {
  1234. LocalTime lt = DateAndTimes.LT_23073050;
  1235.  
  1236. /**
  1237. * Create a {@link LocalTime} from {@link lt} with hour 21
  1238. * by using {@link LocalTime#withHour} or {@link LocalTime#with}
  1239. */
  1240. return lt.withHour(21);
  1241. }
  1242.  
  1243. static LocalTime localTimePlus() {
  1244. LocalTime lt = DateAndTimes.LT_23073050;
  1245.  
  1246. /**
  1247. * Create a {@link LocalTime} from {@link lt} with 30 minutes later
  1248. * by using {@link LocalTime#plusMinutes} or {@link LocalTime#plus}
  1249. */
  1250. return lt.plusMinutes(30);
  1251. }
  1252.  
  1253. static LocalTime localTimeMinus() {
  1254. LocalTime lt = DateAndTimes.LT_23073050;
  1255.  
  1256. /**
  1257. * Create a {@link LocalTime} from {@link lt} with 3 hours before
  1258. * by using {@link LocalTime#minusHours} or {@link LocalTime#minus}
  1259. */
  1260. return lt.minusHours(3);
  1261. }
  1262.  
  1263.  
  1264. static LocalTime localTimeMinusDuration() {
  1265. LocalTime lt = DateAndTimes.LT_23073050;
  1266.  
  1267. /**
  1268. * Define a {@link Duration} of 3 hours 30 minutes and 20.2 seconds
  1269. * Create a {@link LocalTime} subtracting the duration from {@link lt} by using {@link LocalTime#minus}
  1270. */
  1271. return lt.minus(Duration.ofMillis((3*3600+30*60+20)*1000+200));
  1272. }
  1273.  
  1274. static boolean localDateIsBefore() {
  1275. LocalTime lt = DateAndTimes.LT_23073050;
  1276. LocalTime lt2 = DateAndTimes.LT_12100000;
  1277. /**
  1278. * Check whether {@link lt2} is before {@link lt} or not
  1279. * by using {@link LocalTime#isAfter} or {@link LocalTime#isBefore}
  1280. */
  1281. return lt.isAfter(lt2);
  1282. }
  1283.  
  1284. static LocalTime localTimeTruncatedTo() {
  1285. LocalTime lt = DateAndTimes.LT_23073050;
  1286.  
  1287. /**
  1288. * Create a {@link LocalTime} from {@link lt} truncated to minutes by using {@link LocalTime#truncatedTo}
  1289. */
  1290. return lt.truncatedTo(ChronoUnit.MINUTES);
  1291. }
  1292.  
  1293. static class DateAndTimes {
  1294. public static final LocalTime LT_23073050 = LocalTime.of(23, 7, 30, 500000000);
  1295. public static final LocalTime LT_12100000 = LocalTime.of(12, 10);
  1296. }
  1297.  
  1298. }
  1299.  
  1300. ////////////////
  1301. LocalDateTime Problem 3 (1 / 3)
  1302.  
  1303.  
  1304. import java.time.LocalDate;
  1305. import java.time.LocalDateTime;
  1306. import java.time.LocalTime;
  1307. import java.time.format.DateTimeFormatter;
  1308. import java.time.temporal.ChronoUnit;
  1309. import java.time.temporal.TemporalAdjuster;
  1310. import java.time.temporal.TemporalAdjusters;
  1311.  
  1312. /**
  1313. * LocalDateTime tests
  1314. */
  1315. public class LocalDateTimeTest {
  1316.  
  1317. public static void main(String[] args) {
  1318. System.out.println(localDateTimeOf());
  1319. System.out.println(localDateTimeParse());
  1320. System.out.println(localTimeWith());
  1321. System.out.println(localDatePlusMinus());
  1322. System.out.println(localDateTimeFormat());
  1323. System.out.println(toLocalDateAndTime());
  1324. System.out.println(toLocalDateTime());
  1325. }
  1326.  
  1327. static LocalDateTime localDateTimeOf() {
  1328. /**
  1329. * Create a {@link LocalDateTime} of 2015-06-20 23:07:30 by using {@link LocalDateTime#of}
  1330. */
  1331. return LocalDateTime.of(LocalDate.of(2015, 06, 20), LocalTime.of(23, 07, 30));
  1332. }
  1333.  
  1334. static LocalDateTime localDateTimeParse() {
  1335. /**
  1336. * Create a {@link LocalDateTime} of 2015-06-20 23:07:30 by using {@link LocalDateTime#parse}
  1337. */
  1338. return LocalDateTime.parse("2015-06-20t23:07:30");
  1339. }
  1340.  
  1341. static LocalDateTime localTimeWith() {
  1342. LocalDateTime ldt = DateAndTimes.LDT_20150618_23073050;
  1343.  
  1344. /**
  1345. * Create a {@link LocalDateTime} from {@link ldt}
  1346. * with first day of the next month and also truncated to hours.
  1347. */
  1348. return ldt.with(TemporalAdjusters.firstDayOfNextMonth()).truncatedTo(ChronoUnit.HOURS);
  1349. }
  1350.  
  1351. static LocalDateTime localDatePlusMinus() {
  1352. LocalDateTime ldt = DateAndTimes.LDT_20150618_23073050;
  1353.  
  1354. /**
  1355. * Create a {@link LocalDateTime} from {@link ldt} with 10 month later and 5 hours before
  1356. * by using {@link LocalDateTime#plus*} or {@link LocalDateTime#minus*}
  1357. */
  1358. return ldt.plus(10, ChronoUnit.MONTHS).minus(5, ChronoUnit.HOURS);
  1359. }
  1360.  
  1361. static String localDateTimeFormat() {
  1362. LocalDateTime ldt = DateAndTimes.LDT_20150618_23073050;
  1363.  
  1364. /**
  1365. * Format {@link ldt} to a {@link String} as "2015_06_18_23_07_30"
  1366. * by using {@link LocalDateTime#format} and {@link DateTimeFormatter#ofPattern}
  1367. */
  1368. return ldt.format(DateTimeFormatter.ofPattern("2015_06_18_23_07_30"));
  1369. }
  1370.  
  1371. static String toLocalDateAndTime() {
  1372. LocalDateTime ldt = DateAndTimes.LDT_20150618_23073050;
  1373.  
  1374. /**
  1375. * Create a {@link LocalDate} and a {@link LocalTime} from {@link ldt}
  1376. * by using {@link LocalDateTime#toLocalDate} and {@link LocalDateTime#toLocalTime}
  1377. */
  1378. LocalDate localDate = ldt.toLocalDate();
  1379. LocalTime localTime = ldt.toLocalTime();
  1380. return localDate.toString() + localTime.toString();
  1381. }
  1382.  
  1383. static String toLocalDateTime() {
  1384. LocalDate ld = DateAndTimes.LD_20150618;
  1385. LocalTime lt = DateAndTimes.LT_23073050;
  1386.  
  1387. /**
  1388. * Create two equal {@link LocalDateTime} from {@link ld} and {@link lt}
  1389. * by using {@link LocalDate#atTime} and {@link LocalTime#atDate}
  1390. */
  1391. LocalDateTime localDateTime1 = ld.atTime(lt);
  1392. LocalDateTime localDateTime2 = lt.atDate(ld);
  1393. return localDateTime1.toString() + " " + localDateTime2.toString();
  1394. }
  1395.  
  1396. static class DateAndTimes {
  1397. public static final LocalDate LD_20150618 = LocalDate.of(2015, 6, 18);
  1398. public static final LocalTime LT_23073050 = LocalTime.of(23, 7, 30, 500000000);
  1399. public static final LocalDateTime LDT_20150618_23073050 = LocalDateTime.of(2015, 6, 18, 23, 7, 30, 500000000);
  1400. }
  1401. }
  1402.  
  1403. /////////
  1404.  
  1405. ZonedDateTime Problem 4 (1 / 1)
  1406.  
  1407.  
  1408. import java.time.LocalDate;
  1409. import java.time.LocalDateTime;
  1410. import java.time.LocalTime;
  1411. import java.time.ZoneId;
  1412. import java.time.ZonedDateTime;
  1413. import java.time.format.DateTimeFormatter;
  1414.  
  1415. /**
  1416. * ZonedDateTime tests
  1417. */
  1418. public class ZonedDateTimeTest {
  1419. public static void main(String[] args) {
  1420. System.out.println(zonedDateTimeOf());
  1421. System.out.println(zonedDateTimeParse());
  1422. System.out.println(zonedDateTimeFormat());
  1423. System.out.println(toPST());
  1424. System.out.println(sameInstantAs());
  1425. System.out.println(sameLocalAs());
  1426. }
  1427.  
  1428. static ZonedDateTime zonedDateTimeOf() {
  1429. /**
  1430. * Create a {@link ZonedDateTime} with time of 2015-07-10 2:14:25.000 as Japan Standard Time
  1431. * by using {@link ZonedDateTime#of} and {@link ZoneId#of}
  1432. */
  1433. return ZonedDateTime.of(LocalDate.of(2015, 07, 10), LocalTime.of(2, 14, 25,000), ZoneId.of("Asia/Tokyo"));
  1434. }
  1435.  
  1436. static ZonedDateTime zonedDateTimeParse() {
  1437. /**
  1438. * Create a {@link ZonedDateTime} with time of 2015-06-18 23:07:25.000 as Japan Standard Time
  1439. * by using {@link ZonedDateTime#parse}
  1440. */
  1441. return ZonedDateTime.parse("2015-06-18t23:07:25+09:00[Asia/Tokyo]");
  1442. }
  1443.  
  1444. static String zonedDateTimeFormat() {
  1445. ZonedDateTime zdt = DateAndTimes.ZDT_20150618_23073050;
  1446.  
  1447. /**
  1448. * Format {@link zdt} to a {@link String} as "2015_06_18_23_07_30_JST"
  1449. * by using {@link ZonedDateTime#format}
  1450. */
  1451. return zdt.format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss_z"));
  1452. }
  1453.  
  1454. static ZonedDateTime toPST() {
  1455. LocalDateTime ldt = DateAndTimes.LDT_20150618_23073050;
  1456. /**
  1457. * Create a {@link ZonedDateTime} from {@link ldt} with Pacific Standard Time
  1458. */
  1459. ZoneId zone=ZoneId.of("America/Los_Angeles");
  1460. return ZonedDateTime.of(ldt, zone);
  1461. }
  1462.  
  1463. static ZonedDateTime sameInstantAs() {
  1464. ZonedDateTime zdt = DateAndTimes.ZDT_20150618_23073050;
  1465. /**
  1466. * Create a {@link ZonedDateTime} same instant as {@link zdt} with Pacific Standard Time
  1467. * by using {@link ZonedDateTime#withZoneSameInstant}
  1468. */
  1469. return zdt.withZoneSameInstant(ZoneId.of(("America/Los_Angeles")));
  1470. }
  1471.  
  1472. static ZonedDateTime sameLocalAs() {
  1473. ZonedDateTime zdt = DateAndTimes.ZDT_20150618_23073050;
  1474. /**
  1475. * Create a {@link ZonedDateTime} same local time as {@link zdt} with Pacific Standard Time
  1476. * by using {@link ZonedDateTime#withZoneSameLocal}
  1477. */
  1478. return zdt.withZoneSameLocal(ZoneId.of(("America/Los_Angeles")));
  1479. }
  1480.  
  1481. static class DateAndTimes {
  1482.  
  1483. public static final LocalDateTime LDT_20150618_23073050 = LocalDateTime.of(2015, 6, 18, 23, 7, 30, 500000000);
  1484. public static final ZonedDateTime
  1485. ZDT_20150618_23073050 = ZonedDateTime.of(LDT_20150618_23073050, ZoneId.of("Asia/Tokyo"));
  1486. }
  1487. }
  1488.  
  1489.  
  1490. ///////////
  1491. Лаб 5.
  1492. ///////
  1493.  
  1494. Комплексни броеви Problem 1 (1 / 2)
  1495.  
  1496. import java.util.Collections;
  1497. import java.util.LinkedList;
  1498. import java.util.Scanner;
  1499. class ComplexNumber<T extends Number,U extends Number> implements Comparable<ComplexNumber> {
  1500. T real;
  1501. U imaginary;
  1502. public ComplexNumber(T real, U imaginary) {
  1503. this.real = real;
  1504. this.imaginary = imaginary;
  1505. }
  1506. T getReal(){return real;}
  1507. U getImaginary(){return imaginary;}
  1508. public double modul(){
  1509. return Math.sqrt(real.doubleValue()*real.doubleValue()+imaginary.doubleValue()*imaginary.doubleValue());
  1510. }
  1511. @Override
  1512. public int compareTo(ComplexNumber c) {
  1513. if (modul()>c.modul())return 1;
  1514. else if(modul()==c.modul())return 0;
  1515. else return -1;
  1516. }
  1517. public String toString(){
  1518. if(imaginary.doubleValue()>=0)
  1519. return String.format("%.2f+%.2fi",real.doubleValue(),imaginary.doubleValue());
  1520. else
  1521. return String.format("%.2f%.2fi",real.doubleValue(),imaginary.doubleValue());
  1522.  
  1523. }
  1524.  
  1525.  
  1526. }
  1527. public class ComplexNumberTest {
  1528.  
  1529. public static void main(String[] args) {
  1530. Scanner jin = new Scanner(System.in);
  1531. int k = jin.nextInt();
  1532. if ( k == 0 ) { //test simple functions int
  1533. int r = jin.nextInt();int i = jin.nextInt();
  1534. ComplexNumber<Integer, Integer> c = new ComplexNumber<Integer, Integer>(r, i);
  1535. System.out.println(c);
  1536. System.out.println(c.getReal());
  1537. System.out.println(c.getImaginary());
  1538. System.out.println(c.modul());
  1539. }
  1540. if ( k == 1 ) { //test simple functions float
  1541. float r = jin.nextFloat();
  1542. float i = jin.nextFloat();
  1543. ComplexNumber<Float, Float> c = new ComplexNumber<Float, Float>(r, i);
  1544. System.out.println(c);
  1545. System.out.println(c.getReal());
  1546. System.out.println(c.getImaginary());
  1547. System.out.println(c.modul());
  1548. }
  1549. if ( k == 2 ) { //compareTo int
  1550. LinkedList<ComplexNumber<Integer,Integer>> complex = new LinkedList<ComplexNumber<Integer,Integer>>();
  1551. while ( jin.hasNextInt() ) {
  1552. int r = jin.nextInt(); int i = jin.nextInt();
  1553. complex.add(new ComplexNumber<Integer, Integer>(r, i));
  1554. }
  1555. System.out.println(complex);
  1556. Collections.sort(complex);
  1557. System.out.println(complex);
  1558. }
  1559. if ( k == 3 ) { //compareTo double
  1560. LinkedList<ComplexNumber<Double,Double>> complex = new LinkedList<ComplexNumber<Double,Double>>();
  1561. while ( jin.hasNextDouble() ) {
  1562. double r = jin.nextDouble(); double i = jin.nextDouble();
  1563. complex.add(new ComplexNumber<Double, Double>(r, i));
  1564. }
  1565. System.out.println(complex);
  1566. Collections.sort(complex);
  1567. System.out.println(complex);
  1568. }
  1569. if ( k == 4 ) { //compareTo mixed
  1570. LinkedList<ComplexNumber<Double,Integer>> complex = new LinkedList<ComplexNumber<Double,Integer>>();
  1571. while ( jin.hasNextDouble() ) {
  1572. double r = jin.nextDouble(); int i = jin.nextInt();
  1573. complex.add(new ComplexNumber<Double, Integer>(r, i));
  1574. }
  1575. System.out.println(complex);
  1576. Collections.sort(complex);
  1577. System.out.println(complex);
  1578. }
  1579. }
  1580. }
  1581.  
  1582. ////////////////
  1583. Генерички распоредувач Problem 2 (1 / 27)
  1584.  
  1585.  
  1586. import java.time.Instant;
  1587. import java.time.LocalDateTime;
  1588. import java.time.Period;
  1589. import java.time.ZoneId;
  1590. import java.util.ArrayList;
  1591. import java.util.Collections;
  1592. import java.util.List;
  1593. import java.util.Scanner;
  1594. import java.util.stream.Collectors;
  1595. import java.util.Comparator;
  1596.  
  1597. public class SchedulerTest {
  1598.  
  1599. static final LocalDateTime TIME = LocalDateTime.of(2016, 10, 25, 10, 15);
  1600.  
  1601. public static void main(String[] args) {
  1602. Scanner jin = new Scanner(System.in);
  1603. int k = jin.nextInt();
  1604. if (k == 0) { //test Timestamp with String
  1605. Timestamp<String> t = new Timestamp<>(TIME, jin.next());
  1606. System.out.println(t);
  1607. System.out.println(t.getTime());
  1608. System.out.println(t.getElement());
  1609. }
  1610. if (k == 1) { //test Timestamp with ints
  1611. Timestamp<Integer> t1 = new Timestamp<>(TIME, jin.nextInt());
  1612. System.out.println(t1);
  1613. System.out.println(t1.getTime());
  1614. System.out.println(t1.getElement());
  1615. Timestamp<Integer> t2 = new Timestamp<>(TIME.plusDays(10), jin.nextInt());
  1616. System.out.println(t2);
  1617. System.out.println(t2.getTime());
  1618. System.out.println(t2.getElement());
  1619. System.out.println(t1.compareTo(t2));
  1620. System.out.println(t2.compareTo(t1));
  1621. System.out.println(t1.equals(t2));
  1622. System.out.println(t2.equals(t1));
  1623. }
  1624. if (k == 2) {//test Timestamp with String, complex
  1625. Timestamp<String> t1 = new Timestamp<>(ofEpochMS(jin.nextLong()), jin.next());
  1626. System.out.println(t1);
  1627. System.out.println(t1.getTime());
  1628. System.out.println(t1.getElement());
  1629. Timestamp<String> t2 = new Timestamp<>(ofEpochMS(jin.nextLong()), jin.next());
  1630. System.out.println(t2);
  1631. System.out.println(t2.getTime());
  1632. System.out.println(t2.getElement());
  1633. System.out.println(t1.compareTo(t2));
  1634. System.out.println(t2.compareTo(t1));
  1635. System.out.println(t1.equals(t2));
  1636. System.out.println(t2.equals(t1));
  1637. }
  1638. if (k == 3) { //test Scheduler with String
  1639. Scheduler<String> scheduler = new Scheduler<>();
  1640. LocalDateTime now = LocalDateTime.now();
  1641. scheduler.add(new Timestamp<>(now.minusHours(2), jin.next()));
  1642. scheduler.add(new Timestamp<>(now.minusHours(1), jin.next()));
  1643. scheduler.add(new Timestamp<>(now.minusHours(4), jin.next()));
  1644. scheduler.add(new Timestamp<>(now.plusHours(2), jin.next()));
  1645. scheduler.add(new Timestamp<>(now.plusHours(4), jin.next()));
  1646. scheduler.add(new Timestamp<>(now.plusHours(1), jin.next()));
  1647. scheduler.add(new Timestamp<>(now.plusHours(5), jin.next()));
  1648. System.out.println(scheduler.next().getElement());
  1649. System.out.println(scheduler.last().getElement());
  1650. List<Timestamp<String>> result = scheduler.getAll(now.minusHours(3), now.plusHours(4).plusMinutes(15));
  1651. String out = result.stream()
  1652. .sorted()
  1653. .map(Timestamp::getElement)
  1654. .collect(Collectors.joining(", "));
  1655. System.out.println(out);
  1656. }
  1657. if (k == 4) {//test Scheduler with ints complex
  1658. Scheduler<Integer> scheduler = new Scheduler<>();
  1659. int counter = 0;
  1660. ArrayList<Timestamp<Integer>> forRemoval = new ArrayList<>();
  1661. while (jin.hasNextLong()) {
  1662. Timestamp<Integer> ti = new Timestamp<>(ofEpochMS(jin.nextLong()), jin.nextInt());
  1663. if ((counter & 7) == 0) {
  1664. forRemoval.add(ti);
  1665. }
  1666. scheduler.add(ti);
  1667. ++counter;
  1668. }
  1669. jin.next();
  1670.  
  1671. while (jin.hasNextLong()) {
  1672. LocalDateTime left = ofEpochMS(jin.nextLong());
  1673. LocalDateTime right = ofEpochMS(jin.nextLong());
  1674. List<Timestamp<Integer>> res = scheduler.getAll(left, right);
  1675. Collections.sort(res);
  1676. System.out.println(left + " <: " + print(res) + " >: " + right);
  1677. }
  1678. System.out.println("test");
  1679. List<Timestamp<Integer>> res = scheduler.getAll(ofEpochMS(0), ofEpochMS(Long.MAX_VALUE));
  1680. Collections.sort(res);
  1681. System.out.println(print(res));
  1682. forRemoval.forEach(scheduler::remove);
  1683. res = scheduler.getAll(ofEpochMS(0), ofEpochMS(Long.MAX_VALUE));
  1684. Collections.sort(res);
  1685. System.out.println(print(res));
  1686. }
  1687. }
  1688.  
  1689. private static LocalDateTime ofEpochMS(long ms) {
  1690. return LocalDateTime.ofInstant(Instant.ofEpochMilli(ms), ZoneId.systemDefault());
  1691. }
  1692.  
  1693. private static <T> String print(List<Timestamp<T>> res) {
  1694. if (res == null || res.size() == 0) return "NONE";
  1695. return res.stream()
  1696. .map(each -> each.getElement().toString())
  1697. .collect(Collectors.joining(", "));
  1698. }
  1699.  
  1700. }
  1701.  
  1702. class Timestamp <T> implements Comparable<Timestamp<T>>{
  1703. private LocalDateTime time;
  1704. private T element;
  1705. public Timestamp(LocalDateTime time, T element) {
  1706. this.time = time;
  1707. this.element = element;
  1708. }
  1709. public LocalDateTime getTime() {
  1710. return time;
  1711. }
  1712. public T getElement() {
  1713. return element;
  1714. }
  1715. public int compareTo(Timestamp t)
  1716. {
  1717. if(t.time.isAfter(time))
  1718. return -1;
  1719. else if(t.time.isBefore(time))
  1720. return 1;
  1721. else return 0;
  1722. }
  1723. @Override
  1724. public boolean equals(Object obj) {
  1725. if (this == obj)
  1726. return true;
  1727. if (obj == null)
  1728. return false;
  1729. if (getClass() != obj.getClass())
  1730. return false;
  1731. Timestamp other = (Timestamp) obj;
  1732. /*if (element == null) {
  1733. if (other.element != null)
  1734. return false;
  1735. } else if (!element.equals(other.element))
  1736. return false;*/
  1737. if (time == null) {
  1738. if (other.time != null)
  1739. return false;
  1740. } else if (!time.equals(other.time))
  1741. return false;
  1742. return true;
  1743. }
  1744. public String toString(){
  1745. return String.format("%s %s",time,element);
  1746. }
  1747.  
  1748. }
  1749. class Scheduler<T>{
  1750. private Timestamp<T> [] ts;
  1751. int count;
  1752. public Scheduler(){
  1753. ts=new Timestamp[947];
  1754. count=0;
  1755. }
  1756. public void add(Timestamp<T> t)
  1757. {
  1758. ts[count]=t;
  1759. count++;
  1760. }
  1761. public boolean remove(Timestamp<T> t)
  1762. {
  1763. for(int i=0;i<count;i++)
  1764. {
  1765. if(t.equals(ts[i]))
  1766. {
  1767. for(int j=i;j<count-1;j++)
  1768. {
  1769. ts[j]=ts[j+1];
  1770. }
  1771. ts[count-1]=null;
  1772. count--;
  1773. return true;
  1774. }
  1775. }
  1776. return false;
  1777. }
  1778. public Timestamp<T> next(){
  1779. Timestamp<T> tmp=null;
  1780. LocalDateTime now=LocalDateTime.now();
  1781. for(int i=1;i<count;i++)
  1782. {
  1783. if(ts[i].getTime().isAfter(now))
  1784. {
  1785. if(tmp==null)
  1786. {
  1787. tmp=ts[i];
  1788. }
  1789. else if(ts[i].getTime().isBefore(tmp.getTime()))
  1790. {
  1791. tmp=ts[i];
  1792. }
  1793. }
  1794. }
  1795. return tmp;
  1796. }
  1797. public Timestamp<T> last(){
  1798. Timestamp<T> tmp=null;
  1799. LocalDateTime now=LocalDateTime.now();
  1800. for(int i=1;i<count;i++)
  1801. {
  1802. if(ts[i].getTime().isBefore(now))
  1803. {
  1804. if(tmp==null)
  1805. {
  1806. tmp=ts[i];
  1807. }
  1808. if(ts[i].getTime().isAfter(tmp.getTime()))
  1809. {
  1810. tmp=ts[i];
  1811. }
  1812. }
  1813. }
  1814. return tmp;
  1815. }
  1816. List<Timestamp<T>>getAll(LocalDateTime begin, LocalDateTime end)
  1817. {
  1818. List list=new ArrayList<>();
  1819. for(int i=0;i<count;i++)
  1820. {
  1821. if(ts[i].getTime().isAfter(begin)&&ts[i].getTime().isBefore(end))
  1822. {
  1823. list.add(ts[i]);
  1824. }
  1825. }
  1826. return list;
  1827. }
  1828. }
  1829.  
  1830.  
  1831. ////////////
  1832. Генерички ред Problem 3 (1 / 2)
  1833.  
  1834. import java.util.LinkedList;
  1835. import java.util.Scanner;
  1836. class EmptyQueueException extends Exception{
  1837. }
  1838. class Node<T>
  1839. {
  1840. private T element;
  1841. private Node<T> next;
  1842. public Node(T element, Node<T> next) {
  1843. this.element = element;
  1844. this.next = next;
  1845. }
  1846. public T getElement() {
  1847. return element;
  1848. }
  1849. public Node<T> getNext() {
  1850. return next;
  1851. }
  1852. public void setNext(Node<T> next) {
  1853. this.next = next;
  1854. }
  1855. }
  1856. class Queue<T>{
  1857. private Node<T> first,last;
  1858. public Queue()
  1859. {
  1860. first=null;
  1861. last=null;
  1862. }
  1863. public boolean isEmpty()
  1864. {
  1865. if(first==null)
  1866. return true;
  1867. else return false;
  1868. }
  1869. public void enqueue(T element){
  1870. if(first==null)
  1871. {
  1872. first=new Node<T>(element,null);
  1873. last=first;
  1874. }
  1875. else
  1876. {
  1877. last.setNext(new Node<T>(element,null));
  1878. last=last.getNext();
  1879. }
  1880. }
  1881. public T dequeue()throws EmptyQueueException
  1882. {
  1883. if(isEmpty())throw new EmptyQueueException();
  1884. T out=first.getElement();
  1885. first=first.getNext();
  1886. return out;
  1887. }
  1888. public T peek()throws EmptyQueueException
  1889. {
  1890. if(isEmpty())throw new EmptyQueueException();
  1891. T out=first.getElement();
  1892. return out;
  1893. }
  1894. public T inspect() throws EmptyQueueException
  1895. {
  1896. if(isEmpty())throw new EmptyQueueException();
  1897. T out=last.getElement();
  1898. return out;
  1899. }
  1900. public int count(){
  1901. int br=0;
  1902. if(first!=null)
  1903. {
  1904. Node<T> tmp=first;
  1905. while(tmp!=null)
  1906. {
  1907. br++;
  1908. tmp=tmp.getNext();
  1909. }
  1910. }
  1911. return br;
  1912. }
  1913. }
  1914. public class QueueTest {
  1915.  
  1916.  
  1917. public static void main(String[] args) throws EmptyQueueException {
  1918. Scanner jin = new Scanner(System.in);
  1919. int k = jin.nextInt();
  1920. if ( k == 0 ) { //Simple test case with one int element
  1921. int t = jin.nextInt();
  1922. Queue<Integer> queue = new Queue<Integer>();
  1923. System.out.println("Queue empty? - "+queue.isEmpty());
  1924. System.out.println("Queue count? - "+queue.count());
  1925. System.out.println("Queue enqueue "+t);
  1926. queue.enqueue(t);
  1927. System.out.println("Queue empty? - "+queue.isEmpty());
  1928. System.out.println("Queue count? - "+queue.count());
  1929. System.out.println("Queue dequeue? - "+queue.dequeue());
  1930. System.out.println("Queue empty? - "+queue.isEmpty());
  1931. System.out.println("Queue count? - "+queue.count());
  1932. }
  1933. if ( k == 1 ) { //a more complex test with strings
  1934. Queue<String> queue = new Queue<String>();
  1935. int counter = 0;
  1936. while ( jin.hasNextInt() ) {
  1937. String t = jin.next();
  1938. queue.enqueue(t);
  1939. ++counter;
  1940. }
  1941. for ( int i = 0 ; i < counter ; ++i ) {
  1942. System.out.println(queue.dequeue());
  1943. }
  1944. queue.enqueue(jin.next());
  1945. System.out.println("Queue inspect? - "+queue.inspect());
  1946. System.out.println("Queue peek? - "+queue.peek());
  1947. queue.enqueue(queue.dequeue());
  1948. queue.enqueue(jin.next());
  1949. System.out.println("Queue inspect? - "+queue.inspect());
  1950. System.out.println("Queue peek? - "+queue.peek());
  1951. }
  1952. if ( k == 2 ) {
  1953. Queue<String> queue = new Queue<String>();
  1954. String next = "";
  1955. int counter = 0;
  1956. while ( true ) {
  1957. next = jin.next();
  1958. if ( next.equals("stop") ) break;
  1959. queue.enqueue(next);
  1960. ++counter;
  1961. }
  1962. while ( !queue.isEmpty() ) {
  1963. if ( queue.count()<counter) System.out.print(" ");
  1964. System.out.print(queue.dequeue());
  1965. }
  1966. }
  1967. if ( k == 3 ) { //random testing
  1968. Queue<Double> queue = new Queue<Double>();
  1969. LinkedList<Double> java_queue = new LinkedList<Double>();
  1970. boolean flag = true;
  1971. int n = jin.nextInt();
  1972. for ( int i = 0 ; i < n ; ++i ) {
  1973. double q = Math.random();
  1974. if ( q < 0.5 ) {
  1975. double t = Math.random();
  1976. queue.enqueue(t);
  1977. java_queue.addFirst(t);
  1978. }
  1979. if ( q < 0.8&&q >= 0.5 ) {
  1980. if ( ! java_queue.isEmpty() ) {
  1981. double t1 = java_queue.removeLast();
  1982. double t2 = queue.dequeue();
  1983. flag &= t1==t2;
  1984. }
  1985. else {
  1986. flag &= java_queue.isEmpty()==queue.isEmpty();
  1987. }
  1988. }
  1989. if ( q < 0.9 && q >= 0.8 ) {
  1990. if ( ! java_queue.isEmpty() ) {
  1991. double t1 = java_queue.peekLast();
  1992. double t2 = queue.peek();
  1993. flag &= t1==t2;
  1994. }
  1995. else {
  1996. flag &= java_queue.isEmpty()==queue.isEmpty();
  1997. }
  1998. }
  1999. if ( q < 1 && q >= 0.9 ) {
  2000. if ( ! java_queue.isEmpty() ) {
  2001. double t1 = java_queue.peekFirst();
  2002. double t2 = queue.inspect();
  2003. flag &= t1==t2;
  2004. }
  2005. else {
  2006. flag &= java_queue.isEmpty()==queue.isEmpty();
  2007. }
  2008. }
  2009. flag &= java_queue.size()==queue.count();
  2010. }
  2011. System.out.println("Compared to the control queue the results were the same? - "+flag);
  2012. }
  2013. if ( k == 4 ) { //performance testing
  2014. Queue<Double> queue = new Queue<Double>();
  2015. int n = jin.nextInt();
  2016. for ( int i = 0 ; i < n ; ++i ) {
  2017. if ( Math.random() < 0.5 ) {
  2018. queue.enqueue(Math.random());
  2019. }
  2020. else {
  2021. if ( ! queue.isEmpty() ) {
  2022. queue.dequeue();
  2023. }
  2024. }
  2025. }
  2026. System.out.println("You implementation finished in less then 3 seconds, well done!");
  2027. }
  2028. if ( k == 5 ) { //Exceptions testing
  2029. Queue<String> queue = new Queue<String>();
  2030. try {
  2031. queue.dequeue();
  2032. }
  2033. catch ( Exception e ) {
  2034. System.out.println(e.getClass().getSimpleName());
  2035. }
  2036. try {
  2037. queue.peek();
  2038. }
  2039. catch ( Exception e ) {
  2040. System.out.println(e.getClass().getSimpleName());
  2041. }
  2042. try {
  2043. queue.inspect();
  2044. }
  2045. catch ( Exception e ) {
  2046. System.out.println(e.getClass().getSimpleName());
  2047. }
  2048. }
  2049. }
  2050.  
  2051. }
  2052.  
  2053. /////////////////
  2054.  
  2055. Генерички контејнер со променлива должина Problem 4 (2 / 21)
  2056. import java.util.Scanner;
  2057. import java.util.Arrays;
  2058. import java.util.LinkedList;
  2059. class ResizableArray<T> {
  2060. private T [] niza;
  2061. private int size;
  2062. public ResizableArray() {
  2063. niza= (T[])new Object[100];
  2064. size=0;
  2065. }
  2066. public void addElement(T element) {
  2067. if (size==niza.length) niza=Arrays.copyOf(niza,niza.length+1);
  2068. niza[size++]=element;
  2069. }
  2070. public boolean removeElement (T element) {
  2071. for (int i=0;i<size;i++)
  2072. {
  2073. if (niza[i].equals(element))
  2074. {
  2075.  
  2076. for (int j=i;j<size-1;j++) {
  2077. niza[i]=niza[j+1];
  2078.  
  2079.  
  2080. }
  2081. size--;
  2082. return true;
  2083. }
  2084. }
  2085. return false;
  2086. }
  2087. public int count() {
  2088. return size;
  2089. }
  2090. public boolean contains(T element) {
  2091. for (int i=0;i<size;i++)
  2092. {
  2093. if(niza[i].equals(element)) {
  2094. return true;
  2095. }
  2096. }
  2097. return false;
  2098. }
  2099. public boolean isEmpty() {
  2100. if(niza.length==0) return false;
  2101. else return true;
  2102. }
  2103. public T elementAt(int index) throws ArrayIndexOutOfBoundsException {
  2104. if(index<0||index>=size) throw new ArrayIndexOutOfBoundsException();
  2105. else return niza[index];
  2106. }
  2107. public Object[] toArray() {
  2108. return niza;
  2109. }
  2110. public static <T> void copyAll(ResizableArray<? super T> dest , ResizableArray<? extends T>src) {
  2111.  
  2112. for(int i = 0, j = dest.size; i < src.size; i++,j++)
  2113. dest.niza[j] = src.niza[i];
  2114.  
  2115. dest.size = dest.size+ src.size;
  2116. }
  2117. }
  2118. class IntegerArray extends ResizableArray<Integer> {
  2119. public double sum() {
  2120. int s=0;
  2121. for (int i=0;i<count();i++) {
  2122. s=s+elementAt(i);
  2123. } return s;
  2124. }
  2125. public double mean() {
  2126. return sum()/count();
  2127. }
  2128. public int countNonZero () {
  2129. int br=0;
  2130. for (int i=0;i<count();i++) {
  2131. if (elementAt(i)!=0) {
  2132. br++;
  2133. }
  2134. }
  2135. return br;
  2136. }
  2137. public IntegerArray increment(int offset) {
  2138.  
  2139. IntegerArray tmp = new IntegerArray();
  2140.  
  2141. for(int i = 0; i < count(); ++i)
  2142. tmp.addElement(elementAt(i) + offset);
  2143.  
  2144. return tmp;
  2145. }
  2146. public IntegerArray distinct() {
  2147. IntegerArray tmp = new IntegerArray();
  2148. IntegerArray.copyAll(tmp, this);
  2149. for (int i=0;i<tmp.count();i++) {
  2150. for (int j=0;j<i;j++) {
  2151. if (tmp.elementAt(i)==tmp.elementAt(j))
  2152. {
  2153. tmp.removeElement(tmp.elementAt(j));
  2154. i--;
  2155. j--;
  2156. }
  2157. }
  2158. }
  2159. return tmp;
  2160.  
  2161. }
  2162. }
  2163. public class ResizableArrayTest {
  2164.  
  2165. public static void main(String[] args) {
  2166. Scanner jin = new Scanner(System.in);
  2167. int test = jin.nextInt();
  2168. if ( test == 0 ) { //test ResizableArray on ints
  2169. ResizableArray<Integer> a = new ResizableArray<Integer>();
  2170. System.out.println(a.count());
  2171. int first = jin.nextInt();
  2172. a.addElement(first);
  2173. System.out.println(a.count());
  2174. int last = first;
  2175. while ( jin.hasNextInt() ) {
  2176. last = jin.nextInt();
  2177. a.addElement(last);
  2178. }
  2179. System.out.println(a.count());
  2180. System.out.println(a.contains(first));
  2181. System.out.println(a.contains(last));
  2182. System.out.println(a.removeElement(first));
  2183. System.out.println(a.contains(first));
  2184. System.out.println(a.count());
  2185. }
  2186. if ( test == 1 ) { //test ResizableArray on strings
  2187. ResizableArray<String> a = new ResizableArray<String>();
  2188. System.out.println(a.count());
  2189. String first = jin.next();
  2190. a.addElement(first);
  2191. System.out.println(a.count());
  2192. String last = first;
  2193. for ( int i = 0 ; i < 4 ; ++i ) {
  2194. last = jin.next();
  2195. a.addElement(last);
  2196. }
  2197. System.out.println(a.count());
  2198. System.out.println(a.contains(first));
  2199. System.out.println(a.contains(last));
  2200. System.out.println(a.removeElement(first));
  2201. System.out.println(a.contains(first));
  2202. System.out.println(a.count());
  2203. ResizableArray<String> b = new ResizableArray<String>();
  2204. ResizableArray.copyAll(b, a);
  2205. System.out.println(b.count());
  2206. System.out.println(a.count());
  2207. System.out.println(a.contains(first));
  2208. System.out.println(a.contains(last));
  2209. System.out.println(b.contains(first));
  2210. System.out.println(b.contains(last));
  2211. ResizableArray.copyAll(b, a);
  2212. System.out.println(b.count());
  2213. System.out.println(a.count());
  2214. System.out.println(a.contains(first));
  2215. System.out.println(a.contains(last));
  2216. System.out.println(b.contains(first));
  2217. System.out.println(b.contains(last));
  2218. System.out.println(b.removeElement(first));
  2219. System.out.println(b.contains(first));
  2220. System.out.println(b.removeElement(first));
  2221. System.out.println(b.contains(first));
  2222.  
  2223. System.out.println(a.removeElement(first));
  2224. ResizableArray.copyAll(b, a);
  2225. System.out.println(b.count());
  2226. System.out.println(a.count());
  2227. System.out.println(a.contains(first));
  2228. System.out.println(a.contains(last));
  2229. System.out.println(b.contains(first));
  2230. System.out.println(b.contains(last));
  2231. }
  2232. if ( test == 2 ) { //test IntegerArray
  2233. IntegerArray a = new IntegerArray();
  2234. System.out.println(a.isEmpty());
  2235. while ( jin.hasNextInt() ) {
  2236. a.addElement(jin.nextInt());
  2237. }
  2238. jin.next();
  2239. System.out.println(a.sum());
  2240. System.out.println(a.mean());
  2241. System.out.println(a.countNonZero());
  2242. System.out.println(a.count());
  2243. IntegerArray b = a.distinct();
  2244. System.out.println(b.sum());
  2245. IntegerArray c = a.increment(5);
  2246. System.out.println(c.sum());
  2247. if ( a.sum() > 100 )
  2248. ResizableArray.copyAll(a, a);
  2249. else
  2250. ResizableArray.copyAll(a, b);
  2251. System.out.println(a.sum());
  2252. System.out.println(a.removeElement(jin.nextInt()));
  2253. System.out.println(a.sum());
  2254. System.out.println(a.removeElement(jin.nextInt()));
  2255. System.out.println(a.sum());
  2256. System.out.println(a.removeElement(jin.nextInt()));
  2257. System.out.println(a.sum());
  2258. System.out.println(a.contains(jin.nextInt()));
  2259. System.out.println(a.contains(jin.nextInt()));
  2260. }
  2261. if ( test == 3 ) { //test insanely large arrays
  2262. LinkedList<ResizableArray<Integer>> resizable_arrays = new LinkedList<ResizableArray<Integer>>();
  2263. for ( int w = 0 ; w < 500 ; ++w ) {
  2264. ResizableArray<Integer> a = new ResizableArray<Integer>();
  2265. int k = 2000;
  2266. int t = 1000;
  2267. for ( int i = 0 ; i < k ; ++i ) {
  2268. a.addElement(i);
  2269. }
  2270.  
  2271. a.removeElement(0);
  2272. for ( int i = 0 ; i < t ; ++i ) {
  2273. a.removeElement(k-i-1);
  2274. }
  2275. resizable_arrays.add(a);
  2276. }
  2277. System.out.println("You implementation finished in less then 3 seconds, well done!");
  2278. }
  2279. }
  2280.  
  2281. }
  2282.  
  2283. ////////////////
  2284. Лаб 6.
  2285. ////////////
  2286.  
  2287. Супер-стринг Problem 1 (2 / 9)
  2288.  
  2289. import java.util.LinkedList;
  2290. import java.util.Scanner;
  2291. import java.util.Stack;
  2292. class SuperString{
  2293. private LinkedList<String> superstring;
  2294. private Stack<String> last;
  2295. public SuperString() {
  2296. superstring=new LinkedList<String>();
  2297. last=new Stack<String>();
  2298. }
  2299. public void append(String s)
  2300. {
  2301. superstring.add(s);
  2302. last.push(s);
  2303. }
  2304. public void insert(String s)
  2305. {
  2306. superstring.addFirst(s);
  2307. last.push(s);
  2308. }
  2309. public boolean contains(String s)
  2310. {
  2311. return toString().contains(s);
  2312. }
  2313. public String toString()
  2314. {
  2315. StringBuilder sb=new StringBuilder();
  2316. superstring.forEach(temp->sb.append(temp));
  2317. return sb.toString();
  2318. }
  2319. public static String wordreverse(String s)
  2320. {
  2321. StringBuilder sb=new StringBuilder();
  2322. for(int i=s.length()-1;i>=0;i--)
  2323. {
  2324. sb.append(s.charAt(i));
  2325. }
  2326. return sb.toString();
  2327. }
  2328. public void removeLast(int k)
  2329. {
  2330. for(int i=0;i<k;i++)
  2331. {
  2332. String lastword=last.pop();
  2333. superstring.remove(wordreverse(lastword));
  2334. superstring.remove(lastword);
  2335. }
  2336. }
  2337. public void reverse()
  2338. {
  2339. LinkedList<String> revs=new LinkedList<String>();
  2340. superstring.forEach(temp->revs.addFirst(wordreverse(temp)));
  2341. superstring=revs;
  2342. }
  2343. }
  2344. public class SuperStringTest {
  2345.  
  2346. public static void main(String[] args) {
  2347. Scanner jin = new Scanner(System.in);
  2348. int k = jin.nextInt();
  2349. if ( k == 0 ) {
  2350. SuperString s = new SuperString();
  2351. while ( true ) {
  2352. int command = jin.nextInt();
  2353. if ( command == 0 ) {//append(String s)
  2354. s.append(jin.next());
  2355. }
  2356. if ( command == 1 ) {//insert(String s)
  2357. s.insert(jin.next());
  2358. }
  2359. if ( command == 2 ) {//contains(String s)
  2360. System.out.println(s.contains(jin.next()));
  2361. }
  2362. if ( command == 3 ) {//reverse()
  2363. s.reverse();
  2364. }
  2365. if ( command == 4 ) {//toString()
  2366. System.out.println(s);
  2367. }
  2368. if ( command == 5 ) {//removeLast(int k)
  2369. s.removeLast(jin.nextInt());
  2370. }
  2371. if ( command == 6 ) {//end
  2372. break;
  2373. }
  2374. }
  2375. }
  2376. }
  2377.  
  2378. }
  2379.  
  2380.  
  2381. ////////////////
  2382.  
  2383. Листа на цели броеви Problem 2 (1 / 7)
  2384.  
  2385. import java.util.ArrayList;
  2386. import java.util.Scanner;
  2387. class IntegerList{
  2388. private ArrayList<Integer> integerlist;
  2389. public IntegerList()
  2390. {
  2391. integerlist=new ArrayList<Integer>();
  2392. }
  2393. public IntegerList(Integer [] a)
  2394. {
  2395. integerlist=new ArrayList<Integer>(a.length);
  2396. for(int i=0;i<a.length;i++)
  2397. integerlist.add(a[i]);
  2398. }
  2399. private void addlargeridx(int el,int idx)
  2400. {
  2401. int length=integerlist.size();
  2402. while(idx!=length)
  2403. {
  2404. integerlist.add(0);
  2405. length++;
  2406. }
  2407. integerlist.add(el);
  2408. }
  2409. public void add(int el,int idx)
  2410. {
  2411. if(idx>=integerlist.size())
  2412. addlargeridx(el,idx);
  2413. else
  2414. integerlist.add(idx, el);
  2415. }
  2416. public int remove(int idx) throws ArrayIndexOutOfBoundsException
  2417. {
  2418. if(idx<0)
  2419. throw new ArrayIndexOutOfBoundsException();
  2420. return integerlist.remove(idx);
  2421. }
  2422. public void set(int el,int idx)throws ArrayIndexOutOfBoundsException
  2423. {
  2424. if(idx<0)
  2425. throw new ArrayIndexOutOfBoundsException();
  2426. integerlist.set(idx, el);
  2427. }
  2428. public int get(int idx)throws ArrayIndexOutOfBoundsException
  2429. {
  2430. if(idx<0)
  2431. throw new ArrayIndexOutOfBoundsException();
  2432. return integerlist.get(idx);
  2433. }
  2434. public int size()
  2435. {
  2436. return integerlist.size();
  2437. }
  2438. public int count(int el)
  2439. {
  2440. //long n=integerlist.stream().filter(s->s.equals(el)).count();
  2441. int c=0;
  2442. for(Integer integ : integerlist)
  2443. if(integ.equals(el))
  2444. c++;
  2445. return c;
  2446. }
  2447. public void removeDuplicates()
  2448. {
  2449. for(int i=0;i<integerlist.size()-1;i++)
  2450. for(int j=i+1;j<integerlist.size();j++)
  2451. if(integerlist.get(i).equals(integerlist.get(j)))
  2452. {
  2453. integerlist.remove(i);
  2454. i--;
  2455. break;
  2456. }
  2457. }
  2458. public int sumFirst(int k)
  2459. {
  2460. int sum=0;
  2461. int l=Math.min(k,integerlist.size());
  2462. for(int i=0;i<l;i++)
  2463. sum+=integerlist.get(i);
  2464. return sum;
  2465. }
  2466. public int sumLast(int k)
  2467. {
  2468. int sum=0;
  2469. int n=integerlist.size();
  2470. int l=Math.max(n-k,0);
  2471. for(int i=l;i<n;i++)
  2472. sum+=integerlist.get(i);
  2473. return sum;
  2474. }
  2475. public void shiftRight(int idx,int k)throws ArrayIndexOutOfBoundsException
  2476. {
  2477. if(idx<0)
  2478. throw new ArrayIndexOutOfBoundsException();
  2479. int el=integerlist.remove(idx);
  2480. integerlist.add((idx+k)%(integerlist.size()+1), el);
  2481. }
  2482. public void shiftLeft(int idx,int k)throws ArrayIndexOutOfBoundsException
  2483. {
  2484. if(idx<0)
  2485. throw new ArrayIndexOutOfBoundsException();
  2486. int el=integerlist.remove(idx);
  2487. int id1=k%(integerlist.size()+1);
  2488. integerlist.add((idx-id1+integerlist.size()+1)%(integerlist.size()+1), el);
  2489. }
  2490. public IntegerList addValue(int value)
  2491. {
  2492. Integer a[]=new Integer[integerlist.size()];
  2493. for(int i=0;i<integerlist.size();i++)
  2494. a[i]=integerlist.get(i)+value;
  2495. return new IntegerList(a);
  2496. }
  2497.  
  2498. }
  2499. public class IntegerListTest {
  2500.  
  2501. public static void main(String[] args) {
  2502. Scanner jin = new Scanner(System.in);
  2503. int k = jin.nextInt();
  2504. if ( k == 0 ) { //test standard methods
  2505. int subtest = jin.nextInt();
  2506. if ( subtest == 0 ) {
  2507. IntegerList list = new IntegerList();
  2508. while ( true ) {
  2509. int num = jin.nextInt();
  2510. if ( num == 0 ) {
  2511. list.add(jin.nextInt(), jin.nextInt());
  2512. }
  2513. if ( num == 1 ) {
  2514. list.remove(jin.nextInt());
  2515. }
  2516. if ( num == 2 ) {
  2517. print(list);
  2518. }
  2519. if ( num == 3 ) {
  2520. break;
  2521. }
  2522. }
  2523. }
  2524. if ( subtest == 1 ) {
  2525. int n = jin.nextInt();
  2526. Integer a[] = new Integer[n];
  2527. for ( int i = 0 ; i < n ; ++i ) {
  2528. a[i] = jin.nextInt();
  2529. }
  2530. IntegerList list = new IntegerList(a);
  2531. print(list);
  2532. }
  2533. }
  2534. if ( k == 1 ) { //test count,remove duplicates, addValue
  2535. int n = jin.nextInt();
  2536. Integer a[] = new Integer[n];
  2537. for ( int i = 0 ; i < n ; ++i ) {
  2538. a[i] = jin.nextInt();
  2539. }
  2540. IntegerList list = new IntegerList(a);
  2541. while ( true ) {
  2542. int num = jin.nextInt();
  2543. if ( num == 0 ) { //count
  2544. System.out.println(list.count(jin.nextInt()));
  2545. }
  2546. if ( num == 1 ) {
  2547. list.removeDuplicates();
  2548. }
  2549. if ( num == 2 ) {
  2550. print(list.addValue(jin.nextInt()));
  2551. }
  2552. if ( num == 3 ) {
  2553. list.add(jin.nextInt(), jin.nextInt());
  2554. }
  2555. if ( num == 4 ) {
  2556. print(list);
  2557. }
  2558. if ( num == 5 ) {
  2559. break;
  2560. }
  2561. }
  2562. }
  2563. if ( k == 2 ) { //test shiftRight, shiftLeft, sumFirst , sumLast
  2564. int n = jin.nextInt();
  2565. Integer a[] = new Integer[n];
  2566. for ( int i = 0 ; i < n ; ++i ) {
  2567. a[i] = jin.nextInt();
  2568. }
  2569. IntegerList list = new IntegerList(a);
  2570. while ( true ) {
  2571. int num = jin.nextInt();
  2572. if ( num == 0 ) { //count
  2573. list.shiftLeft(jin.nextInt(), jin.nextInt());
  2574. }
  2575. if ( num == 1 ) {
  2576. list.shiftRight(jin.nextInt(), jin.nextInt());
  2577. }
  2578. if ( num == 2 ) {
  2579. System.out.println(list.sumFirst(jin.nextInt()));
  2580. }
  2581. if ( num == 3 ) {
  2582. System.out.println(list.sumLast(jin.nextInt()));
  2583. }
  2584. if ( num == 4 ) {
  2585. print(list);
  2586. }
  2587. if ( num == 5 ) {
  2588. break;
  2589. }
  2590. }
  2591. }
  2592. }
  2593.  
  2594. public static void print(IntegerList il) {
  2595. if ( il.size() == 0 ) System.out.print("EMPTY");
  2596. for ( int i = 0 ; i < il.size() ; ++i ) {
  2597. if ( i > 0 ) System.out.print(" ");
  2598. System.out.print(il.get(i));
  2599. }
  2600. System.out.println();
  2601. }
  2602.  
  2603. }
  2604. /////////////
  2605. Лаб 7.
  2606. /////////////
  2607.  
  2608. Генерички магацин (Stack) Problem 1 (1 / 2)
  2609.  
  2610. import java.util.Date;
  2611. import java.util.EmptyStackException;
  2612. import java.util.LinkedList;
  2613. import java.util.Scanner;
  2614.  
  2615. class Stack<T>{
  2616. private T []stack;
  2617. private int n;
  2618. public Stack()
  2619. {
  2620. stack=(T[])new Object[100000];
  2621. n=0;
  2622. }
  2623. public void push(T element)
  2624. {
  2625. stack[n++]=element;
  2626. }
  2627. public T peek() throws EmptyStackException
  2628. {
  2629. if(isEmpty())
  2630. throw new EmptyStackException();
  2631. return stack[n-1];
  2632. }
  2633. public T pop() throws EmptyStackException
  2634. {
  2635. if(isEmpty())
  2636. throw new EmptyStackException();
  2637. T pop=stack[n-1];
  2638. stack[n-1]=null;
  2639. n--;
  2640. return pop;
  2641. }
  2642. public boolean isEmpty()
  2643. {
  2644. return n==0;
  2645. }
  2646. }
  2647.  
  2648. public class StackTest {
  2649.  
  2650. public static void main(String[] args) {
  2651. Scanner jin = new Scanner(System.in);
  2652. int k = jin.nextInt();
  2653. System.out.println("Test#"+k);
  2654. if ( k == 0 ) {
  2655. System.out.println("testing: Stack::push(T) , Stack::pop():T , T is Integer");
  2656. int n = jin.nextInt();
  2657. Stack<Integer> stack = new Stack<Integer>();
  2658. System.out.println("Pushing elements:");
  2659. for ( int i = 1 ; i <= n ; ++i ) {
  2660. if ( i > 1 ) System.out.print(" ");System.out.print(i);
  2661. stack.push(i);
  2662. }
  2663. System.out.println();
  2664. System.out.println("Poping elements:");
  2665. for ( int i = n ; i >= 1 ; --i ) {
  2666. if ( i < n ) System.out.print(" ");
  2667. System.out.print(stack.pop());
  2668. }
  2669. System.out.println();
  2670. }
  2671. if ( k == 1 ) {
  2672. System.out.println("testing: Stack::push(T) , Stack::pop():T , T is String");
  2673.  
  2674. int n = jin.nextInt();
  2675. Stack<String> stack = new Stack<String>();
  2676. System.out.println("Pushing elements:");
  2677. for ( int i = 0 ; i < n ; ++i ) {
  2678. if ( i > 0 ) System.out.print(" ");
  2679. String next = jin.next();System.out.print(next);
  2680. stack.push(next);
  2681. }
  2682. System.out.println();
  2683. System.out.println("Poping elements:");
  2684. for ( int i = 0 ; i < n ; ++i ) {
  2685. if ( i > 0 ) System.out.print(" ");
  2686. System.out.print(stack.pop());
  2687. }
  2688. }
  2689. if ( k == 2 ) {
  2690. System.out.println("testing: Stack::push(T) , Stack::pop():T , Stack::isEmpty():boolean, T is Double");
  2691.  
  2692. Stack<Double> stack = new Stack<Double>();
  2693. System.out.println("Pushing elements:");
  2694. boolean flag = false;
  2695. while ( jin.hasNextDouble() ) {
  2696. double d = jin.nextDouble();
  2697. stack.push(d);
  2698. if ( flag ) System.out.print(" ");
  2699. System.out.printf("%.2f",d);
  2700. flag = true;
  2701. }
  2702. int i = 0;
  2703. System.out.println();
  2704. System.out.println("Poping elements:");
  2705. while ( ! stack.isEmpty() ) {
  2706. if ( i > 0 ) System.out.print(" ");++i;
  2707. System.out.printf("%.2f",stack.pop());
  2708. }
  2709. }
  2710. if ( k == 3 ) {
  2711. System.out.println("testing: Stack::push(T) , Stack::pop():T , Stack::isEmpty():boolean , Stack::peek():T , T is Long");
  2712.  
  2713. int n = jin.nextInt();
  2714. Stack<Long> stack = new Stack<Long>();
  2715. LinkedList<Long> control_stack = new LinkedList<Long>();
  2716. boolean exact = true;
  2717. for ( int i = 0 ; exact&&i < n ; ++i ) {
  2718. if ( Math.random() < 0.5 ) {//add
  2719. long to_add = (long)(Math.random()*456156168);
  2720. stack.push(to_add);control_stack.addFirst(to_add);
  2721. }
  2722. else {
  2723. exact &= control_stack.isEmpty()==stack.isEmpty();
  2724. if ( exact&&! stack.isEmpty() ) {
  2725. if ( Math.random() > 0.7 ) exact &= control_stack.removeFirst().equals(stack.pop());
  2726. else exact &= control_stack.peekFirst().equals(stack.peek());
  2727. }
  2728. }
  2729. }
  2730. System.out.println("Your stack outputs compared to the built in java stack were the same? "+exact);
  2731. }
  2732. if ( k == 4 ) {
  2733. System.out.println("testing: Stack::pop():T , Stack::isEmpty():boolean , Stack::peek():T , T is Long");
  2734.  
  2735. Stack<Date> test_stack = new Stack<Date>();
  2736.  
  2737. System.out.println("Stack empty? "+test_stack.isEmpty());
  2738. try {
  2739. test_stack.pop();
  2740. System.out.println("NO exeption was thrown when trying to pop from an empty stack!");
  2741.  
  2742. } catch(Exception e) {
  2743. System.out.print("Exeption thrown when trying to pop from an empty stack ");
  2744. System.out.println(e.getClass().getSimpleName());
  2745. }
  2746. try {
  2747. test_stack.peek();
  2748. System.out.println("NO exeption was thrown when trying to peek in an empty stack!");
  2749. } catch(Exception e) {
  2750. System.out.print("Exeption thrown when trying to peek in an empty stack ");
  2751. System.out.println(e.getClass().getSimpleName());
  2752. }
  2753. }
  2754. }
  2755.  
  2756. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement