code
stringlengths
3
1.18M
language
stringclasses
1 value
package pack; public class factor { public static void main(String[] args) { long start; start = System.nanoTime(); System.out.println(factorial(5)); System.out.println("Time of running: "+(System.nanoTime()-start)+" nanosec"); start = System.nanoTime(); System.out.println(factorial_rec(10)); System.out.println("Time of running: "+(System.nanoTime()-start)+" nanosec"); } public static int factorial(int n) { int ret = 1; for (int i = 1; i <= n; ++i) ret *= i; return ret; } public static int factorial_rec(int n) { if (n == 0) return 1; return n * factorial_rec(n-1); } }
Java
package pack; import java.math.BigInteger; import java.util.Random; public class Karatsuba { public static BigInteger karatsuba(BigInteger x, BigInteger y) { int N = Math.max(x.bitLength(), y.bitLength()); if (N <= 2000) return x.multiply(y); N = (N / 2) + (N % 2); BigInteger b = x.shiftRight(N); BigInteger a = x.subtract(b.shiftLeft(N)); BigInteger d = y.shiftRight(N); BigInteger c = y.subtract(d.shiftLeft(N)); BigInteger ac = karatsuba(a, c); BigInteger bd = karatsuba(b, d); BigInteger abcd = karatsuba(a.add(b), c.add(d)); return ac.add(abcd.subtract(ac).subtract(bd).shiftLeft(N)).add(bd.shiftLeft(2*N)); } public static void main(String[] args) { long start, stop; Random random = new Random(); int N = 10000; BigInteger a = new BigInteger(N, random); BigInteger b = new BigInteger(N, random); start = System.nanoTime(); BigInteger c = karatsuba(a, b); stop = System.nanoTime(); System.out.println("(karatsuba) " + a.toString() + " * " + b.toString() + " = " + c.toString()); System.out.println("Time of running: "+(stop-start)+" nanosec"); System.out.println(); start = System.nanoTime(); BigInteger d = a.multiply(b); stop = System.nanoTime(); System.out.println("(multiply) " + a.toString() + " * " + b.toString() + " = " + c.toString()); System.out.println("Time of running: "+(stop-start)+" nanosec"); System.out.println(); System.out.println("Equals: " + c.equals(d)); } }
Java
package pack; import java.io.File; public class ShowDirectoryAndSize { public ShowDirectoryAndSize(String path) { File root = new File(path); printDirectory(root.getPath(), 0); } public long printDirectory(String path, int level) { long sizeByte = 0; File tmp = new File(path); for(int k = 0; k < level; k++) System.out.print("\t"); System.out.println(tmp.getPath()); File[] files = tmp.listFiles(); for(int k = 0; k < files.length; k++) if(files[k].isDirectory()) sizeByte += printDirectory(files[k].getPath(), level+1); else sizeByte += files[k].length(); for(int k = 0; k < level; k++) System.out.print("\t"); System.out.println("Size: " + sizeByte); return sizeByte; } public static void main(String[] args) { ShowDirectoryAndSize a = new ShowDirectoryAndSize(".."); } }
Java
package Algo; public class Summ { private Summ () { } static int [] summ (int [] a, int[] b) { if (a.length>b.length) return summ_iter (a, b); else return summ_iter (b, a); } static int [] summ_iter (int [] max, int [] min) { int res [] = new int [max.length + 1]; int i=max.length-1; for (int j=min.length - 1; j>=0; j--) { if (max[i]+min[j]+res[i+1]<10) { res[i+1]=max[i]+min[j]+res[i+1]; i--; } else { res[i+1]=max[i]+min[j]+res[i+1]-10; res[i]=1; i--; } } for (i=i; i>=0; i--) if (max[i]+res[i+1]<10) { res[i+1]=max[i]+res[i+1]; } else { res[i+1]=0; res[i]=1; } return res; } static void full_mass (int [] a) { for (int i=0; i<a.length; i++) a[i]=(int)(Math.random()*9); } static void print_mass (int []a) { int i=0; while (a[i]==0) i++; for (i=i; i<a.length; i++) System.out.print(a[i] + " "); System.out.print("\n"); } public static void main(String[] args) { int a [] = new int [16]; int b [] = new int [20]; full_mass(a); full_mass(b); print_mass(a); print_mass(b); print_mass(summ(a,b)); } }
Java
package Algo; import java.io.File; public class Node { File file; Node father = null; Node son = null; Node brother = null; public Node (File name) { this.file = name; } }
Java
public class Factorial { public Factorial() { } private double factorial(double n) { if (n==1) return 1; else return n*factorial(n-1); } public static void main(String[] args) { Factorial f = new Factorial(); double m; for (int i=5; i<170; i+=5) { long before = System.nanoTime(); m=f.factorial(i); long after = System.nanoTime(); long diff = after - before; System.out.print(i + "\t" + m + "\t" + diff + "\n"); } } }
Java
package Algo; public class BH { static int arr[]; static int level = 0; public BH (int [] mass) { arr = mass; } public static int get_left (int i) { if (2*i>=arr.length) return 0; return arr[2*i]; } public static int get_right (int i) { if (2*i+1>=arr.length) return 0; return arr[2*i+1]; } public static int Min_element () { return arr[1]; } public static void printBinaryTree() { print_binary_tree(1); } private static void print_binary_tree (int j) { for (int i=0; i<level; i++) System.out.print (" "); System.out.print (arr [j]); level ++; if (get_left(j)!=0) { System.out.print ("\n"); for (int i=0; i<level; i++) System.out.print (" "); print_binary_tree (2*j); } if (get_right(j)!=0) { System.out.print ("\n"); for (int i=0; i<level; i++) System.out.print (" "); print_binary_tree (2*j+1); } level--; } public static void Insert (int num) { int i=arr.length-1; if (arr[i]!=0) makeNewMass(); else { while (arr[i]==0) {i--;} } i++; arr[i]=num; while (arr[(int)(i/2)]>arr[i] && i>1) { swap ((int)(i/2),i); i=(int)(i/2); } } public static void swap ( int a, int b) { int t=arr[a]; arr[a]=arr[b]; arr[b]=t; } public static void makeNewMass () { int [] mass = new int [(int)(arr.length*1.3)]; for (int i=0; i<arr.length; i++) mass[i]=arr[i]; arr=mass; } public static void remove_min () { int i = arr.length-1; while (arr[i]==0) {i--;} arr[1]=arr[i]; arr[i]=0; i=1; while (arr[i]>get_left(i) && get_left(i)!=0 || arr[i]>get_right(i) && get_right(i)!=0) { if ((arr[i])>get_left(i) && get_left(i)!=0 && get_left(i)<get_right(i) && get_right(i)!=0) { swap (i, 2*i); i=2*i; } else { swap (i, 2*i+1); i=2*i+1; } } } public static void main(String[] args) { int mass [] = {0,2,3,2,4,5,7,9,6,8,9,11,8,9}; arr=mass; print_binary_tree (1); System.out.print("\n"); Insert(15); Insert(4); Insert(19); Insert(3); Insert(1); Insert(-10); System.out.print("\n15, 4, 19, 3, 1, -10 have been inserted into the tree: \n"); printBinaryTree(); System.out.print("\nMinimum: " + Min_element()); remove_min(); System.out.print("\nMinimum has been deleted: \n"); print_binary_tree (1); } }
Java
public class algo { public static void nod () { int i, min, max, a, b, temp, iter=0; max=(int)(Math.random()*2000000000); min=(int)(Math.random()*2000000000); System.out.printf("%d \t", max); System.out.printf("%d \t", min); long before = System.currentTimeMillis(); if ((min==1) || (max==1)) {System.out.println("1\t"); return;} if (min==max) {System.out.print(min); return;} if (min>max) {temp=max; max=min; min=temp;} a=min; b=max; i=2; while (i<=Math.sqrt(min)) { iter++; if (min%i==0 && max%i==0) {min=min/i; max=max/i;} else i++; } long after = System.currentTimeMillis(); long diff = after - before; if ((i=a/min)==(b/max)) {System.out.printf(" %d \t", i); System.out.printf("%.10f\t", diff/1e3); System.out.printf(" %d \n", iter); return;} else System.out.println("error!\n"); return; } public static void main(String [] args) { System.out.print("Number 1\t"+"Number 2\t"+"NOD\t"+"Time\t"+"the number of iterations\n"); for (int i=0; i<10; i++) { algo.nod(); } return; } }
Java
package Algo; public class Element { int num; Element next=null; public Element (int num) { this.num=num; this.next=null; } }
Java
package Algo; public class Element { int num; Element next=null; public Element (int num) { this.num=num; this.next=null; } }
Java
package horse; public class horse { int razmer=5; static void print_mass(int [][]mass, int a, int b) { for (int i=0; i<a; i++) { for (int j=0; j<b; j++) System.out.print(mass[i][j] + "\t"); System.out.print("\n"); } System.out.print("\n"); } static int count=0; private void horse_move (int [][]arr, int level, int str, int poz) { //System.out.print("level = " + level +" str= "+ str +" poz = "+poz+ "\n" ); arr[str][poz]=level; if(level == razmer*razmer) { print_mass(arr, razmer, razmer); count++; // System.out.print("count = "+ count + "\n"); } else { if (str+2<razmer && poz+1<razmer && arr[str+2][poz+1]==0)horse_move(arr, level+1, str+2, poz+1); if (str+2<razmer && poz-1<razmer && poz-1>=0 && arr[str+2][poz-1]==0)horse_move(arr, level+1, str+2, poz-1); if (str+1<razmer && poz+2<razmer && arr[str+1][poz+2]==0)horse_move(arr, level+1, str+1, poz+2); if (str+1<razmer && poz-2<razmer && poz-2>=0 && arr[str+1][poz-2]==0)horse_move(arr, level+1, str+1, poz-2); if (str-2<razmer && poz-1<razmer && poz-1>=0 && str-2>=0 && arr[str-2][poz-1]==0)horse_move(arr, level+1, str-2, poz-1); if (str-2<razmer && poz+1<razmer && str-2>=0 && arr[str-2][poz+1]==0)horse_move(arr, level+1, str-2, poz+1); if (str-1<razmer && poz+2<razmer && str-1>=0 && arr[str-1][poz+2]==0)horse_move(arr, level+1, str-1, poz+2); if (str-1<razmer && poz-2<razmer && poz-2>=0 && str-1>=0 && arr[str-1][poz-2]==0)horse_move(arr, level+1, str-1, poz-2); } arr[str][poz]=0; // íå ïîïàëè íå â îäíî èç óñëîâèé âûøå - ýòîò õîä ïðèâîäèò â òóïèê //System.out.print("level = " + level + "\n"); } public static void main(String[] args) { horse a= new horse(); int[][] arr = new int[a.razmer][a.razmer]; for (int i=0; i<a.razmer; i++) for (int j=0; j<a.razmer; j++) a.horse_move(arr, 1, i, j); System.out.print("the number of all possible " + count ); } }
Java
package ru.java2e; public class Bullet { int x, y; int rx, ry; Tank sender; public Bullet(int x, int y, int rx, int ry) { this.x = x; this.y = y; this.rx = rx; this.ry = ry; } public void moveB() { x += rx; y += ry; } public void setSender(Tank tank) { this.sender = tank; } public Tank getSender() { return sender; } }
Java
package ru.java2e; import java.awt.*; //import java.awt.event.KeyEvent; import java.util.Vector; //import javax.swing.ImageIcon; //import javax.swing.JFrame; import javax.swing.JPanel; enum Direction { Up, Right, Down, Left; } enum UnitGroup { NoneGroup, PlayerGroup, BotGroup; } public class Tank extends JPanel { int x; int y; Direction direct; int hp; UnitGroup group; int explosionLvl; int speedBullet; Image imgTank; Image imgDefaultUp, imgDefaultRight, imgDefaultDown, imgDefaultLeft; Image imgExplosion; Vector<Bullet> bullets = new Vector<Bullet>(); public Tank(int x, int y) { setLocTank(x, y); setDirectTank(Direction.Up); this.hp = 100; this.group = UnitGroup.NoneGroup; this.explosionLvl = 0; this.speedBullet = 2; } public void setHP(int hp) { this.hp = hp; } public int getHP() { return hp; } public boolean takeDamage(int damage) { this.hp -= damage; if(this.hp <= 0) { hp = 0; return true; } else return false; } public void percentTurnTank() { int turn = (int) (Math.random()*3); if(turn == 0) { if(getDirectTank() == Direction.Up) setDirectTank(Direction.Right); else if(getDirectTank() == Direction.Right) setDirectTank(Direction.Down); else if(getDirectTank() == Direction.Down) setDirectTank(Direction.Left); else if(getDirectTank() == Direction.Left) setDirectTank(Direction.Up); } else if (turn == 1) { if(getDirectTank() == Direction.Up) setDirectTank(Direction.Down); else if(getDirectTank() == Direction.Right) setDirectTank(Direction.Left); else if(getDirectTank() == Direction.Down) setDirectTank(Direction.Up); else if(getDirectTank() == Direction.Left) setDirectTank(Direction.Right); } else if (turn == 2) { if(getDirectTank() == Direction.Up) setDirectTank(Direction.Left); else if(getDirectTank() == Direction.Right) setDirectTank(Direction.Up); else if(getDirectTank() == Direction.Down) setDirectTank(Direction.Right); else if(getDirectTank() == Direction.Left) setDirectTank(Direction.Down); } } public void setTankImages(Image imgUp, Image imgRight, Image imgDown, Image imgLeft) { this.imgDefaultUp = imgUp; this.imgDefaultRight = imgRight; this.imgDefaultDown = imgDown; this.imgDefaultLeft = imgLeft; this.imgTank = imgDefaultUp; } public void setDirectTank(Direction direct) { this.direct = direct; if(direct == Direction.Up) this.imgTank = this.imgDefaultUp; else if(direct == Direction.Right) this.imgTank = this.imgDefaultRight; else if(direct == Direction.Down) this.imgTank = this.imgDefaultDown; else if(direct == Direction.Left) this.imgTank = this.imgDefaultLeft; } public Direction getDirectTank() { return direct; } public Image getTankImage() { return this.imgTank; } public void setLocTank(int x, int y) { this.x = x; this.y = y; } public void setGroup(UnitGroup group) { this.group = group; } public UnitGroup getGroup() { return group; } public int getX() { return x; } public int getY() { return y; } public void fire() { if(!Map.autoFire && bullets.size() == 1) return; int rx = 0, ry = 0; if(direct == Direction.Up) ry -= speedBullet; else if(direct == Direction.Right) rx += speedBullet; else if(direct == Direction.Down) ry += speedBullet; else if(direct == Direction.Left) rx -= speedBullet; int x = (Map.sizeCell*this.x) + (Map.sizeCell/2); int y = (Map.sizeCell*this.y) + (Map.sizeCell/2); Bullet bullet = new Bullet(x, y, rx, ry); bullet.setSender(this); bullets.add(bullet); } public Bullet[] getArrayBullets() { return bullets.toArray(new Bullet[0]); } public void moveAllBullet() { for(int k = 0; k < bullets.size(); k++) { bullets.elementAt(k).moveB(); } } public boolean deleteBullet(int index) { int num = bullets.size(); bullets.removeElementAt(index); if(num != bullets.size()) return true; else return false; } }
Java
package ru.java2e; import javax.swing.*; public abstract class MainClass { public static void main(String[] args) { JFrame window = new JFrame(); window.setSize(640, 640); window.setTitle("Battle City"); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.add(new Map()); window.setVisible(true); window.setLocationRelativeTo(null); } }
Java
package ru.java2e; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.Timer; public class Map extends JPanel implements ActionListener { public class Cell { boolean empty; int brick; boolean concrete; boolean water; boolean tank; public Cell() { empty = true; brick = 0; concrete = false; water = false; tank = false; } } int test = 0; boolean blockMove = false; boolean gameOver = false; boolean gameStart = false; static boolean autoFire = false; int autoFireCombinationKey = 0; int kills = 0; int numbofbots = 10; Tank player; Tank[] units = new Tank[numbofbots]; Cell world[][]; int mapSize = 18; static int sizeCell = 32; Timer startTimer = new Timer(5000, this); Timer endTimer = new Timer(5000, this); Timer bulletTimer = new Timer(10, this); Timer botsTimer = new Timer(350, this); public Image imgBrick, imgBrick1Fire, imgBrick2Fire, imgBrick3Fire, imgConcrete, imgWater, imgPlayerTankUp, imgPlayerTankLeft, imgPlayerTankDown, imgPlayerTankRight, imgBullet, imgBotTankUp, imgBotTankRight, imgBotTankDown, imgBotTankLeft, imgHeadImage, imgGameOver, imgWin; Image[] imgExplosions; public Map() { addKeyListener(new AL()); setFocusable(true); setBackground(Color.BLACK); ImageIcon ii_brick = new ImageIcon("res/brick.png"); ImageIcon ii_brick1Fire = new ImageIcon("res/brick1Fire.png"); ImageIcon ii_brick2Fire = new ImageIcon("res/brick2Fire.png"); ImageIcon ii_brick3Fire = new ImageIcon("res/brick3Fire.png"); ImageIcon ii_concrete = new ImageIcon("res/concrete.png"); ImageIcon ii_water = new ImageIcon("res/water.png"); ImageIcon ii_playerU = new ImageIcon("res/player-u.png"); ImageIcon ii_playerR = new ImageIcon("res/player-r.png"); ImageIcon ii_playerD = new ImageIcon("res/player-d.png"); ImageIcon ii_playerL = new ImageIcon("res/player-l.png"); ImageIcon ii_botU = new ImageIcon("res/bot-u.png"); ImageIcon ii_botR = new ImageIcon("res/bot-r.png"); ImageIcon ii_botD = new ImageIcon("res/bot-d.png"); ImageIcon ii_botL = new ImageIcon("res/bot-l.png"); ImageIcon ii_bullet = new ImageIcon("res/bullet.png"); ImageIcon ii_gameover = new ImageIcon("res/game-over.png"); ImageIcon ii_headimage = new ImageIcon("res/head_image.png"); ImageIcon ii_winimage = new ImageIcon("res/win_image.png"); ImageIcon ii_explosion1 = new ImageIcon("res/explosion1.png"); ImageIcon ii_explosion2 = new ImageIcon("res/explosion2.png"); ImageIcon ii_explosion3 = new ImageIcon("res/explosion3.png"); ImageIcon ii_explosion4 = new ImageIcon("res/explosion4.png"); ImageIcon ii_explosion5 = new ImageIcon("res/explosion5.png"); ImageIcon ii_explosion6 = new ImageIcon("res/explosion6.png"); imgBrick = ii_brick.getImage(); imgBrick1Fire = ii_brick1Fire.getImage(); imgBrick2Fire = ii_brick2Fire.getImage(); imgBrick3Fire = ii_brick3Fire.getImage(); imgConcrete = ii_concrete.getImage(); imgWater = ii_water.getImage(); imgPlayerTankUp = ii_playerU.getImage(); imgPlayerTankRight = ii_playerR.getImage(); imgPlayerTankDown = ii_playerD.getImage(); imgPlayerTankLeft = ii_playerL.getImage(); imgBotTankUp = ii_botU.getImage(); imgBotTankRight = ii_botR.getImage(); imgBotTankDown = ii_botD.getImage(); imgBotTankLeft = ii_botL.getImage(); imgBullet = ii_bullet.getImage(); imgGameOver = ii_gameover.getImage(); imgHeadImage = ii_headimage.getImage(); imgWin = ii_winimage.getImage(); imgExplosions = new Image[6]; imgExplosions[0] = ii_explosion1.getImage(); imgExplosions[1] = ii_explosion2.getImage(); imgExplosions[2] = ii_explosion3.getImage(); imgExplosions[3] = ii_explosion4.getImage(); imgExplosions[4] = ii_explosion5.getImage(); imgExplosions[5] = ii_explosion6.getImage(); initWorld(); player = createTank(10, 10, imgPlayerTankUp, imgPlayerTankRight, imgPlayerTankDown, imgPlayerTankLeft); player.setGroup(UnitGroup.PlayerGroup); player.setHP(100); units[0] = player; for(int k = 1; k < units.length; k++) { int x = (int) (Math.random()*mapSize); int y = (int) (Math.random()*mapSize); units[k] = createTank(x, y, imgBotTankUp, imgBotTankRight, imgBotTankDown, imgBotTankLeft); if(units[k] == null) { k--; continue; } units[k].setGroup(UnitGroup.BotGroup); units[k].setHP(200); } for(int y = 0; y < mapSize; y++) for(int x = 0; x < mapSize; x++) { if(!isTank(x, y)) { int num = (int) (Math.random()*100 + 1); if(num < 30) setBrick(x, y); if(num > 80 && num < 90) setConcrete(x, y); if(num > 40 && num < 50) setWater(x, y); } } startTimer.start(); bulletTimer.start(); botsTimer.start(); } private void initWorld() { world = new Cell[mapSize][mapSize]; for(int y = 0; y < mapSize; y++) for(int x = 0; x < mapSize; x++) world[x][y] = new Cell(); } private Tank createTank(int x, int y, Image imgUp, Image imgRight, Image imgDown, Image imgLeft) { Tank tank = new Tank(x, y); tank.setTankImages(imgUp, imgRight, imgDown, imgLeft); if(setTank(x, y, tank)) return tank; return null; } private boolean setTank(int x, int y, Tank tank) { if(world[x][y].empty == true) { world[x][y].tank = true; world[x][y].empty = false; tank.setLocTank(x, y); return true; } return false; } private boolean setBrick(int x, int y) { if(world[x][y].empty == true) { world[x][y].brick = 1; world[x][y].empty = false; return true; } else if(world[x][y].brick > 0) { if(world[x][y].brick < 4) world[x][y].brick++; else { world[x][y].brick = 0; world[x][y].empty = true; } return true; } return false; } private boolean setConcrete(int x, int y) { if(world[x][y].empty == true) { world[x][y].concrete = true; world[x][y].empty = false; return true; } return false; } private boolean setWater(int x, int y) { if(world[x][y].empty == true) { world[x][y].water = true; world[x][y].empty = false; return true; } return false; } // private boolean isEmpty(int x, int y) // { // if((x >= 0 && x < mapSize) && (y >= 0 && y < mapSize)) // if(world[x][y].empty == true) // return true; // return false; // } private int isBrick(int x, int y) { if((x >= 0 && x < mapSize) && (y >= 0 && y < mapSize)) return world[x][y].brick; return 0; } private boolean isConcrete(int x, int y) { if((x >= 0 && x < mapSize) && (y >= 0 && y < mapSize)) if(world[x][y].empty == false) if(world[x][y].concrete == true) return true; return false; } private boolean isWater(int x, int y) { if((x >= 0 && x < mapSize) && (y >= 0 && y < mapSize)) if(world[x][y].empty == false) if(world[x][y].water == true) return true; return false; } private boolean isTank(int x, int y) { if((x >= 0 && x < mapSize) && (y >= 0 && y < mapSize)) if(world[x][y].empty == false) if(world[x][y].tank == true) return true; return false; } private boolean clearTank(int x, int y) { if(world[x][y].empty == false) if(world[x][y].tank == true) { world[x][y].tank = false; world[x][y].empty = true; return true; } return false; } public void actionPerformed(ActionEvent e) { if(e.getSource() == endTimer) gameOver = true; else if(e.getSource() == startTimer) { if(!gameStart) { gameStart = true; startTimer.stop(); } } else if(e.getSource() == bulletTimer) { if(!gameOver && gameStart) { for(int k = 0; k < units.length; k++) { units[k].moveAllBullet(); Bullet bullets[] = units[k].getArrayBullets(); for(int i = 0; i < bullets.length; i++) { int x = bullets[i].x/sizeCell; int y = bullets[i].y/sizeCell; if(x < 0 || x > mapSize || y < 0 || y > mapSize || isConcrete(x, y) || isBrick(x, y) > 0 || isTank(x, y)) { if(isTank(x, y)) { Tank receiver = null; Tank sender = bullets[i].getSender(); for(Tank tank: units) if (tank.getX() == x && tank.getY() == y) { receiver = tank; break; } if(sender != receiver) { if(sender.getGroup() != receiver.getGroup()) if(receiver.takeDamage(100)) { receiver.explosionLvl = 1; clearTank(x, y); kills++; if(receiver.getGroup() == UnitGroup.PlayerGroup) { clearTank(x, y); kills--; endTimer.start(); blockMove = true; } } units[k].deleteBullet(i); bullets = units[k].getArrayBullets(); i = 0; } } else { if(isBrick(x, y) > 0) setBrick(x, y); units[k].deleteBullet(i); bullets = units[k].getArrayBullets(); i = 0; } } } } } } else if(e.getSource() == botsTimer) { moveBot(); fireBot(); } repaint(); } public void paint(Graphics g) { super.paint(g); Graphics2D g2 = (Graphics2D) g; if(gameStart) { if(!gameOver) { if(kills != numbofbots-1) { for(int y = 0; y < mapSize; y++) { for(int x = 0; x < mapSize; x++) { if(isBrick(x, y) == 1) g2.drawImage(imgBrick, x*sizeCell, y*sizeCell, null); else if(isBrick(x, y) == 2) g2.drawImage(imgBrick1Fire, x*sizeCell, y*sizeCell, null); else if(isBrick(x, y) == 3) g2.drawImage(imgBrick2Fire, x*sizeCell, y*sizeCell, null); else if(isBrick(x, y) == 4) g2.drawImage(imgBrick3Fire, x*sizeCell, y*sizeCell, null); if(isConcrete(x, y)) g2.drawImage(imgConcrete, x*sizeCell, y*sizeCell, null); if(isWater(x, y)) g2.drawImage(imgWater, x*sizeCell, y*sizeCell, null); } } for(int k = 0; k < units.length; k++) { Bullet bullets[] = units[k].getArrayBullets(); for(int l = 0; l < bullets.length; l++) { ImageIcon icon = new ImageIcon(imgBullet); int x = bullets[l].x - icon.getIconWidth()/2; int y = bullets[l].y - icon.getIconHeight()/2; g2.drawImage(imgBullet, x, y, null); } } for(int k = 0; k < units.length; k++) if(units[k].getHP() > 0) g2.drawImage(units[k].getTankImage(), units[k].getX()*sizeCell, units[k].getY()*sizeCell, null); else if(units[k].explosionLvl != 0) { g2.drawImage(imgExplosions[units[k].explosionLvl - 1],units[k].getX()*sizeCell, units[k].getY()*sizeCell, null); units[k].explosionLvl++; if(units[k].explosionLvl > 6) units[k].explosionLvl = 0; } g2.setColor(Color.RED); for(int y = 0; y < mapSize; y++) for(int x = 0; x < mapSize; x++) if(isTank(x, y)) g2.drawOval(x*sizeCell+sizeCell/2, y*sizeCell+sizeCell/2, 3, 3); } else g2.drawImage(imgWin, 0, 0, null); } else g2.drawImage(imgGameOver, 0, 0, null); } else g2.drawImage(imgHeadImage, 0, 0, null); } private void moveBot() { for(int k = 1; k < units.length; k++) { if(units[k].getHP() > 0) { int botX = units[k].getX(); int botY = units[k].getY(); int exitX = botX; int exitY = botY; if(units[k].getDirectTank() == Direction.Up) exitY--; else if(units[k].getDirectTank() == Direction.Right) exitX++; else if(units[k].getDirectTank() == Direction.Down) exitY++; else if(units[k].getDirectTank() == Direction.Left) exitX--; if(exitX != botX || exitY != botY) if(exitX >= 0 && exitX <= mapSize-1) if(exitY >= 0 && exitY <= mapSize-1) { clearTank(botX, botY); if(isBrick(exitX, exitY) == 0 && !isConcrete(exitX, exitY) && !isWater(exitX, exitY) && !isTank(exitX, exitY)) setTank(exitX, exitY, units[k]); else { setTank(botX, botY, units[k]); units[k].percentTurnTank(); } } int percentTurn = (int) (Math.random()*100); if(percentTurn < 10) units[k].percentTurnTank(); repaint(); } } } private void fireBot() { int procent = (int)(Math.random()*100); if(procent < 32) { bulletTimer.start(); for(int k = 1; k < units.length; k++) if(units[k].getHP() > 0) units[k].fire(); } } private class AL extends KeyAdapter { public void keyPressed(KeyEvent e) { int tankX = player.getX(); int tankY = player.getY(); int exitX = tankX; int exitY = tankY; int key = e.getKeyCode(); System.out.println("Key: " + key); if(!blockMove) { if (key == KeyEvent.VK_SPACE) player.fire(); else if (key == KeyEvent.VK_UP || key == KeyEvent.VK_W) { if(player.getDirectTank() != Direction.Up) player.setDirectTank(Direction.Up); else exitY--; } else if (key == KeyEvent.VK_RIGHT || key == KeyEvent.VK_D) { if(player.getDirectTank() != Direction.Right) player.setDirectTank(Direction.Right); else exitX++; } else if (key == KeyEvent.VK_DOWN || key == KeyEvent.VK_S) { if(player.getDirectTank() != Direction.Down) player.setDirectTank(Direction.Down); else exitY++; } else if (key == KeyEvent.VK_LEFT || key == KeyEvent.VK_A) { if(player.getDirectTank() != Direction.Left) player.setDirectTank(Direction.Left); else exitX--; } else if(key == KeyEvent.VK_CONTROL && autoFireCombinationKey == 0) autoFireCombinationKey = 1; else if(key == KeyEvent.VK_SHIFT && autoFireCombinationKey == 1) autoFireCombinationKey = 2; else if(key == KeyEvent.VK_BACK_SPACE && autoFireCombinationKey == 2) { System.out.println("Test"); autoFire = !autoFire; } else autoFireCombinationKey = 0; if(exitX != tankX || exitY != tankY) if(exitX >= 0 && exitX <= mapSize-1) if(exitY >= 0 && exitY <= mapSize-1) { clearTank(tankX, tankY); if(isBrick(exitX, exitY) == 0 && !isConcrete(exitX, exitY) && !isWater(exitX, exitY) && !isTank(exitX, exitY)) setTank(exitX, exitY, player); else setTank(tankX, tankY, player); } repaint(); } } } }
Java
import java.io.File; public class DirectAndSize { public DirectAndSize(String path) { File root = new File(path); printDirect(root.getPath(), 0); } public long printDirect(String path, int level) { long sizeByt = 0; File tmp = new File(path); for(int l = 0; l < level; l++) System.out.print("\t"); System.out.println(tmp.getPath()); File[] files = tmp.listFiles(); for(int l = 0; l < files.length; l++) if(files[l].isDirectory()) sizeByt += printDirect(files[l].getPath(), level+1); else sizeByt += files[l].length(); for(int l = 0; l < level; l++) System.out.print("\t"); System.out.println("Size: " + sizeByt); return sizeByt; } public static void main(String[] args) { DirectAndSize a = new DirectAndSize(".."); } }
Java
import java.util.Random; public class QuickSort { public static int ARRAY_LENGTH = 30; private static int[] array = new int[ARRAY_LENGTH]; private static Random generator = new Random(); public static void initArray() { for (int i=0; i<ARRAY_LENGTH; i++) { array[i] = generator.nextInt(100); } } public static void printArray() { for (int i=0; i<ARRAY_LENGTH-1; i++) { System.out.print(array[i] + ", "); } System.out.println(array[ARRAY_LENGTH-1]); } public static void quickSort() { int startIndex = 0; int endIndex = ARRAY_LENGTH - 1; doSort(startIndex, endIndex); } private static void doSort(int start, int end) { if (start >= end) return; int i = start, j = end; int cur = i - (i - j) / 2; while (i < j) { while (i < cur && (array[i] <= array[cur])) { i++; } while (j > cur && (array[cur] <= array[j])) { j--; } if (i < j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; if (i == cur) cur = j; else if (j == cur) cur = i; } } doSort(start, cur); doSort(cur+1, end); } public static void main(String[] args) { initArray(); printArray(); long time1; long time2; time1 = System.nanoTime(); quickSort(); printArray(); time2 = System.nanoTime(); double second = (double) (time2 - time1 / 1000000000.0); System.out.println(second); } }
Java
import java.util.ArrayList; import java.util.Collections; public class bubleSort { public static void main(String[] args) { // int[] a = new int [100]; int num = 100000; ArrayList<Integer> list = new ArrayList<Integer>(100000); for (int i=0;i<100000;i++) { list.add(i); } Collections.shuffle(list); System.out.println(list); System.out.println(list.get(0)); long time1, time2; time1 = System.nanoTime(); boolean flag = false; for(int i=0; i<num-1 && !flag; i++) { for(int j=0; j<num-i-1; j++) { if (list.get(j) > list.get(j+1)) { int tmp = list.get(j); // tmp = a[j] list.set(j,list.get(j+1)); // a[j] = a[j+1] list.set(j+1,tmp); // a[j+1] = tmp } //System.out.println(i+","+j+list); } } time2 = System.nanoTime(); double second = (double) (time2 - time1) / 1000000000.0; System.out.println(second); } }
Java
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Binar_search { public static void main(String[] args) { int num = 10; ArrayList<Integer> list = new ArrayList<Integer>(num); for(int i = 0; i < num; i++) list.add(i); Collections.shuffle(list); System.out.println(list); buble(list,num); System.out.println(list); Scanner cin = new Scanner(System.in); int p = cin.nextInt(); System.out.println(BinarySearch(list,p,0,num-1)); } public static int BinarySearch(ArrayList<Integer> list, int p, int s, int e) { int i = (s + e)/2; if (list.get(i) == p) return i; if (list.get(i) < p) return BinarySearch(list, p, i + 1, e); else return BinarySearch(list, p, s, i - 1); } public static void buble(ArrayList<Integer> list,int num) { for(int i = 0; i < num - 1; i++) { for(int j = 0; j < num - i - 1; j++) { if(list.get(j) > list.get(j + 1)) { int tmp=list.get(j); list.set(j,list.get(j + 1)); list.set(j + 1, tmp); } } } } }
Java
public class Heap { public int array[]; public int length; public void swap(int i, int j) { int tmp = array[i]; array[i]=array[j]; array[j]=tmp; } public void buildHeap() { while(length != 0) { for(int i = (length - 1)/2; i >= 0; i--) maxHeap(i); swap(0,length-1); length--; } } public void maxHeap(int parent) { int right = 2 * parent + 2; int left = 2 * parent + 1; int biggest = parent; if(right < length && array[right] > array[biggest]) biggest = right; if(left < length && array[left] > array[parent]) biggest = left; if(biggest!=parent) { swap(parent, biggest); maxHeap(biggest); } } public Heap(int length) { this.length = length; array = new int[length]; for(int i = 0; i < length; i++) array[i] = (int)(Math.random()*100); } public static void main(String[] args) { int N = 1000; double start; double stop; for(int i=0; i<10; i++) { System.out.print("Size array - " + N +" "); Heap hs = new Heap(N); start = System.nanoTime()/10000000; hs.buildHeap(); stop = System.nanoTime()/10000000; System.out.println("Time - " + (stop-start) + "mls"); N=N+1000; } } }
Java
import java.math.BigInteger; import java.util.Random; public class Karatsuba { public static BigInteger karacuba(BigInteger x, BigInteger y) { int N = Math.max(x.bitLength(), y.bitLength()); if (N <= 2000) return x.multiply(y); N = (N / 2) + (N % 2); BigInteger b = x.shiftRight(N); BigInteger a = x.subtract(b.shiftLeft(N)); BigInteger d = y.shiftRight(N); BigInteger c = y.subtract(d.shiftLeft(N)); BigInteger ac = karacuba(a, c); BigInteger bd = karacuba(b, d); BigInteger abcd = karacuba(a.add(b), c.add(d)); return ac.add(abcd.subtract(ac).subtract(bd).shiftLeft(N)).add(bd.shiftLeft(2*N)); } public static void main(String[] args) { Random random = new Random(); int N = 10; BigInteger a = new BigInteger(N, random); BigInteger b = new BigInteger(N, random); BigInteger c = karacuba(a, b); System.out.println("(karatsuba) " + a.toString() + " * " + b.toString() + " = " + c.toString()); System.out.println(); BigInteger d = a.multiply(b); System.out.println("(multiply) " + a.toString() + " * " + b.toString() + " = " + c.toString()); System.out.println(); System.out.println("Equals: " + c.equals(d)); } }
Java
package Calendar; import java.util.Scanner; public class day { public int D = 1,M = 1,Y = 1,Number_of_Mouth = 1, DoM[] = {0,31,28,31,30,31,30,31,31,30,31,30,31}, DoW = 0,Number_of_day = 0; public int Search(week day){ if(day.M == M && day.Y == Y)return (day.D-D+DoW)%7; if(day.Y == Y && day.M != M) { while(Number_of_Mouth<day.M) { Number_of_day = Number_of_day+DoM[Number_of_Mouth]; Number_of_Mouth++; } Number_of_day = Number_of_day+day.D; return (Number_of_day-D+DoW)%7; } if(day.Y != Y) { if(day.Y>Y) { int Number_of_Year = day.Y - Y; Number_of_day = 365*Number_of_Year+Number_of_Year/4; if(day.M == M) { Number_of_day = Number_of_day+day.D; return (Number_of_day-D+DoW)%7; } else if(day.M != M) { int mcount = 1; while(mcount<day.M) { Number_of_day = Number_of_day+DoM[mcount]; mcount++; } if(day.Y%4 == 0 && day.M>2 )Number_of_day = Number_of_day+1; Number_of_day = Number_of_day+day.D; return (Number_of_day-D+DoW)%7; } } } return 1; } }
Java
package Calendar; public class week { public int D; public int M; public int Y; public week(int Day, int Mounth, int Year){ this.D = Day; this.M = Mounth; this.Y = Year; } }
Java
package binary; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class bynarySearch { @SuppressWarnings("resource") public static void main(String[] args) { int num=10; ArrayList<Integer> list = new ArrayList<Integer>(num); for(int i=0;i<num;i++){ list.add(i); } Collections.shuffle(list); System.out.println(list); buble(list,num); System.out.println(list); Scanner sc = new Scanner(System.in); int p = sc.nextInt(); System.out.println(BinarySearch(list,p,0,num-1)); } public static int BinarySearch(ArrayList<Integer> list, int p, int s, int e){ int i=(s+e)/2; if (list.get(i)==p) return i; if (list.get(i)<p) return BinarySearch(list,p,i+1,e); else return BinarySearch(list, p,s,i-1); } public static void buble(ArrayList<Integer> list,int num) { for(int i=0;i<num-1;i++){ for(int j=0;j<num-i-1;j++){ if(list.get(j)>list.get(j+1)){ int tmp=list.get(j); list.set(j,list.get(j+1)); list.set(j+1, tmp); } } } } }
Java
package root; public class call_funtion { public static void main(String[] args) { Three tree = new Three(); int num = 5; for(int k = 0; k < num; k++) { int number = (int) (Math.random()*num*2-num); System.out.print(number + ","); tree.add(number); } tree.printTree(); System.out.println("Remove: " + 4 + " : " + tree.remove(4)); int search = (int) (Math.random()*num*2-num); int searchNum = tree.search(search).num; System.out.println("Search: " + search); System.out.println("Search Num: " + searchNum); System.out.println("Remove: " + searchNum + " : " + tree.remove(searchNum)); System.out.println("Remove: " + searchNum/2 + " : " + tree.remove(searchNum/2)); System.out.println("Min: " + tree.getMin()); System.out.println("Max: " + tree.getMax()); tree.printTree(); } }
Java
package root; public class Three { public class EL { int num; EL left; EL right; EL iam; EL parent; public EL(int num, EL parent) { this.num = num; this.left = null; this.right = null; this.iam = this; this.parent = parent; } } EL root; int lenght; public void BinaryTree() { root = null; lenght = 0; } public void BinaryTree(int num) { root = new EL(num, null); lenght = 1; } public EL add(int num) { lenght++; if(root == null) { root = new EL(num, null); return root; } EL EL = root; while(EL != null) if(num >= EL.num) if(EL.right == null) { EL.right = new EL(num, EL); return EL.right; } else EL = EL.right; else if(num < EL.num) if(EL.left == null) { EL.left = new EL(num, EL); return EL.left; } else EL = EL.left; lenght--; return null; } public void printTree() { System.out.println("\nLenght: " + lenght); printTree(root, 0); } private void printTree(EL EL, int level) { if(EL.right != null) printTree(EL.right, level+1); for(int k = 0; k < level; k++) System.out.print("\t"); System.out.println(EL.num); if(EL.left != null) printTree(EL.left, level+1); } public EL search(int num) { EL minEL = root; EL maxEL = root; EL EL = root; while(EL != null) if(num == EL.num) return EL; else if(num > EL.num) { if(maxEL.num < EL.num)maxEL = EL; minEL = EL; EL = EL.right; } else if(num < EL.num) { if(minEL.num > EL.num)minEL = EL; maxEL = EL; EL = EL.left; } if(maxEL.num - num <= num - minEL.num) return maxEL; else return minEL; } public EL getMax() { EL EL = root; while(EL.right != null) EL = EL.right; return EL; } public EL getMin() { EL EL = root; while(EL.left != null) EL = EL.left; return EL; } public boolean remove(int num) { return remove(num, root); } private boolean remove(int num, EL EL) { while(EL != null) { if(num < EL.num) EL = EL.left; else if(num > EL.num) EL = EL.right; else if(num == EL.num) { if(EL.left != null && EL.right != null) { if(EL.right.left == null) { EL.right.left = EL.left; if(EL == root) root = EL.right; else if(EL.parent.left == EL) EL.parent.left = EL.right; else if(EL.parent.right == EL) EL.parent.right = EL.right; lenght--; return true; } else { EL ELLeft = EL.right.left; while(ELLeft.left != null) ELLeft = ELLeft.left; EL.num = ELLeft.num; return remove(ELLeft.num, ELLeft); } } else { if(EL.left == null && EL.right == null) { if(EL == root) root = null; else if(EL.parent.left == EL) EL.parent.left = null; else if(EL.parent.right == EL) EL.parent.right = null; } else if(EL.left != null) { if(EL == root) root = EL.left; else if(EL.parent.left == EL) EL.parent.left = EL.left; else if(EL.parent.right == EL) EL.parent.right = EL.left; } else if(EL.right != null) { if(EL == root) root = EL.right; else if(EL.parent.left == EL) EL.parent.left = EL.right; else if(EL.parent.right == EL) EL.parent.right = EL.right; } lenght--; return true; } } } return false; } }
Java
package root; public class EL { int num; EL left; EL right; EL iam; EL parent; public EL(int num, EL parent) { this.num = num; this.left = null; this.right = null; this.iam = this; this.parent = parent; } }
Java
package algoritm; import java.util.ArrayList; import java.util.Collections; public class sort { public static void main(String[] args) { int num=10; ArrayList<Integer> list = new ArrayList<Integer>(num); for(int i=0;i<num;i++){ list.add(i); } Collections.shuffle(list); System.out.println(list); long start = System.nanoTime(); buble(list,num); long end = System.nanoTime(); long traceTime = end-start; System.out.println(traceTime); System.out.println(list); } public static void buble(ArrayList<Integer> list,int num) { int t=0; boolean flag = false; for(int i=0;i<num-1 && !flag;i++){ t=0; for(int j=0;j<num-i-1;j++){ if(list.get(j)>list.get(j+1)){ int tmp=list.get(j); list.set(j,list.get(j+1)); list.set(j+1, tmp); t++; } } if (t==0) flag=true;System.out.println(list); } } }
Java
package sort; public class Heap { int arr[]; public Heap() { arr = new int[11]; } private int getL(int i) { if(0 < 2*i && 2*i < arr.length) return arr[2*i]; return 0; } private int getR(int i) { if(0 < 2*i+1 && 2*i+1 < arr.length) return arr[2*i+1]; return 0; } public int getMin() { return arr[1]; } private void print(int num, int level) { if(getL(num) != 0) print(2*num, level+1); for(int i = 0; i < level; i++) System.out.print("\t"); System.out.println(arr[num]); if(getR(num) != 0) print(2*num+1, level+1); } public void insert(int num) { int i = arr.length-1; if(arr[i] != 0) makeNewArray(); else while(arr[i] == 0 && i > 0) i--; arr[++i] = num; while(arr[i/2] > arr[i]) { swap(i/2, i); i = i/2; } } private void swap(int a, int b) { int tmp = arr[a]; arr[a] = arr[b]; arr[b] = tmp; } private void makeNewArray() { int mass[] = new int[ (int) (arr.length*3/2) ]; for(int i = 0; i < arr.length; i++) mass[i] = arr[i]; arr = mass; } public int remove() { int exitNum = arr[1]; int i = arr.length-1; while(arr[i] == 0) i--; arr[1] = arr[i]; arr[i] = 0; i = 1; while(arr[i] > getL(i) && getL(i) != 0 || arr[i] > getR(i) && getR(i) != 0) if(arr[i] > getL(i) && getL(i) != 0 && getL(i) < getR(i) && getR(i) != 0) { swap(i, 2*i); i = 2*i; } else { swap(i, 2*i+1); i = 2*i+1; } return exitNum; } public static void main(String[] args) { Heap tree = new Heap(); for(int k = 0; k < 15; k++) tree.insert((int)(Math.random()*10+1)); tree.print(1,0); System.out.println(" "+"CHANGE before SORTING"+" "); tree.remove(); tree.print(1,0); } }
Java
package algoritm; public class cl { public static void main(String[] args) { int a=12345, b= 125; long start = System.nanoTime(); evklid(a,b); perebor(a,b); svou(a,b); long end = System.nanoTime(); long traceTime = end-start; System.out.println(traceTime); } public static void evklid(int a,int b){ while (a!=0 && b!=0) { if (a>b) a=a%b; else b=b%a; } System.out.println(a+b); } public static void perebor(int a,int b){ if (a!=0 && b!=0){ int k=a; while(a%k!=0 || b%k!=0){ k=k-1; } System.out.println(k); } } public static void svou(int a,int b){ if (a!=0 && b!=0){ if(a%2==0 && b%2==0){ int k=a; while(a%k!=0 || b%k!=0){ k=k-2; } System.out.println(k); } else{ int k=a; while(a%k!=0 || b%k!=0){ k=k-1; } System.out.println(k); } } } }
Java
public class Testing { public static void main(String[] args) { Map q = new Map(); q.printMap(); q.Add(new El("Name","Tom")); q.Add(new El("surname","Johnson")); System.out.println(q); q.Add(new El("Name","John")); q.Add(new El("Market_of_economic","7")); q.Add(new El("Market_of_programming","10")); q.Add(new El("Market_of_english","5")); q.Add(new El("Market_of_programming","1")); System.out.println(q); System.out.println("'Name' = "+q.Get("Name")); System.out.println("'Market_of_matematic' = "+q.Get("Market_of_matematic")); q.printMap(); q.Delete_Key("Market_of_economic"); System.out.println("\n'Market_of_economic'"); System.out.println(q); q.Delete_Value("Johnson"); System.out.println("'Johnson'"); System.out.println(q); q.Delete_KeyAndValue("Name", "John"); System.out.println("\n'Name'+'John'"); System.out.println(q); q.Delete_KeyAndValue("Name", "Tom"); System.out.println("\n'Name''Tom'"); System.out.println(q); } }
Java
public class Map { public El head = null; public void printMap() { if(head == null)System.out.println("Error: Map is empty!"); else { El cur = head; System.out.print("Key list: "); while(cur.next!=null) { System.out.print(cur.key+" "); cur = cur.next; } System.out.println(); } } public void Add(El elem) { if(head== null)head = elem; else { if(head.next == null) { if(head.key.compareTo(elem.key)<0) { head.next = elem; return; } if(head.key.compareTo(elem.key)>0) { elem.next = head; head = elem; return; } if(head.key.compareTo(elem.key)==0) { System.out.println("Error: key '"+head.key+"' already used! ('"+head.value+"','"+elem.value+"')"); return; } } if(head.key.compareTo(elem.key)<0) { elem.next = head.next; head.next = elem; return; } if(head.key.compareTo(elem.key)>0) { elem.next = head; head = elem; return; } if(head.key.compareTo(elem.key)==0) { System.out.println("Error: key '"+head.key+"' already used! ('"+head.value+"','"+elem.value+"')"); return; } El cur = head; while(cur.next!=null) { if(cur.key.compareTo(elem.key)>0 || elem.key.compareTo(cur.next.key)<0) { elem.next=cur.next; cur.next=elem; return; } cur = cur.next; } cur.next = elem; } } public String Get(String key) { if(head==null) { System.out.println("Error: Map is empty!"); return null; } else { if(head.key == key)return head.value; else { El cur = head; while(cur.next!=null) { if(cur.key == key)return cur.value; cur = cur.next; } System.out.println("Error: there isn't record with the key '"+key+"'!"); return null; } } } public void Delete_Key(String key) { if(head.key == key)head = head.next; else { El cur = head; while(cur.next!=null) { if(cur.next.key == key) { cur.next = cur.next.next; return; } cur = cur.next; } } } public void Delete_Value(String value) { Boolean flag=false; if(head == null) return; if(head.value == value) { if(head.next!=null)head = head.next; else { head = null; return; } while(head.value==value) if(head.next!=null) head = head.next; else { head = null; return; } }; El cur = head; while(cur.next!=null) { if(cur.next.value == value) { cur.next = cur.next.next; flag=true; } if(flag==false) cur = cur.next; else flag=false; } } public void Delete_KeyAndValue(String key, String value) { if(head.key == key && head.value == value)head = head.next; else { El cur = head; while(cur.next!=null) { if(cur.next.key == key && cur.next.value == value) { cur.next = cur.next.next; return; } cur = cur.next; } } } public String toString() { StringBuffer sb = new StringBuffer(); El current = head; sb.append("KEY\t"); sb.append("VALUE\n"); while (current != null) { sb.append(current.key + "\t"); sb.append(current.value + "\n"); current = current.next; } return sb.toString(); } }
Java
public class El { public El next; public String key; public String value; public El(String key, String value) { this.key = key; this.value = value; } }
Java
package factorial; public class fact { public static void main(String[] args) { int a=7; factor(a); System.out.print(factor(a)); } public static int factor(int a) { if (a<=1) return 1; else return factor(a-1)*a; } }
Java
package quick; import java.util.Random; public class qiuck { public static void main(String[] args) { int num=1000000; int[] arr = new int[num]; Random rand = new Random(); for(int i=0;i<num;i++){ arr[i]=rand.nextInt(num); } PrintArr(arr,num); long start = System.nanoTime(); QuickSort(arr,0,num-1); long end = System.nanoTime(); long traceTime = end-start; PrintArr(arr,num); System.out.print("\n"); System.out.println(traceTime); } public static void QuickSort(int arr[] ,int p,int r) { int i,j; int x; i=p; j=r; x=arr[(i+j)/2]; do{ while(arr[i]<x){ i++;} while(arr[j]>x){ j--;} if(i<=j) { int tmp=arr[j]; arr[j]=arr[i]; arr[i]=tmp; i++; j--; } } while(i<=j); if(j>p) QuickSort(arr,p,j); if(i<r) QuickSort(arr,i,r); } public static void PrintArr(int arr[],int num){ System.out.print("\n"); for(int i=0;i<num;i++){ System.out.print(arr[i]+","); } } }
Java
import java.util.ArrayList; import java.util.Collections; public class bublesort { public static void main(String[] args) { int num = 10; ArrayList<Integer> list = new ArrayList<Integer>(10); for (int i=0;i<10;i++) { list.add(i); } Collections.shuffle(list); System.out.println(list); System.out.println(list.get(0)); long time1, time2; time1 = System.nanoTime(); boolean flag = false; for(int i=0; i<num-1 && !flag; i++) { for(int j=0; j<num-i-1; j++) { if (list.get(j) > list.get(j+1)) { int tmp = list.get(j); // tmp = a[j] list.set(j,list.get(j+1)); // a[j] = a[j+1] list.set(j+1,tmp); // a[j+1] = tmp } System.out.println(i+","+j+list); } } time2 = System.nanoTime(); double second = (double) (time2-time1)/1000000000.0; System.out.println(second); } }
Java
package algorithms; public class Tree { public Element head = null; public Element min(){ Element current = head; while(current.left!=null){ current = current.left; } return current; } public Element max(){ Element current = head; while(current.right!=null){ current = current.right; } return current; } public void add(Element elem){ if(head==null){ head = elem; }else{ Element current = head; while(true){ if (current.key>elem.key){ if(current.left==null){ current.left=elem; return; }else{ current=current.left; } } if (current.key<elem.key){ if(current.right==null){ current.right=elem; return; }else{ current=current.right; } } } } } }
Java
package algorithms; public class Element { public Element right; public Element left; public int key; public String value; Element(int Key, String Value){ value = Value; key = Key; } }
Java
import java.util.Random; public class QuickSort { public static int ARRAY_LENGTH = 1000000; private static int[] array = new int[ARRAY_LENGTH]; private static Random generator = new Random(); public static void initArray() { for (int i=0; i<ARRAY_LENGTH; i++) { array[i] = generator.nextInt(100); } } public static void printArray() { for (int i=0; i<ARRAY_LENGTH-1; i++) { System.out.print(" " + array[i] + ' '); } System.out.println(array[ARRAY_LENGTH-1]); } public static void quickSort() { int startIndex = 0; int endIndex = ARRAY_LENGTH - 1; doSort(startIndex, endIndex); } private static void doSort(int start, int end) { if (start >= end) return; int i = start, j = end; int cur = i - (i - j) / 2; while (i < j) { while (i < cur && (array[i] <= array[cur])) { i++; } while (j > cur && (array[cur] <= array[j])) { j--; } if (i < j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; if (i == cur) cur = j; else if (j == cur) cur = i; } } doSort(start, cur); doSort(cur+1, end); } public static void main(String[] args) { long time1, time2; time1 = System.nanoTime(); initArray(); printArray(); quickSort(); printArray(); time2 = System.nanoTime(); double second = (double) (time2-time1)/1000000000.0; System.out.println(second); } }
Java
public class factorial { public static int fac (int n) { if (n <= 1) return 1; return n * fac(n-1); } public static void main(String[] args) { System.out.println (fac(4)); } }
Java
public class algoritm4 { static int count=0; public static int fib1 (int n) { if (n == 0) return 0; if (n == 1) return 1; count++; return fib1(n-2) + fib1(n-1); } public static void main(String[] args) { System.out.println (fib1(10)); System.out.println(count); } }
Java
package Algo; import java.io.File; public class Node { File file; Node father = null; Node son = null; Node brother = null; public Node (File name) { this.file = name; } }
Java
package Algo; import java.io.File; public class Tree { private static Node make_tree (File dir) { Node root = new Node (dir); if (dir.isDirectory()) { make_tree_iter (root); return root; } else { return root; } } private static void make_tree_iter (Node cur_node) { File list [] = cur_node.file.listFiles(); if (list.length<1) { if (list.length==0) return; cur_node.son=new Node (list[0]); if (list[0].isDirectory()) make_tree_iter (cur_node.son); } else { cur_node.son = new Node (list[0]); cur_node=cur_node.son; if (list[0].isDirectory()) make_tree_iter (cur_node.son); for (int i=1; i<list.length; i++) { cur_node.brother = new Node (list[i]); cur_node=cur_node.brother; if (list[i].isDirectory()) make_tree_iter (cur_node); } } } static int level=0; public static void print_tree (Node node) { if (node==null) return; for (int i=0; i<level; i++) System.out.print ("\t"); System.out.print (node.file.getName()); if (node.son!=null) { level ++; System.out.print ("\n"); for (int i=0; i<level; i++) System.out.print ("\t"); print_tree (node.son); } if (node.brother!=null) { System.out.print ("\n"); for (int i=0; i<level; i++) System.out.print ("\t"); print_tree (node.brother); } else { level=level-1;} } public static void main(String[] args) { File dir = new File ("d:/1"); Node root = make_tree (dir); print_tree(root); } }
Java
package bin_search; public class search { public int bin_search (int array[], int n, int x) { int first = 0; int last = n; int mid = (last - first) / 2; if (last == 0) { return 0; } else if (array[0] > x) { return 0; } else if (array[n-1] < x) { return 0; } while (first < last) { if (x < array[mid]) { last = mid; } else if (x == array [mid]) { return mid+1; } else { first = mid + 1; } mid = first + (last - first) / 2; } return 0; } }
Java
package bin_search; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Random; public class main { public static void main(String[] args) { search w = new search(); long time_start = 0; int max = 15; int x =7; int[] array = new int[max]; Random ran = new Random(); for (int i = 0; i<max; i++) { array[i]=Math.abs(ran.nextInt(20)); System.out.printf(array[i] + "\t"); } System.out.printf("\n"); int tmp = 0; for (int j = 0; j < max - 1; j++) { for (int i = 0; i < max - j - 1; i++) { if (array[i] > array[i+1]) { tmp = array[i]; array[i] = array[i+1]; array[i+1] = tmp; } } } for (int i = 0; i<max; i++) { System.out.printf(array[i] + "\t"); } time_start = System.currentTimeMillis(); System.out.printf("\nPosition is " + w.bin_search(array, max, x)); } }
Java
package bintree; public class methods { Node root = null; int depth = 0; Node addNode(int value) { Node node = root; if(root == null) { root = new Node(value, null); return root; } while(node != null) if(value <= node.value) { if(node.left == null) { node.left = new Node(value, node); return node.left; } else node = node.left; } else { if(node.right == null) { node.right = new Node(value, node); return node.right; } else node = node.right; } return null; } void printTree() { printTree(root, 0); } private void printTree(Node node, int level) { if(node.right != null) printTree(node.right, level+1); for(int k = 0; k < level; k++) System.out.print("\t"); System.out.println(node.value); if(node.left != null) printTree(node.left, level+1); } class Node { int value; Node left; Node right; Node me; Node parent; Node(int value, Node parent) { this.value = value; this.parent = parent; } } }
Java
package algorithms; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TicTacToeGUI extends JFrame { /** * */ private static final long serialVersionUID = 1L; private static final String TITLE = "Tic Tac Toe"; private static final int WIDTH = 450; private static final int HEIGHT = 600; private Container content; private JLabel result; private JButton[] cells; private JButton exitButton; private JButton initButton; private CellButtonHandler[] cellHandlers; private ExitButtonHandler exitHandler; private InitButtonHandler initHandler; private boolean noughts; private boolean gameOver; public TicTacToeGUI() { // Necessary initialization code setTitle(TITLE); setSize(WIDTH, HEIGHT); setDefaultCloseOperation(EXIT_ON_CLOSE); // Get content pane content = getContentPane(); content.setBackground(Color.blue.darker()); // Set layout content.setLayout(new GridLayout(4, 3)); // Create cells and handlers cells = new JButton[9]; cellHandlers = new CellButtonHandler[9]; for (int i = 0; i < 9; i++) { char ch = (char) ('0' + i + 1); cells[i] = new JButton("" + ch); cellHandlers[i] = new CellButtonHandler(); cells[i].addActionListener(cellHandlers[i]); } // Create init and exit buttons and handlers exitButton = new JButton("EXIT"); exitHandler = new ExitButtonHandler(); exitButton.addActionListener(exitHandler); initButton = new JButton("CLEAR"); initHandler = new InitButtonHandler(); initButton.addActionListener(initHandler); // Create result label result = new JLabel("Noughts", SwingConstants.CENTER); result.setForeground(Color.white); // Add elements to the grid content pane for (int i = 0; i < 9; i++) { content.add(cells[i]); } content.add(initButton); content.add(result); content.add(exitButton); // Initialize init(); } public void init() { // Initialize booleans noughts = true; gameOver = false; // Initialize text in buttons for (int i = 0; i < 9; i++) { char ch = (char) ('0' + i + 1); cells[i].setText("" + ch); } // Initialize result label result.setText("Noughts"); setVisible(true); } public boolean checkWinner() { if (cells[0].getText().equals(cells[1].getText()) && cells[1].getText().equals(cells[2].getText())) { return true; } else if (cells[3].getText().equals(cells[4].getText()) && cells[4].getText().equals(cells[5].getText())) { return true; } else if (cells[6].getText().equals(cells[7].getText()) && cells[7].getText().equals(cells[8].getText())) { return true; } else if (cells[0].getText().equals(cells[3].getText()) && cells[3].getText().equals(cells[6].getText())) { return true; } else if (cells[1].getText().equals(cells[4].getText()) && cells[4].getText().equals(cells[7].getText())) { return true; } else if (cells[2].getText().equals(cells[5].getText()) && cells[5].getText().equals(cells[8].getText())) { return true; } else if (cells[0].getText().equals(cells[4].getText()) && cells[4].getText().equals(cells[8].getText())) { return true; } else if (cells[2].getText().equals(cells[4].getText()) && cells[4].getText().equals(cells[6].getText())) { return true; } else { return false; } } public static void main(String[] args) { // Create TicTacToe object // TicTacToeGUI gui = new TicTacToeGUI(); } private class CellButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { // If game over, ignore if (gameOver) { return; } // Get button pressed JButton pressed = (JButton) (e.getSource()); // Get text of button String text = pressed.getText(); // If noughts or crosses, ignore if (text.equals("O") || text.equals("X")) { return; } // Add nought or cross if (noughts) { pressed.setText("O"); } else { pressed.setText("X"); } // Check winner if (checkWinner()) { // End of game gameOver = true; // Display winner message if (noughts) { result.setText("Noughts win!!"); } else { result.setText("Crosses win!"); } } else { // Change player noughts = !noughts; // Display player message if (noughts) { result.setText("Noughts"); } else { result.setText("Crosses"); } } } } private class ExitButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } private class InitButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { init(); } } }
Java
package binaryTree; import java.util.Scanner; public class BinaryTree { public class Node { int num; Node left; Node right; Node iam; Node parent; public Node(int num, Node parent) { this.num = num; this.left = null; this.right = null; this.iam = this; this.parent = parent; } } Node root; int lenght; public BinaryTree() { root = null; lenght = 0; } public BinaryTree(int num) { root = new Node(num, null); lenght = 1; } public Node insert(int num) { lenght++; if(root == null) { root = new Node(num, null); return root; } Node node = root; while(node != null) if(num >= node.num) if(node.right == null) { node.right = new Node(num, node); return node.right; } else node = node.right; else if(num < node.num) if(node.left == null) { node.left = new Node(num, node); return node.left; } else node = node.left; lenght--; return null; } public void printTree() { System.out.println("\n"); printTree(root, 0); } private void printTree(Node node, int level) { if(node.right != null) printTree(node.right, level+1); for(int k = 0; k < level; k++) System.out.print("\t"); System.out.println(node.num); if(node.left != null) printTree(node.left, level+1); } public Node search(int num) { Node minNode = root; Node maxNode = root; Node node = root; while(node != null) if(num == node.num) return node; else if(num > node.num) { if(maxNode.num < node.num) maxNode = node; minNode = node; node = node.right; } else if(num < node.num) { if(minNode.num > node.num) minNode = node; maxNode = node; node = node.left; } if(maxNode.num - num <= num - minNode.num) return maxNode; else return minNode; } public Node getMax() { Node node = root; while(node.right != null){ node = node.right; } return node; } public Node getMin() { Node node = root; while(node.left != null){ node = node.left; } return node; } public boolean remove(int num) { return remove(num, root); } private boolean remove(int num, Node node) { while(node != null) { if(num < node.num) node = node.left; else if(num > node.num) node = node.right; else if(num == node.num) { if(node.left != null && node.right != null) { if(node.right.left == null) { node.right.left = node.left; if(node == root) root = node.right; else if(node.parent.left == node) node.parent.left = node.right; else if(node.parent.right == node) node.parent.right = node.right; lenght--; return true; } else { Node nodeLeft = node.right.left; while(nodeLeft.left != null) nodeLeft = nodeLeft.left; node.num = nodeLeft.num; return remove(nodeLeft.num, nodeLeft); } } else { if(node.left == null && node.right == null) { if(node == root) root = null; else if(node.parent.left == node) node.parent.left = null; else if(node.parent.right == node) node.parent.right = null; } else if(node.left != null) { if(node == root) root = node.left; else if(node.parent.left == node) node.parent.left = node.left; else if(node.parent.right == node) node.parent.right = node.left; } else if(node.right != null) { if(node == root) root = node.right; else if(node.parent.left == node) node.parent.left = node.right; else if(node.parent.right == node) node.parent.right = node.right; } lenght--; return true; } } } return false; } public static void main(String[] args) { BinaryTree tree = new BinaryTree(); int amount = 5; //change the number of inputs for(int k = 0; k < amount; k++) //creating of tree { System.out.println("Enter the number:"); Scanner n= new Scanner (System.in); String n1 = n.next(); int number=Integer.parseInt(n1); tree.insert(number); } tree.printTree(); System.out.println("Remove: " + 4 + " : " + tree.remove(4)); int search = (int) (Math.random()*amount*2-amount); int searchNum = tree.search(search).num; System.out.println("Search Num: " + searchNum); System.out.println("Remove: " + searchNum + " : " + tree.remove(searchNum)); System.out.println("Min: " + tree.getMin().num); System.out.println("Max: " + tree.getMax().num); tree.printTree(); } }
Java
package fib; public class fib { public static void main(String[] args) { long start; start = System.nanoTime(); System.out.println(fib(7)); System.out.println("Time of running: "+(System.nanoTime()-start)+" nanosec"); start = System.nanoTime(); System.out.println(fib_rec(10)); System.out.println("Time of running: "+(System.nanoTime()-start)+" nanosec"); } public static int fib_rec(int n) { if(n <= 0) return 0; else if(n == 1) return 1; else return fib_rec(n-1) + fib_rec(n-2); } public static int fib(int n) { int a = 1, b = 1; int fib = 2, i = 2; while (i < n) { fib = a + b; a = b; b = fib; i++; } return fib; } }
Java
package searchTests; import java.util.ArrayList; public interface ISearch { public int search(ArrayList<Integer> array, int elem); }
Java
package searchTests; import java.util.ArrayList; import java.util.Random; import sortTests.QuickSort; public class SearchTestsMain { public static void main(String[] args) { int size = 10000; int tries = 200; for (int a = 0; a < tries; a++) { if (tries > 10) if (a % (tries / 10) == 0) System.out.print("."); ArrayList<Integer> array = new ArrayList<Integer>(); Random random = new Random(); for (int i = 0; i < size; i++) { array.add(random.nextInt(size*10)); } //System.out.println(array); QuickSort sort = new QuickSort(); sort.sort(array); //System.out.println(array); int toFind = array.get(random.nextInt(size)); //System.out.println(toFind); ISearch search = new BinSearch(); int index = search.search(array, toFind); //System.out.println(index); if (index != -1) if (array.get(index) != toFind) { System.out.println("FAIL"); System.out.println(array); System.out.println("To find:"+toFind); System.out.println("Found i:"+index); System.out.println("At i:"+array.get(index)); return; } } System.out.println("Done"); } }
Java
package searchTests; import java.util.ArrayList; public class BinSearch implements ISearch { @Override public int search(ArrayList<Integer> array, int elem) { return searchInner(array, elem, 0, array.size()-1); } private int searchInner(ArrayList<Integer> array, int elem, int l, int r) { if (r == l) { if (array.get(l) == elem) return l; else return -1; } int pivotIndex = (l+r)/2; int pivot = array.get(pivotIndex); if (elem == pivot) { return pivotIndex; } else { if (elem > pivot) return searchInner(array, elem, pivotIndex+1, r); else return searchInner(array, elem, l, pivotIndex-1); } } }
Java
package guiTicTacToe; import javax.swing.*; import java.awt.*; import java.awt.event.*; import botTicTacToe.*; public class TicTacToeGUI extends JFrame { /** * */ private static final long serialVersionUID = 1L; private static final String TITLE = "Tic Tac Toe"; private static final int WIDTH = 450; private static final int HEIGHT = 600; private Container content; private JLabel result; private JButton[] cells; private JButton exitButton; private JButton initButton; private CellButtonHandler[] cellHandlers; private ExitButtonHandler exitHandler; private InitButtonHandler initHandler; private GameField field; private GameBot botX; private GameBot botO; private enum gameModes { HvC, CvH, HvH, CvC } gameModes gameMode; boolean noughts; public TicTacToeGUI() { // Necessary initialization code setTitle(TITLE); setSize(WIDTH, HEIGHT); setDefaultCloseOperation(EXIT_ON_CLOSE); // Get content pane content = getContentPane(); content.setBackground(Color.blue.darker()); // Set layout content.setLayout(new GridLayout(4, 3)); // Create cells and handlers cells = new JButton[9]; cellHandlers = new CellButtonHandler[9]; for (int i = 0; i < 9; i++) { char ch = (char) ('0' + i + 1); cells[i] = new JButton("" + ch); cellHandlers[i] = new CellButtonHandler(); cells[i].addActionListener(cellHandlers[i]); } // Create init and exit buttons and handlers exitButton = new JButton("EXIT"); exitHandler = new ExitButtonHandler(); exitButton.addActionListener(exitHandler); initButton = new JButton("CLEAR"); initHandler = new InitButtonHandler(); initButton.addActionListener(initHandler); // Create result label result = new JLabel("Noughts", SwingConstants.CENTER); result.setForeground(Color.white); // Add elements to the grid content pane for (int i = 0; i < 9; i++) { content.add(cells[i]); } content.add(initButton); content.add(result); content.add(exitButton); // Initialize init(); } private void turn(int cellN) { if (field.placeMark(noughts? GameField.MARK_O : GameField.MARK_X, cellN)) { cells[cellN].setText(noughts? "O" : "X"); if (botX != null) if (botX.inited()) botX.turn(cellN); else botX.init(field, noughts? GameField.MARK_X : GameField.MARK_O); if (botO != null) if (botO.inited()) botO.turn(cellN); else botO.init(field, noughts? GameField.MARK_X : GameField.MARK_O); // Check winner if (field.isGameEnd()) { // Display winner message if (field.getWinner() != GameField.WINNER_DRAW) result.setText((noughts? "Noughts" : "Crosses") + " win!"); else result.setText("Draw!"); } else { // Change player noughts = !noughts; // Display player message result.setText(noughts? "Noughts" : "Crosses"); // Process bots if (botO != null) { if (noughts) { int botTurn = botO.getTurn(); turn(botTurn); } } if (botX != null) { if (!noughts) { int botTurn = botX.getTurn(); turn(botTurn); } } } } } public void init() { // Initialize text in buttons for (int i = 0; i < 9; i++) { cells[i].setText(""); } // Initialize result label result.setText("Noughts"); noughts = true; botX = null; botO = null; field = new GameField(); setVisible(true); String[] modes = {"Human - Computer", "Computer - Human", "Human - Human", "Computer - Computer"}; String mode = (String) JOptionPane.showInputDialog( null, "Choose game mode", "Mode selection", JOptionPane.INFORMATION_MESSAGE, null, modes, modes[0]); if (mode == null) System.exit(0); for (int i = 0; i < modes.length; i++) if (modes[i] == mode) { gameMode = gameModes.values()[i]; break; } switch (gameMode) { case HvC: botX = new GameBot(GameField.MARK_X); break; case CvH: botO = new GameBot(GameField.MARK_O); botO.init(noughts? GameField.MARK_O : GameField.MARK_X); turn(botO.getTurn()); break; case CvC: botX = new GameBot(GameField.MARK_X); botO = new GameBot(GameField.MARK_O); botO.init(noughts? GameField.MARK_O : GameField.MARK_X); turn(botO.getTurn()); break; default: } } public static void main(String[] args) { // Create TicTacToe object // TicTacToeGUI gui = new TicTacToeGUI(); } private class CellButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { if (gameMode == gameModes.CvC) return; // Get button pressed JButton pressed = (JButton) (e.getSource()); for (int i = 0; i < cells.length; i++) { if (pressed == cells[i]) { turn(i); break; } } } } private class ExitButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } private class InitButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { init(); } } }
Java
package botTicTacToe; import java.util.ArrayList; public class MainBotTicTacToe { public static void main(String[] args) { /*try { char[][] fieldChar = new char[3][3]; byte[][] fieldByte = new byte[3][3]; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); fieldChar[0] = s.toCharArray(); s = br.readLine(); fieldChar[1] = s.toCharArray(); s = br.readLine(); fieldChar[2] = s.toCharArray(); for (int i = 0; i < fieldChar.length; i++) { for (int j = 0; j < fieldChar[i].length; j++) { if (fieldChar[i][j] == ' ') fieldByte[i][j] = 0; if (fieldChar[i][j] == 'X') fieldByte[i][j] = 1; if (fieldChar[i][j] == 'O') fieldByte[i][j] = 2; } }*/ GameTree tree = new GameTree(); tree.generateMap(2); System.out.println("done"); /*byte[][] f1 = {{2, 1, 2}, {1, 2, 1}, {1, 2, 0}}; GameField field1 = new GameField(f1); System.out.println(field1.toString()); System.out.println(field1.hashCode()); byte[][] f2 = {{2, 1, 2}, {1, 2, 1}, {0, 2, 1}}; GameField field2 = new GameField(f2); System.out.println(field2.toString()); System.out.println(field2.hashCode()); System.out.println(field1.equals(field2)); System.out.println(field1 == field2);*/ /*} catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ } }
Java
package botTicTacToe; public class GameBot { private GameTree game; private int side; int nextTurn; public GameBot(int side) { this.side = side; game = null; } public void init(int nextTurn) { if (inited()) return; game = new GameTree(); game.generateMap(nextTurn); this.nextTurn = nextTurn; } public boolean inited() { return (!(game == null)); } public void init(GameField field, int nextTurn) { if (inited()) return; game = new GameTree(field); game.generateMap(nextTurn); this.nextTurn = nextTurn; } public GameField getField() { return game.getCurrentField(); } public void turn(int x, int y) { if (!inited()) return; game.turn(nextTurn, x, y); nextTurn = nextTurn == GameField.MARK_X? GameField.MARK_O : GameField.MARK_X; } public void turn(int cellN) { if (!inited()) return; game.turn(nextTurn, cellN); nextTurn = nextTurn == GameField.MARK_X? GameField.MARK_O : GameField.MARK_X; } public int getTurn() { if (!inited()) return -1; if (game.getCurrentField().isGameEnd()) return -1; int cellN = 0; float maxPriority = 0; for (int i = 0; i < GameField.CELL_NUMBER; i++) { if (game.getCurrentField().getCell(i) != GameField.MARK_NONE) continue; GameField childField = null; try { childField = game.getCurrentField().clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } childField.setMark(nextTurn, i); float priority = computePriority(childField); if (priority > maxPriority) { maxPriority = priority; cellN = i; } } return cellN; } private float computePriority(GameField field) { float minPriority = 1; // If bot wins then it will choose this position if (field.getWinner() == side) return minPriority+1; // Bot uses pessimistic strategy // It computes the best minimal priority of the cell, // so it would be the best cell in the worst-case scenario for (int i = 0; i < GameField.CELL_NUMBER; i++) { if (field.getCell(i) != GameField.MARK_NONE) continue; GameField childField = null; try { childField = field.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } childField.setMark(nextTurn == GameField.MARK_X? GameField.MARK_O : GameField.MARK_X, i); GameTree.GameNode child = game.getNode(childField); if (child == null) continue; int winsX = child.getWinsX(); int winsO = child.getWinsO(); int draws = child.getDraws(); float priority; if (side == GameField.MARK_X) priority = 1 - winsO / (float)(winsX + winsO + draws); else priority = 1 - winsX / (float)(winsX + winsO + draws); if (priority < minPriority) minPriority = priority; } return minPriority; } }
Java
package botTicTacToe; /** * This class stores information about state of the game */ public class GameField implements Cloneable { public static final int MARK_NONE = 0; public static final int MARK_X = 1; public static final int MARK_O = 2; public static final int WINNER_NONE = 0; public static final int WINNER_X = 1; public static final int WINNER_O = 2; public static final int WINNER_DRAW = WINNER_X + WINNER_O; public static final int CELL_NUMBER = 9; public static final int CELL_NUMBER_X = 3; public static final int CELL_NUMBER_Y = 3; /** * This byte string contains positions of marks <br> * Every space is represented by two bits: <br> * GameField.MARK_NONE - no mark <br> * GameField.MARK_X - X <br> * GameField.MARK_O - O <br> * Grid is accessed in following order: <br> * 0 1 2 <br> * 3 4 5 <br> * 6 7 8 */ private FieldString field; //If both variables set then the game ended with draw //If none set then the game is not over yet private boolean winX; private boolean winO; public GameField() { field = new FieldString(); winX = false; winO = false; } /** * Creates object using array of positions as input * @param field - array 3x3 in following format: <br> * GameField.MARK_NONE - no mark <br> * GameField.MARK_X - X <br> * GameField.MARK_O - O */ public GameField(byte[][] field) { this.field = new FieldString(); for (byte y = 0; y < field.length; y++) { byte[] row = field[y]; for (byte x = 0; x < row.length; x++) { this.field.set(y*CELL_NUMBER_X+x, row[x]); } } checkWinner(); } /** * @return GameField.WINNER_NONE - Game has not ended yet <br> * GameField.WINNER_X - X wins <br> * GameField.WINNER_O - O wins <br> * GameField.WINNER_DRAW - Draw */ public byte getWinner() { byte winner = WINNER_NONE; if (winX) winner += WINNER_X; if (winO) winner += WINNER_O; return winner; } /** * Attempts to place mark in specified coordinates * this function checks if game is not over and target cell is empty * @param mark format: <br> * GameField.MARK_NONE - no mark <br> * GameField.MARK_X - X <br> * GameField.MARK_O - O * @param x - horizontal coord (0..2) * @param y - vertical coord (0..2) * @return true if mark was placed successfully, false otherwise */ public boolean placeMark(int mark, int x, int y) { if (field.get(y*CELL_NUMBER_X+x) != 0) return false; if (isGameEnd()) return false; setMark(mark, x, y); return true; } /** * Attempts to place mark in cell with specified number * this function checks if game is not over and target cell is empty * @param mark format: <br> * GameField.MARK_NONE - no mark <br> * GameField.MARK_X - X <br> * GameField.MARK_O - O * @param cellN - number of cell on the grid: <br> * 0 1 2 <br> * 3 4 5 <br> * 6 7 8 <br> * @return true if mark was placed successfully, false otherwise */ public boolean placeMark(int mark, int cellN) { if (field.get(cellN) != MARK_NONE) return false; if (getWinner() != WINNER_NONE) return false; setMark(mark, cellN); return true; } /** * Sets mark in specified coordinates * @param mark format: <br> * GameField.MARK_NONE - no mark <br> * GameField.MARK_X - X <br> * GameField.MARK_O - O * @param x - horizontal coord (0..2) * @param y - vertical coord (0..2) */ public void setMark(int mark, int x, int y) { this.field.set(y*CELL_NUMBER_X+x, mark); checkWinner(); } /** * Sets mark in cell with specified number * @param mark format: <br> * GameField.MARK_NONE - no mark <br> * GameField.MARK_X - X <br> * GameField.MARK_O - O * @param cellN - number of cell on the grid: <br> * 0 1 2 <br> * 3 4 5 <br> * 6 7 8 <br> */ public void setMark(int mark, int cellN) { this.field.set(cellN, mark); checkWinner(); } /** * @return numbers of empty cells */ public int[] getEmptyCells() { int cardinality = field.cardinality(); if (cardinality == CELL_NUMBER) return null; int[] cells = new int[CELL_NUMBER - cardinality]; int j = 0; for (int i = 0; i < CELL_NUMBER; i++) { if (field.get(i) == MARK_NONE) cells[j++] = i; if (j == cells.length) break; } return cells; } /** * Returns mark in cell * @param x - horizontal coord (0..2) * @param y - vertical coord (0..2) * @return GameField.MARK_NONE - no mark <br> * GameField.MARK_X - X <br> * GameField.MARK_O - O */ public byte getCell(int x, int y) { return field.get(y*CELL_NUMBER_X+x); } /** * Returns mark in cell * @param cellN - number of cell on the grid: <br> * 0 1 2 <br> * 3 4 5 <br> * 6 7 8 <br> * @return GameField.MARK_NONE - no mark <br> * GameField.MARK_X - X <br> * GameField.MARK_O - O */ public byte getCell(int cellN) { return field.get(cellN); } /** * @return array 3x3 in following format: <br> * GameField.MARK_NONE - no mark <br> * GameField.MARK_X - X <br> * GameField.MARK_O - O */ public byte[][] getCellArray() { byte[][] fieldArray = new byte[CELL_NUMBER_Y][CELL_NUMBER_X]; for (byte y = 0; y < CELL_NUMBER_Y; y++) { for (byte x = 0; x < CELL_NUMBER_X; x++) { fieldArray[y][x] = getCell(x, y); } } return fieldArray; } public GameField clone() throws CloneNotSupportedException { GameField newField = (GameField)super.clone(); newField.field = field.clone(); return newField; } /** * This method checks field and sets winner */ private void checkWinner() { //Clear last two bits winO = false; winX = false; //There are total of 8 winning positions: byte[][] conditions = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6}}; //Check if we have enough turns first boolean enoughTurns = false; for (int i = 0; i < conditions.length; i++) if (field.cardinality() > conditions[i].length) { enoughTurns = true; break; } if (!enoughTurns) return; //Checking for X's winning positions for (byte[] condition: conditions) { boolean win = true; for (byte index: condition) { if (field.get(index) != MARK_X) { win = false; break; } } if (win) { winX = true; return; } } //Checking for O's winning positions for (byte[] condition: conditions) { boolean win = true; for (byte index: condition) { if (field.get(index) != MARK_O) { win = false; break; } } if (win) { winO = true; return; } } //Now check if field is full - the condition for draw if (field.cardinality() == CELL_NUMBER) { winO = true; winX = true; return; } } public boolean isGameEnd() { return (winO || winX); } public String toString() { String string = "["; for (int i = 0; i < CELL_NUMBER; i++) { if (i % CELL_NUMBER_X == 0) string += "\r\n"; switch(field.get(i)) { case MARK_NONE: string += '-'; break; case MARK_X: string += 'X'; break; case MARK_O: string += 'O'; break; } } string += "\r\n]"; return string; } @Override public boolean equals(Object arg0) { if (arg0.getClass() != GameField.class) return false; return field.toSmallest().equals(((GameField)arg0).field.toSmallest()); } /** * Produces hash code that is equal for every field that equals this. <br> * (i. e. can be rotated and/or mirrored to become identical) */ public int hashCode() { int hash = field.toSmallest().hashCode(); return hash; } private class FieldString implements Cloneable{ public FieldString() { bitString = new byte[3]; } public int cardinality() { int cardinality = 0; for (byte b: bitString) { cardinality += Integer.bitCount(b); } return cardinality; } public FieldString clone() throws CloneNotSupportedException { FieldString newField = (FieldString)super.clone(); newField.bitString = (byte[]) this.bitString.clone(); return newField; } public String toString() { return "[" + bitString[0] + ", " + bitString[1] + ", " + bitString[2] + "]"; } /** * @return Similar field string with minimal hash code. <br> * (i. e. can be rotated and/or mirrored to become identical) */ public FieldString toSmallest() { FieldString smallest = this; for (int i = 0; i < 4; i++) { FieldString str = this.rotateFieldRight(i); if (str.hashCode() < smallest.hashCode()) smallest = str; str = str.mirror(); if (str.hashCode() < smallest.hashCode()) smallest = str; } return smallest; } public FieldString rotateFieldRight(int n) { n %= 4; if (n == 0) try { return this.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } FieldString resultString = new FieldString(); /* Field with following indexes: * 0 1 2 * 3 4 5 * 6 7 8 * Rotates like that: * 1: * 6 3 0 * 7 4 1 * 8 5 2 * 2: * 8 7 6 * 5 4 3 * 2 1 0 * 3: * 2 5 8 * 1 4 7 * 0 3 6 */ int[][] rotateMaps = { {6, 3, 0, 7, 4, 1, 8, 5, 2}, {8, 7, 6, 5, 4, 3, 2, 1, 0}, {2, 5, 8, 1, 4, 7, 0, 3, 6} }; int[] rotateMap = rotateMaps[n - 1]; for(int i = 0; i < 9; i++) { resultString.set(rotateMap[i], get(i)); } return resultString; } /** * Mirrors the field * @return Mirrored cells from: <br> * 0 1 2 <br> * 3 4 5 <br> * 6 7 8 <br> * To: <br> * 2 1 0 <br> * 5 4 3 <br> * 8 7 6 */ public FieldString mirror() { FieldString resultString = new FieldString(); int[] cellMirrorMapping = {2, 1, 0, 5, 4, 3, 8, 7, 6}; for (int i = 0; i < 9; i++) resultString.set(cellMirrorMapping[i], get(i)); return resultString; } private byte get(int i) { int offset = i % 3; int index = (i - offset) / 3; offset *= 2; byte scope = (byte) (0b11 << offset); byte mark = (byte) ((bitString[index] & scope) >> offset); return mark; } private void set(int i, int mark) { int offset = i % 3; int index = (i - offset) / 3; offset *= 2; byte m = (byte) (mark & 0b11); bitString[index] &= ~(0b11 << offset); bitString[index] |= m << offset; } public boolean equals(FieldString string) { for(int i = 0; i < bitString.length; i++) if (bitString[i] != string.bitString[i]) return false; return true; } public int hashCode() { int hashCode = bitString[0] + (bitString[1] << 8) + (bitString[2] << 16); return hashCode; } private byte[] bitString; } }
Java
package botTicTacToe; import java.util.HashMap; /** Not actually a tree, but provides tree-like interface * * @author NP * */ public class GameTree { private GameField currentField; private HashMap<GameField, GameNode> nodeMap; public GameTree() { currentField = new GameField(); nodeMap = new HashMap<GameField, GameNode>(); } public GameTree(GameField field) { currentField = field; nodeMap = new HashMap<GameField, GameNode>(); } public void turn(int mark, int x, int y) { currentField.placeMark(mark, x, y); } public void turn(int mark, int cellN) { currentField.placeMark(mark, cellN); } public GameNode getCurrentNode() { return getNode(currentField); } public GameNode getNode(GameField field) { return nodeMap.get(field); } public GameField getCurrentField() { return currentField; } public void generateMap(int nextTurn) { generateMap(currentField, nextTurn); } private void generateMap(GameField currentField, int nextTurn) { GameNode node = new GameNode(); if (currentField.isGameEnd()) { switch (currentField.getWinner()) { case 1: node.setWinsX(1); break; case 2: node.setWinsO(1); break; case 3: node.setDraws(1); break; } nodeMap.put(currentField, node); return; } int[] emptyCells = currentField.getEmptyCells(); for (int cell: emptyCells) { GameField field = null; try { field = currentField.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } field.setMark(nextTurn, cell); if (!nodeMap.containsKey(field)) generateMap(field, nextTurn == 1? 2 : 1); GameNode fieldNode = nodeMap.get(field); node.setWinsX(node.getWinsX() + fieldNode.getWinsX()); node.setWinsO(node.getWinsO() + fieldNode.getWinsO()); node.setDraws(node.getDraws() + fieldNode.getDraws()); } nodeMap.put(currentField, node); } public static class GameNode { private int winsX; private int winsO; private int draws; public GameNode() { winsX = 0; winsO = 0; draws = 0; } /** * @return the winsX */ public int getWinsX() { return winsX; } /** * @return the winsO */ public int getWinsO() { return winsO; } /** * @return the draws */ public int getDraws() { return draws; } public void setWinsX(int winsX) { this.winsX = winsX; } public void setWinsO(int winsO) { this.winsO = winsO; } public void setDraws(int draws) { this.draws = draws; } } }
Java
package myHashMap; public class MyHashMapMain { public static void main(String[] args) { System.out.println("Collision testing:"); MyHashMap<String, String> mapStrings = new MyHashMap<String, String>(); String one = "aaaba"; System.out.println("\"" + one + "\" hash: " + one.hashCode()); String two = "aaacB"; System.out.println("\"" + two + "\" hash: " + two.hashCode()); String three = "3"; System.out.println("\"" + three + "\" hash: " + three.hashCode()); mapStrings.put(one, "one"); mapStrings.put(two, "two"); mapStrings.put(three, "three"); System.out.println(mapStrings.get(one)); System.out.println(mapStrings.get(two)); System.out.println(mapStrings.get(three)); System.out.println(mapStrings.getKeys()); System.out.println(mapStrings.getValues()); System.out.println("Resize testing:"); int initialCapacity = 16; int elemAmount = 2048; System.out.println("Initial capacity: " + initialCapacity); System.out.println("Elements amount: " + elemAmount); MyHashMap<Integer, Integer> mapIntegers = new MyHashMap<Integer, Integer>(initialCapacity); for (int i = 0; i < elemAmount; i++) { mapIntegers.put(i, i*2); } for (int i = 0; i < elemAmount; i++) { if (mapIntegers.get(i) != i*2) { System.out.println("Test failed!"); } } System.out.println("Test finished"); } }
Java
package myHashMap; import java.util.ArrayList; import java.util.List; public class MyHashMap<K, V> { private static final float DEFAULT_LOAD_FACTOR = 0.75f; private static final int DEFAULT_CAPACITY = 128; private static final int MAX_CAPACITY = Integer.MAX_VALUE; public MyHashMap(int capacity, float loadFactor) { entries = new Entry[capacity]; this.loadFactor = loadFactor; threshold = (int) (loadFactor*capacity); size = 0; } public MyHashMap(int capacity) { this(capacity, DEFAULT_LOAD_FACTOR); } public MyHashMap() { this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR); } public void put(K key, V value) { size++; if (size > threshold) { resize(entries.length*2); } int hash = hash(key.hashCode()); int index = index(hash, entries.length); Entry<K, V> entry = entries[index]; if (entry == null) { entry = new Entry<K, V>(); entry.key = key; entry.value = value; entries[index] = entry; } else { Entry<K, V> newEntry = new Entry<K, V>(); newEntry.key = key; newEntry.value = value; newEntry.next = entry; entries[index] = newEntry; } } V get(K key) { int hash = hash(key.hashCode()); int index = index(hash, entries.length); Entry<K, V> entry = entries[index]; if (entry == null) return null; if (entry.key.equals(key)) { return entry.value; } else { do { entry = entry.next; if (entry.key.equals(key)) { return entry.value; } } while (entry != null); return null; } } void remove(K key) { if (!iskey(key)) return; int hash = hash(key.hashCode()); int index = index(hash, entries.length); Entry<K, V> entry = entries[index]; if (entry.key.equals(key)) { entries[index] = entry.next; size--; return; } else { do { Entry<K, V> prevEntry = entry; entry = entry.next; if (entry.key.equals(key)) { prevEntry.next = entry.next; size--; return; } } while (entry != null); } } List<K> getKeys() { ArrayList<K> keys = new ArrayList<K>(); for (Entry<K, V> entry: entries) { while (entry != null){ keys.add(entry.key); entry = entry.next; } } return keys; } List<V> getValues() { ArrayList<V> values = new ArrayList<V>(); for (Entry<K, V> entry: entries) { while (entry != null){ values.add(entry.value); entry = entry.next; } } return values; } void change(K key, V value) { if (!iskey(key)) { put(key, value); return; } else { int hash = hash(key.hashCode()); int index = index(hash, entries.length); Entry<K, V> entry = entries[index]; if (entry.key.equals(key)) { entry.value = value; return; } else { do { entry = entry.next; if (entry.key.equals(key)) { entry.value = value; return; } } while (entry != null); } } } boolean iskey(K key) { return (!(get(key) == null)); } int size() { return size; } private int hash(int key) { return key; } private int index(int hash, int length) { return hash & (length - 1); } private void resize(int newCapacity) { if (entries.length == MAX_CAPACITY) { threshold = Integer.MAX_VALUE; return; } Entry<K,V>[] newTable = new Entry[newCapacity]; transfer(newTable); entries = newTable; threshold = (int) (newCapacity*loadFactor); } private void transfer(Entry<K,V>[] newTable) { for (Entry<K, V> entry: entries) { if (entry != null){ int hash = hash(entry.key.hashCode()); int index = index(hash, newTable.length); newTable[index] = entry; } } } private class Entry<K, V> { public K key; public V value; public Entry<K, V> next; public int hashCode() { return (key==null ? 0 : key.hashCode()) ^ (value==null ? 0 : value.hashCode()); } } private Entry<K, V>[] entries; private int size; private float loadFactor; private int threshold; }
Java
package stack; public class StackMain { public static void main(String[] args) { Stack<Integer> stack = new Stack<Integer>(); stack.push(1); stack.push(2); stack.push(3); System.out.println(stack.pop()); System.out.println(stack.pop()); System.out.println(stack.pop()); } }
Java
package stack; import java.util.ArrayList; public class Stack<T> { private ArrayList<T> arr; int stackPtr; Stack() { arr = new ArrayList<T>(); stackPtr = -1; } void push(T elem) { stackPtr++; if (arr.size() <= stackPtr) { arr.add(elem); } else { arr.set(stackPtr, elem); } } T pop() { T elem = arr.get(stackPtr); stackPtr--; return elem; } }
Java
package fibTests; import java.util.ArrayList; public class FibRecDynamic implements IFib { private int iterations; public FibRecDynamic() { results = new ArrayList<Long>(); iterations = 0; } @Override public int getLastIterationsCounter() { return iterations; } private ArrayList<Long> results; @Override public long fib(int n) { if (n < 0) return 0; results.clear(); results.ensureCapacity(n); results.add((long)0); results.add((long)1); results.add((long)1); iterations = 1; if (results.size() > n) return results.get(n); return fibInner(n-1)+fibInner(n-2); } private long fibInner(int n) { iterations++; if (results.size() > n) return results.get(n); results.add(fibInner(n-1)+fibInner(n-2)); return results.get(n); } }
Java
package fibTests; public class FibCycle implements IFib { private int iterations; public FibCycle() { iterations = 0; } @Override public int getLastIterationsCounter() { return iterations; } @Override public long fib(int n) { if (n <= 0) return 0; long current = 1; long previous = 1; iterations = 0; for (int i = 3; i <= n; i++) { iterations++; long t = current; current = current + previous; previous = t; } return current; } }
Java
package fibTests; public class FibRecNaive implements IFib { private int iterations; public FibRecNaive() { iterations = 0; } @Override public int getLastIterationsCounter() { return iterations; } @Override public long fib(int n) { if (n <= 0) return 0; iterations = 1; if (n <= 2) return 1; return fibInner(n-1)+fibInner(n-2); } private long fibInner(int n) { iterations++; if (n <= 2) return 1; return fibInner(n-1)+fibInner(n-2); } }
Java
package fibTests; public interface IFib { public int getLastIterationsCounter(); public long fib(int n); }
Java
package fibTests; public class Main { public static void main(String[] args) { System.out.println("n rec cycle dynamic matrix"); for (int n = 10; n <= 40; n++) { System.out.print(n+" "); IFib fib = new FibRecNaive(); fib.fib(n); int iter = fib.getLastIterationsCounter(); System.out.print(iter+" "); fib = new FibCycle(); fib.fib(n); iter = fib.getLastIterationsCounter(); System.out.print(iter+" "); fib = new FibRecDynamic(); fib.fib(n); iter = fib.getLastIterationsCounter(); System.out.print(iter+" "); fib = new FibMatrix(); fib.fib(n); iter = fib.getLastIterationsCounter(); System.out.println(iter); } } }
Java
package fibTests; public class FibMatrix implements IFib { private int iterations; public FibMatrix() { iterations = 0; } @Override public int getLastIterationsCounter() { return iterations; } @Override //Taken from //ru.wikibooks.org public long fib(int n) { iterations = 0; int a = 1, ta, b = 1, tb, c = 1, rc = 0, tc, d = 0, rd = 1; while (n != 0) { iterations++; if ((n & 1) != 0) { tc = rc; rc = rc*a + rd*c; rd = tc*b + rd*d; } ta = a; tb = b; tc = c; a = a*a + b*c; b = ta*b + b*d; c = c*ta + d*c; d = tc*tb+ d*d; n >>= 1; } return rc; } }
Java
package sortTests; import java.util.List; public class BubbleSortNaive implements ISorter { @Override public void sort(List<Integer> array) { for (int i = 0; i < array.size(); i++) { for (int j = i; j < array.size(); j++) { if (array.get(i) > array.get(j)) { int t = array.get(j); array.set(j, array.get(i)); array.set(i, t); } } } } }
Java
package sortTests; import java.util.List; import java.util.Random; public class QuickSort implements ISorter { @Override public void sort(List<Integer> array) { if (array.size() <= 1) return; Random random = new Random(); int pivotIndex = random.nextInt(array.size()-1); int pivot = array.get(pivotIndex); int i = 0; int j = array.size() - 1; do { while (array.get(i) < pivot) i++; while (array.get(j) > pivot) j--; if (array.get(i) >= array.get(j)) { if (i <= j) { int t = array.get(i); array.set(i, array.get(j)); array.set(j, t); i++; j--; } } } while (i <= j); sort(array.subList(0, i)); sort(array.subList(i, array.size())); } }
Java
package sortTests; import java.util.List; public class HeapSort implements ISorter { @Override public void sort(List<Integer> array) { if (array.size() <= 1) return; buildHeap(array); for (int i = 1; i < array.size(); i++) { int last = array.size()-i; int t = array.get(0); array.set(0, array.get(last)); array.set(last, t); heapify(array.subList(0, last), 0); } } private static void buildHeap(List<Integer> array) { for (int i = array.size()/2; i >=0; i--) { heapify(array, i); } } private static void heapify(List<Integer> array, int index) { if (index > array.size()) return; int left = 2*index+1; int right = 2*index+2; int largest = index; if (left < array.size()) if (array.get(left) > array.get(largest)) largest = left; if (right < array.size()) if (array.get(right) > array.get(largest)) largest = right; if (largest != index) { int t = array.get(index); array.set(index, array.get(largest)); array.set(largest, t); heapify(array, largest); } } }
Java
package sortTests; import java.util.List; public interface ISorter { public void sort(List<Integer> array); }
Java
package sortTests; import java.util.List; public class BubbleSort implements ISorter { @Override public void sort(List<Integer> array) { for (int i = 0; i < array.size()-1; i++) { boolean swapMade = false; for (int j = i; j < array.size(); j++) { if (array.get(i) > array.get(j)) { int t = array.get(j); array.set(j, array.get(i)); array.set(i, t); swapMade = true; } } if (!swapMade) return; } } }
Java
package sortTests; import java.util.ArrayList; import java.util.List; public class MergeSort implements ISorter { @Override public void sort(List<Integer> array) { if (array.size() <= 1) return; sort(array.subList(0, array.size()/2)); sort(array.subList(array.size()/2, array.size())); ArrayList<Integer> buffer = new ArrayList<Integer>(); int i = 0; int j = array.size()/2; while ((i < array.size()/2)&&(j < array.size())) { if (array.get(i) < array.get(j)) { buffer.add(array.get(i)); i++; } else { buffer.add(array.get(j)); j++; } } if (i < array.size()/2) { buffer.addAll(array.subList(i, array.size()/2)); } if (j < array.size()) { buffer.addAll(array.subList(j, array.size())); } for (int k = 0; k < array.size(); k++) { array.set(k, buffer.get(k)); } } }
Java
package sortTests; import java.util.ArrayList; import java.util.Collections; public class MainSortTests { public static void main(String[] args) { /*BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter array:"); String arrayString = br.readLine(); Scanner scanner = new Scanner(arrayString); ArrayList<Integer> array = new ArrayList<Integer>(); while(scanner.hasNextInt()) { array.add(scanner.nextInt()); } scanner.close(); */ int stepSize = 10; int stepAmount = 5; System.out.println("n bubble heap merge quick"); int size = 1; for (int i = 0; i < stepAmount; i++) { size *= stepSize; System.out.print(size+" "); BubbleSort bubble = new BubbleSort(); System.out.print(measureSortTime(bubble, size)+" "); HeapSort heap = new HeapSort(); System.out.print(measureSortTime(heap, size)+" "); MergeSort merge = new MergeSort(); System.out.print(measureSortTime(merge, size)+" "); QuickSort quick = new QuickSort(); System.out.println(measureSortTime(quick, size)); } } private static long measureSortTime(ISorter sorter, int size) { ArrayList<Integer> array = new ArrayList<Integer>(); for (int i = 0; i < size; i++) array.add(i); Collections.shuffle(array); long start = System.nanoTime(); sorter.sort(array); long runTime = System.nanoTime() - start; return runTime; } }
Java
package dataTypeTests; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public class ArrayListTester<T extends Comparable<? super T>> implements DataTypeTester<T> { ArrayList<T> array; ArrayListTester(List<T> list) { array = new ArrayList<T>(list); } @Override public long measureBinSearch(int iterations) { long avgTime = 0; Collections.sort(array); for (int i = 0; i < iterations; i++) { Random random = new Random(); int index = random.nextInt(array.size()-1); T elem = array.get(index); long estTime = System.nanoTime(); binSearch(elem, 0, array.size()-1); estTime = System.nanoTime() - estTime; avgTime += estTime; } avgTime /= iterations; return avgTime; } private int binSearch(T elem, int l, int r) { if (r == l) { int compare = array.get(l).compareTo(elem); if (compare == 0) return l; else return -1; } int pivotIndex = (l+r)/2; T pivot = array.get(pivotIndex); int compare = pivot.compareTo(elem); if (compare == 0) { return pivotIndex; } else { if (compare < 0) return binSearch(elem, pivotIndex+1, r); else return binSearch(elem, l, pivotIndex-1); } } @Override public long measureBubbleSort(int iterations) { // TODO Auto-generated method stub return 0; } }
Java
package dataTypeTests; import java.util.Collections; import java.util.List; import java.util.Random; public class OneWayListTester<T extends Comparable<? super T>> implements DataTypeTester<T> { List<T> list; OneWayListTester(List<T> list) { this.list = list; } @Override public long measureBinSearch(int iterations) { long avgTime = 0; Collections.sort(list); for (int i = 0; i < iterations; i++) { OneWayList<T> oneWayList = new OneWayList<T>(list); Random random = new Random(); int index = random.nextInt(list.size()-1); T elem = oneWayList.getData(index); int listSize = list.size(); long estTime = System.nanoTime(); binSearch(oneWayList, elem, 0, listSize-1); estTime = System.nanoTime() - estTime; avgTime += estTime; } avgTime /= iterations; return avgTime; } private int binSearch(OneWayList<T> oneWayList, T elem, int l, int r) { if (l == r) { if (oneWayList.getData(l).compareTo(elem) == 0) return l; } int middle = (r + l) / 2; T middleData = oneWayList.getData(middle); int compare = middleData.compareTo(elem); if (compare == 0) return middle; if (compare < 0) return binSearch(oneWayList, elem, middle+1, r); else return binSearch(oneWayList, elem, l, middle-1); } @Override public long measureBubbleSort(int iterations) { // TODO Auto-generated method stub return 0; } }
Java
package dataTypeTests; import java.util.Collection; import java.util.Iterator; public class OneWayList<T>{ private T data; private OneWayList<T> next; OneWayList(T data) { this.data = data; next = null; } OneWayList(T[] data) { this.data = data[0]; next = null; OneWayList<T> last = this; for (int i = 1; i < data.length; i++) { last.add(data[i]); last = last.getNext(); } } OneWayList(Collection<T> data) { next = null; OneWayList<T> last = this; Iterator<T> dataIterator = data.iterator(); this.data = dataIterator.next(); while(dataIterator.hasNext()) { last.add(dataIterator.next()); last = last.getNext(); } } OneWayList() { data = null; next = null; } public T getData() {return data;} public T getData(int index) { OneWayList<T> nextElem = this; int i = index; while ((nextElem.getNext() != null)&&(i > 0)) { nextElem = nextElem.getNext(); --i; } if (i > 0) throw new IndexOutOfBoundsException("Index: "+index+", Size: "+(index-i+1)); return nextElem.getData(); } public void setData(T data) {this.data = data;} public OneWayList<T> getNext() {return next;} public OneWayList<T> getElem(int index) { OneWayList<T> nextElem = this; int i = index; while ((nextElem.getNext() != null)&&(i > 0)) { nextElem = nextElem.getNext(); --i; } if (i > 0) throw new IndexOutOfBoundsException("Index: "+index+", Size: "+(index-i+1)); return nextElem; } public void insert(OneWayList<T> list) { if (next == null) next = list; else { OneWayList<T> nextElem = this.next; this.next = list; while (list.getNext() != null) { list = list.getNext(); } list.insert(nextElem); } } public void insert(T data) { OneWayList<T> nextElem = this.next; this.next = new OneWayList<T>(data); this.next.insert(nextElem); } public void insert(int pos, T data) { OneWayList<T> nextElem = this; int size = 1; if (pos < 0) throw new IndexOutOfBoundsException("Index: "+pos); while ((nextElem.getNext() != null) && (pos > 1)) { nextElem = nextElem.getNext(); --pos; ++size; } if (pos > 1) throw new IndexOutOfBoundsException("Index: "+(pos+size-1)+", Size: "+size); nextElem.insert(data); } public void add(T data) { OneWayList<T> nextElem = this.next; if (nextElem == null) { this.insert(data); return; } while (nextElem.getNext() != null) { nextElem = nextElem.getNext(); } nextElem.insert(data); } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append('[' + this.data.toString()); OneWayList<T> list = this.next; while (list != null) { buffer.append(", " + list.data.toString()); list = list.getNext(); } buffer.append(']'); return buffer.toString(); } }
Java
package dataTypeTests; public interface DataTypeTester<T> { public long measureBinSearch(int iterations); public long measureBubbleSort(int iterations); }
Java
package dataTypeTests; import java.util.ArrayList; import java.util.Random; public class DataTypeTestMain { public static void main(String[] args) { ArrayList<Integer> arr = new ArrayList<Integer>(); int size = 100; Random random = new Random(); for (int i = 0; i < size; i++) { arr.add(random.nextInt(size*10)); } DataTypeTester<Integer> tester; tester = new OneWayListTester<Integer>(arr); System.out.println(tester.measureBinSearch(1000)); tester = new ArrayListTester<Integer>(arr); System.out.println(tester.measureBinSearch(1000)); } }
Java
package gcd; import java.util.Random; public class Main { public static void main(String[] args) { long bruteTimeAvg = 0; long bruteTimeMax = 0; long euclidianTimeAvg = 0; long euclidianTimeMax = 0; int tries = 100000; int maxN = 10000000; Random random = new Random(); System.out.println("Start"); long cycleStart = System.nanoTime(); for (int i = 0; i < tries; i++) { if (tries > 100) if (i % (tries / 100) == 0) System.out.print("."); int a = random.nextInt(maxN)+1; int b = random.nextInt(maxN)+1; long start = System.nanoTime(); BruteGCD.find(a, b); long end = System.nanoTime(); long runTime = end - start; if (bruteTimeMax < runTime) bruteTimeMax = runTime; bruteTimeAvg += runTime; } long cycleTime = System.nanoTime() - cycleStart; System.out.println(); System.out.println("Brute cycle time: "+cycleTime); bruteTimeAvg /= tries; System.out.println("Brute force average time: "+bruteTimeAvg); System.out.println("Brute force max time: "+bruteTimeMax); cycleStart = System.nanoTime(); for (int i = 0; i < tries; i++) { if (i % (tries / 100) == 0) System.out.print("."); int a = random.nextInt(maxN)+1; int b = random.nextInt(maxN)+1; long start = System.nanoTime(); EuclidianGCD.find(a, b); long end = System.nanoTime(); long runTime = end - start; if (euclidianTimeMax < runTime) euclidianTimeMax = runTime; euclidianTimeAvg += runTime; } cycleTime = System.nanoTime() - cycleStart; System.out.println(); System.out.println("Euclidian cycle time: "+cycleTime); euclidianTimeAvg /= tries; System.out.println("Euclidian algorithm average time: "+euclidianTimeAvg); System.out.println("Euclidian algorithm max time: "+euclidianTimeMax); } }
Java
package gcd; /** * Finds Greatest Common Divisor using Euclidian algorithm * @author NP * */ public class EuclidianGCD { public static int find(int a, int b) { if ((a == 0)||(b == 0)) return -1; int t; if (a < b) { t = b; b = a; a = t; } while (b != 0) { t = a % b; a = b; b = t; } return a; } }
Java
package gcd; /** * Finds Greatest Common Divisor using brute force search * @author NP * */ public class BruteGCD { public static int find(int a, int b) { if ((a == 0)||(b == 0)) return -1; if (a == b) return a; if (a < b) { int t = b; b = a; a = t; } if (a % b == 0) return b; for (int i = b/2; i > 1; i--) { if ((a % i == 0)&&(b % i ==0)) return i; } return 1; } }
Java
package evklid; public class HeapSort { private int[] arr; private int length; public void buildHeap() { while(length!=0) { for(int i = (length - 1)/2; i>=0; i--) { maxHeap(i); } exchange(0,length-1); length--; } } private void maxHeap(int parent) { int left=2*parent+1; int right=2*parent+2; int largest=parent; if (left< length && arr[left]>arr[parent]) { largest=left; } if (right< length && arr[right]>arr[largest]) { largest=right; } if (largest!=parent) { exchange(parent, largest); maxHeap(largest); } } private void exchange(int i, int j) { int tmp=arr[i]; arr[i]=arr[j]; arr[j]=tmp; } public HeapSort(int length) { this.length = length; arr = new int[length]; for(int i=0; i<length; i++) { arr[i] = (int)(Math.random()*100); } printArray(arr,length); } private void printArray(int []arr,int lenght) { System.out.print("[ "); for(int i=0; i<lenght; i++) { System.out.print(arr[i]+ " "); } System.out.println("]"); } public void sort() { } public static void main(String[] args) { HeapSort hs=new HeapSort(10); int length=hs.length; hs.buildHeap(); hs.printArray(hs.arr, length); } }
Java
package evklid; import java.util.Scanner; public class hod { static int n=5; static int count=1; static int [][]arr=new int [n][n]; static int []dx={2,1,-1,-2,-2,-1,1,2}; static int []dy={1,2,2,1,-1,-2,-2,-1}; public static void main(String[] args) { for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { arr[i][j]=0; System.out.print(arr[i][j]+ " "); } System.out.print("\n"); } int x=(int)Math.random()*(n-1); int y=(int)Math.random()*(n-1); arr[x][y]=1; System.out.println(); for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { System.out.print(arr[i][j]+ " "); } System.out.print("\n"); } int s=1; choose(arr, x, y,s); } public static void Print() { for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { System.out.print(arr[i][j]+ "\t"); } System.out.print("\n"); } } public static void choose (int arr[][], int x, int y, int s) { arr[x][y]=s; if (s==n*n) { Print(); System.out.println(); } else{ if((x+2<n)&&(y+1<n)&&(arr[x+2][y+1]==0)) { choose(arr, x+2, y+1, s+1); } if((x+1<n)&&(y+2<n)&&(arr[x+1][y+2]==0)) { choose(arr, x+1, y+2, s+1); } if((x-1>=0)&&(x-1<n)&&(y+2<n)&&(arr[x-1][y+2]==0)) { choose(arr, x-1, y+2, s+1); } if((x-2>=0)&&(x-2<n)&&(y+1<n)&&(arr[x-2][y+1]==0)) { choose(arr, x-2, y+1, s+1); } if((x-2>=0)&&(y-1>=0)&&(x-2<n)&&(y-1<n)&&(arr[x-2][y-1]==0)) { choose(arr, x-2, y-1, s+1); } if((x-1>=0)&&(y-2>=0)&&(x-1<n)&&(y-2<n)&&(arr[x-1][y-2]==0)) { choose(arr, x-1, y-2, s+1); } if((y-2>=0)&&(x+1<n)&&(y-2<n)&&(arr[x+1][y-2]==0)) { choose(arr, x+1, y-2, s+1); } if((y-1>=0)&&(x+2<n)&&(y-1<n)&&(arr[x+2][y-1]==0)) { choose(arr, x+2, y-1, s+1); } } arr[x][y]=0; } }
Java
package evklid; import java.math.*; public class summa { public static void main(String[] args) { int c; long a=(long)(Math.random()*1000000000*1000000000); long b=(long)(Math.random()*1000000000*1000000000); System.out.println(" " +a); System.out.println("+"); System.out.println(" "+b); long ost=0; int n=0; long res; long a1=a; while(a1!=0){a1=a1/10; n++;} //System.out.println(n); long[] arr= new long [n]; int i=0; while (a!=0&&b!=0){ res=a%10+b%10+ost; ost=res/10; res=res%10; arr[i]=res; a=a/10; b=b/10; i++; } System.out.print(" "); for (int j=n-1; j>=0; j--){ System.out.print(arr[j]); } } }
Java
public class Fibzclass { public static int fibo(int N) { int i=1; int j=1; int p=0; if (N==1||N==2) { return 1; } else { for(int k=3; k<=N; k++) { p=i+j; i=j; j=p; } return(p); } } public static void main(String[] args) { long start = System.nanoTime(); System.out.println(fibo(6)); long end = System.nanoTime(); long traceTime = end-start; System.out.println(traceTime); } }
Java
public class NODsvclass { public static int svoy(int a,int b) { int k=0; if(a>=b) { k=b; } else { k=a; } if(a%2==0 && b%2==0) { while(a%k!=0 || b%k!=0) { k=k-2; } } else { if(a%5==0 && b%5==0) { while(a%k!=0 || b%k!=0) { k=k-5 ; } } else { while(a%k!=0 || b%k!=0) { k=k-1; } } } return(k); } public static void main(String[] args) { int j=30456; int i=2350; long start = System.nanoTime(); System.out.println(svoy(j,i)); long end = System.nanoTime(); long traceTime = end-start; System.out.println(traceTime); } }
Java
public class Fakclass { public static int faktorial(int N) { if(N<=1) return 1; else return N*faktorial(N-1); } public static void main(String[] args) { long start = System.nanoTime(); System.out.println(faktorial(4)); long end = System.nanoTime(); long traceTime = end-start; System.out.println(traceTime); } }
Java
public class NODclass { public static void main(String[] args) { int j=30456; int i=2350; long start = System.nanoTime(); for (int k=i; k>0;k--) { if ((j%k==0)&&(i%k==0)) { System.out.println(k); break; } } long end = System.nanoTime(); long traceTime = end-start; System.out.println(traceTime); } }
Java
package woman; public class Tree { public class Element { int num; Element left_child; Element right_child; Element iam; Element parent; public Element(int num, Element parent) { this.num = num; this.left_child = null; this.right_child = null; this.iam = this; this.parent = parent; } } Element root; int lenght; public Tree() { root = null; lenght = 0; } public Tree(int num) { root = new Element(num, null); lenght = 1; } public Element insert(int num) { lenght++; if(root == null) { root = new Element(num, null); return root; } Element Element = root; while(Element != null) if(num >= Element.num) if(Element.right_child == null) { Element.right_child = new Element(num, Element); return Element.right_child; } else Element = Element.right_child; else if(num < Element.num) if(Element.left_child == null) { Element.left_child = new Element(num, Element); return Element.left_child; } else Element = Element.left_child; lenght--; return null; } public void printTree() { System.out.println("\nLenght: " + lenght); printTree(root, 0); } private void printTree(Element Element, int level) { if(Element.right_child != null) printTree(Element.right_child, level+1); for(int i = 0; i < level; i++) System.out.print("\t"); System.out.println(Element.num); if(Element.left_child != null) printTree(Element.left_child, level+1); } public Element search(int num) { Element minElement = root; Element maxElement = root; Element Element = root; while(Element != null) if(num == Element.num) return Element; else if(num > Element.num) { if(maxElement.num < Element.num) maxElement = Element; minElement = Element; Element = Element.right_child; } else if(num < Element.num) { if(minElement.num > Element.num) minElement = Element; maxElement = Element; Element = Element.left_child; } if(maxElement.num - num <= num - minElement.num) return maxElement; else return minElement; } public Element Maximum() { Element Element = root; while(Element.right_child != null) Element = Element.right_child; return Element; } public Element Minimum() { Element Element = root; while(Element.left_child != null) Element = Element.left_child; return Element; } public boolean Delete(int num) { return Delete(num, root); } private boolean Delete(int num, Element Element) { while(Element != null) { if(num < Element.num) Element = Element.left_child; else if(num > Element.num) Element = Element.right_child; else if(num == Element.num) { if(Element.left_child != null && Element.right_child != null) { if(Element.right_child.left_child == null) { Element.right_child.left_child = Element.left_child; if(Element == root) root = Element.right_child; else if(Element.parent.left_child == Element) Element.parent.left_child = Element.right_child; else if(Element.parent.right_child == Element) Element.parent.right_child = Element.right_child; lenght--; return true; } else { Element Elementleft_child = Element.right_child.left_child; while(Elementleft_child.left_child != null) Elementleft_child = Elementleft_child.left_child; Element.num = Elementleft_child.num; return Delete(Elementleft_child.num, Elementleft_child); } } else { if(Element.left_child == null && Element.right_child == null) { if(Element == root) root = null; else if(Element.parent.left_child == Element) Element.parent.left_child = null; else if(Element.parent.right_child == Element) Element.parent.right_child = null; } else if(Element.left_child != null) { if(Element == root) root = Element.left_child; else if(Element.parent.left_child == Element) Element.parent.left_child = Element.left_child; else if(Element.parent.right_child == Element) Element.parent.right_child = Element.left_child; } else if(Element.right_child != null) { if(Element == root) root = Element.right_child; else if(Element.parent.left_child == Element) Element.parent.left_child = Element.right_child; else if(Element.parent.right_child == Element) Element.parent.right_child = Element.right_child; } lenght--; return true; } } } return false; } public static void main(String[] args) { Tree tree = new Tree(); int n = 5; System.out.println("Binaty_Tree"); for(int i = 0; i < n; i++) { int number = (int) (Math.random()*n*2-n); System.out.print(number + ","); tree.insert(number); } tree.printTree(); int search = (int) (Math.random()*n*2-n); int Num = tree.search(search).num; System.out.println("Search: " + search); System.out.println("Search Num: " + Num); System.out.println("Delete: " + Num + " : " + tree.Delete(Num)); System.out.println("Delete: " + Num/2 + " : " + tree.Delete(Num/2)); System.out.println("Address minimum: " + tree.Minimum()); System.out.println("Address maximum: " + tree.Maximum()); tree.printTree(); } }
Java
package woman; public class Tree { public class Element { int num; Element left_child; Element right_child; Element iam; Element parent; public Element(int num, Element parent) { this.num = num; this.left_child = null; this.right_child = null; this.iam = this; this.parent = parent; } } Element root; int lenght; public Tree() { root = null; lenght = 0; } public Tree(int num) { root = new Element(num, null); lenght = 1; } public Element insert(int num) { lenght++; if(root == null) { root = new Element(num, null); return root; } Element Element = root; while(Element != null) if(num >= Element.num) if(Element.right_child == null) { Element.right_child = new Element(num, Element); return Element.right_child; } else Element = Element.right_child; else if(num < Element.num) if(Element.left_child == null) { Element.left_child = new Element(num, Element); return Element.left_child; } else Element = Element.left_child; lenght--; return null; } public void printTree() { System.out.println("\nLenght: " + lenght); printTree(root, 0); } private void printTree(Element Element, int level) { if(Element.right_child != null) printTree(Element.right_child, level+1); for(int i = 0; i < level; i++) System.out.print("\t"); System.out.println(Element.num); if(Element.left_child != null) printTree(Element.left_child, level+1); } public Element search(int num) { Element minElement = root; Element maxElement = root; Element Element = root; while(Element != null) if(num == Element.num) return Element; else if(num > Element.num) { if(maxElement.num < Element.num) maxElement = Element; minElement = Element; Element = Element.right_child; } else if(num < Element.num) { if(minElement.num > Element.num) minElement = Element; maxElement = Element; Element = Element.left_child; } if(maxElement.num - num <= num - minElement.num) return maxElement; else return minElement; } public Element Maximum() { Element Element = root; while(Element.right_child != null) Element = Element.right_child; return Element; } public Element Minimum() { Element Element = root; while(Element.left_child != null) Element = Element.left_child; return Element; } public boolean Delete(int num) { return Delete(num, root); } private boolean Delete(int num, Element Element) { while(Element != null) { if(num < Element.num) Element = Element.left_child; else if(num > Element.num) Element = Element.right_child; else if(num == Element.num) { if(Element.left_child != null && Element.right_child != null) { if(Element.right_child.left_child == null) { Element.right_child.left_child = Element.left_child; if(Element == root) root = Element.right_child; else if(Element.parent.left_child == Element) Element.parent.left_child = Element.right_child; else if(Element.parent.right_child == Element) Element.parent.right_child = Element.right_child; lenght--; return true; } else { Element Elementleft_child = Element.right_child.left_child; while(Elementleft_child.left_child != null) Elementleft_child = Elementleft_child.left_child; Element.num = Elementleft_child.num; return Delete(Elementleft_child.num, Elementleft_child); } } else { if(Element.left_child == null && Element.right_child == null) { if(Element == root) root = null; else if(Element.parent.left_child == Element) Element.parent.left_child = null; else if(Element.parent.right_child == Element) Element.parent.right_child = null; } else if(Element.left_child != null) { if(Element == root) root = Element.left_child; else if(Element.parent.left_child == Element) Element.parent.left_child = Element.left_child; else if(Element.parent.right_child == Element) Element.parent.right_child = Element.left_child; } else if(Element.right_child != null) { if(Element == root) root = Element.right_child; else if(Element.parent.left_child == Element) Element.parent.left_child = Element.right_child; else if(Element.parent.right_child == Element) Element.parent.right_child = Element.right_child; } lenght--; return true; } } } return false; } public static void main(String[] args) { Tree tree = new Tree(); int n = 5; System.out.println("Binaty_Tree"); for(int i = 0; i < n; i++) { int number = (int) (Math.random()*n*2-n); System.out.print(number + ","); tree.insert(number); } tree.printTree(); int search = (int) (Math.random()*n*2-n); int Num = tree.search(search).num; System.out.println("Search: " + search); System.out.println("Search Num: " + Num); System.out.println("Delete: " + Num + " : " + tree.Delete(Num)); System.out.println("Delete: " + Num/2 + " : " + tree.Delete(Num/2)); System.out.println("Address minimum: " + tree.Minimum()); System.out.println("Address maximum: " + tree.Maximum()); tree.printTree(); } }
Java
public class Evkclass { public static void Evklid(int a,int b) { while (a!=0 && b!=0) { if (a>b) a=a%b; else b=b%a; } System.out.println(a+b); } public static void main(String[] args) { int j=30456; int i=2350; long start = System.nanoTime(); Evklid(j,i); long end = System.nanoTime(); long traceTime = end-start; System.out.println(traceTime); } }
Java
package quick; import java.util.Random; public class Qclass { public static void QuickSort(int arr[], int p, int r) { int k; int j; int x; k=p; j=r; x=arr[(k+j)/2]; do { while(arr[k]<x) k++; while(arr[j]>x) j--; if (k<=j) { int tmp=arr[k]; arr[k]=arr[j]; arr[j]=tmp; k++; j--; } } while(k<=j); if(j>p) QuickSort(arr,p,j); if(k<r) QuickSort(arr,k,r); } public static void main(String[] args) { int num=5; int[] arr = new int[num]; Random rand = new Random(); for(int i=0;i<num;i++) { arr[i]=rand.nextInt(5); System.out.print(arr[i]); } int p=0; int r=num-1; System.out.print('\n'); long start = System.nanoTime(); QuickSort(arr,p,r); long end = System.nanoTime(); long traceTime = end-start; System.out.println(traceTime); for(int i=0; i<num; i++) { System.out.print(arr[i]); } } }
Java
import java.util.ArrayList; import java.util.Collections; public class binaryclass { public static void main(String[] args) { int num=10; ArrayList<Integer> list = new ArrayList<Integer>(num); for(int i=0;i<num;i++) { list.add(i); } Collections.shuffle(list); System.out.println(list); buble(list,num); System.out.println(list); int chislo=8; System.out.println(BinSearch(list,chislo,0,num-1)); } public static int BinSearch(ArrayList<Integer> list, int chislo, int r, int k) { int i=(r+k)/2; if (list.get(i)==chislo) return i; if (list.get(i)<chislo) return BinSearch(list,chislo,i+1,k); else return BinSearch(list, chislo,r,i-1); } public static void buble(ArrayList<Integer> list,int num) { for(int i=0;i<num-1;i++) { for(int j=0;j<num-i-1;j++) { if(list.get(j)>list.get(j+1)) { int tmp=list.get(j); list.set(j,list.get(j+1)); list.set(j+1, tmp); } } } } }
Java
package bubble; import java.util.ArrayList; import java.util.Collections; public class bubclass { public static void main(String[] args) { int num=5; ArrayList<Integer> list= new ArrayList<Integer>(num); for (int i=0; i<num; i++) { list.add(i); } Collections.shuffle(list); System.out.println(list); System.out.println(list.get(0)); int r=0; boolean flag=true; long start = System.nanoTime(); for(int i=0; i<(num-1)&&flag; i++) { for (int j=0; j<(num-i-1); j++) { r=0; if (list.get(j)> list.get(j+1)) { int tmp=list.get(j); list.set(j, list.get(j+1)); list.set(j+1, tmp); r++; } System.out.println(i+","+j+list); } if (r==0) flag=false; } long end = System.nanoTime(); long traceTime = end-start; System.out.println(traceTime); } }
Java
public class Fibclass { public static int fibo_naive(int N) { if(N<=2) { return 1; } return fibo_naive(N-2)+fibo_naive(N-1); } public static void main(String[] args) { long start = System.nanoTime(); System.out.println(fibo_naive(6)); long end = System.nanoTime(); long traceTime = end-start; System.out.println(traceTime); } }
Java
package stolbik; public class slojenie { public static int[] arr1; public static int[] arr2; public static int[] arr3; public static int length=5; public static int n=0; public static void create(){ /*for(int i=0;i<length;i++){ arr1[i]=0; arr2[i]=0; arr3[i]=0; }*/ //random for(int i=1;i<length;i++){ arr1[i]=(int) (Math.random() * 9); } for(int i=0;i<length-1;i++){ arr2[i]=(int) (Math.random() * 9); } } public static void print(){ //System.out.println(); for(int i=0;i<length;i++){ System.out.print(arr1[i]); } System.out.println(); for(int i=0;i<length;i++){ System.out.print(arr2[i]); } System.out.println(); for(int i=0;i<length;i++){ System.out.print(arr3[i]); } } public static void sloj(){ for(int i=length-1;i>=0;i--){ arr3[i]=arr1[i]+arr2[i]+n; n=0; if(arr3[i]>=10){ arr3[i]=arr3[i]%10; n=1; } } } public static void main(String[] args) { arr1 = new int[length]; arr2 = new int[length]; arr3 = new int[length]; //length=5; create(); //print(); sloj(); print(); } }
Java
package lesson4; public class gkl { public static void main(String[] args) { int N=8; int A[][]; A = new int[N][N]; for( int i=0;i<N;i++){ for( int j=0;j<N;j++){ A[i][j]=0; } } A[2][2]=1; pr(A); mir(A,2,2); pr(A); } public static void pr(int A[][]) { int N=8; for( int i=0;i<N;i++){ System.out.println(""); for( int j=0;j<N;j++){ System.out.print(A[i][j]); } } System.out.println(""); } public static int mir(int A[][],int i, int j) { int N=8; if( i+2<N && j+1<N && 0<=i+2 && 0<=j+1 && A[i+2][j+1]==0){ A[i+2][j+1]=1; pr(A); mir(A,i+2,j+1); } if( i+2<N && j-1<N && 0<=i+2 && 0<=j-1 && A[i+2][j-1]==0 ){ A[i+2][j-1]=1; pr(A); mir(A,i+2,j-1); } if( i-2<N && j+1<N && 0<=i-2 && 0<=j+1 && A[i-2][j+1]==0 ){ A[i-2][j+1]=1; pr(A); mir(A,i-2,j+1); } if( i-2<N && j-1<N && 0<=i-2 && 0<=j-1 && A[i-2][j-1]==0){ A[i-2][j-1]=1; pr(A); mir(A,i-2,j-1); } if( i+1<N && j+2<N && 0<=i+1 && 0<=j+2 && A[i+1][j+2]==0){ A[i+1][j+2]=1; pr(A); mir(A,i+1,j+2); } if( i-1<N && j+2<N && 0<=i-1 && 0<=j+2 && A[i-1][j+2]==0){ A[i-1][j+2]=1; pr(A); mir(A,i-1,j+2); } if( i+1<N && j-2<N && 0<=i+1 && 0<=j-2 && A[i+1][j-2]==0){ A[i+1][j-2]=1; pr(A); mir(A,i+1,j-2); } if( i+1<N && j-2<N && 0<=i+1 && 0<=j-2 && A[i+1][j-2]==0){ A[i+1][j-2]=1; pr(A); mir(A,i+1,j-2); } return 0; } }
Java
package tree; public class bin { public class Elem { int num; Elem left; Elem right; public Elem parent; public Elem(int num, Elem parent) { this.num = num; this.left = null; this.right = null; this.parent = parent; } } Elem root; int lenght; /*public bin() { root = null; lenght = 0; } public bin(int num) { root = new Elem(num, null); lenght = 1; }*/ public Elem add(int num) { lenght++; if(root == null) { root = new Elem(num, null); return root; } Elem tree1 = root; while(tree1 != null) if(num >= tree1.num) if(tree1.right == null) { tree1.right = new Elem(num, tree1); return tree1.right; } else tree1 = tree1.right; else if(num < tree1.num) if(tree1.left == null) { tree1.left = new Elem(num, tree1); return tree1.left; } else tree1 = tree1.left; lenght--; return null; } public void printTree(Elem Elem, int level) { if(Elem.right != null) printTree(Elem.right, level+1); for(int k = 0; k < level; k++) System.out.print("\t"); System.out.println(Elem.num); if(Elem.left != null) printTree(Elem.left, level+1); } public Elem max(){ Elem tree1 = root; while(tree1.right!=null){ tree1 = tree1.right; } return tree1; } public Elem min() { Elem tree1 = root; while(tree1.left != null) tree1 = tree1.left; return tree1; } public static void main(String[] args) { bin tree = new bin(); tree.add(7); tree.add(2); tree.add(5); tree.add(3); tree.add(9); tree.add(6); tree.add(11); tree.add(13); tree.add(1); tree.printTree(tree.root, 0); } }
Java
package lesson2; //import java.util.Scanner; public class pereborom { public static void main(String args[]) { long startTime = System.currentTimeMillis(); int fi = 30; int si = 1000; System.out.println(NOD(fi,si)); long timeSpent = System.currentTimeMillis() - startTime; System.out.println("Program - " + timeSpent); } static int NOD(int fi,int si) { int min; int nod = 0; if(fi > si) min = si; else min = fi; for(int count = 1;count <= min;count++) { if(fi % count == 0 && si % count == 0){ if(count>nod) nod = count; } } return nod; } }
Java