diff --git a/basic/file/file_example.java b/basic/file/file_example.java new file mode 100644 index 0000000..0ab487c --- /dev/null +++ b/basic/file/file_example.java @@ -0,0 +1,249 @@ +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.RandomAccessFile; +import java.io.Reader; +public class ReadFromFile { +/** +* Read file by byte, for sound and image files +* @param fileName targetfile name +*/ +public static void readFileByBytes(String fileName){ +File file = new File(fileName); +InputStream in = null; + +try { + System.out.println("Read file by byte"); + // One byte at each time + in = new FileInputStream(file); + int tempbyte; + while((tempbyte=in.read()) != -1){ + System.out.write(tempbyte); + } + in.close(); +} catch (IOException e) { + e.printStackTrace(); + return; +} +try { + System.out.println("Read file by byte, multiple bytes one time"); + //multiple bytes one time + byte[] tempbytes = new byte[100]; + int byteread = 0; + in = new FileInputStream(fileName); + ReadFromFile.showAvailableBytes(in); + //byteread = length + while ((byteread = in.read(tempbytes)) != -1){ + System.out.write(tempbytes, 0, byteread); + } +} catch (Exception e1) { + e1.printStackTrace(); +} finally { + if (in != null){ + try { + in.close(); + } catch (IOException e1) { +} +} +} +} + +/** +* Read file by char, use for text and number files +* @param fileName +*/ +public static void readFileByChars(String fileName){ +File file = new File(fileName); +Reader reader = null; +try { +System.out.println("Read file by char, one char each time"); +reader = new InputStreamReader(new FileInputStream(file)); +int tempchar; +while ((tempchar = reader.read()) != -1){ +//because under windows, rn mean new line, when these two chars split, there will be two new lines. +//delete r can deduce useless blank lines +if (((char)tempchar) != 'r'){ +System.out.print((char)tempchar); +} +} +reader.close(); +} catch (Exception e) { +e.printStackTrace(); +} +try { +System.out.println("Read file by chars, multiple chars each time"); +char[] tempchars = new char[30]; +int charread = 0; +reader = new InputStreamReader(new FileInputStream(fileName)); +while ((charread = reader.read(tempchars))!=-1){ +if ((charread == tempchars.length)&&(tempchars[tempchars.length-1] != 'r')){ +System.out.print(tempchars); +}else{ +for (int i=0; i 4) ? 4 : 0; +//move to beginIndex pos +randomFile.seek(beginIndex); +byte[] bytes = new byte[10]; +int byteread = 0; +//each time at most 10 bytes +//length = readbyte +while ((byteread = randomFile.read(bytes)) != -1){ +System.out.write(bytes, 0, byteread); +} +} catch (IOException e){ +e.printStackTrace(); +} finally { +if (randomFile != null){ +try { +randomFile.close(); +} catch (IOException e1) { +} +} +} +} +/** +* display inputstream remaining byte number +* @param in +*/ +private static void showAvailableBytes(InputStream in){ +try { +System.out.println("current inputstream byte number is " + in.available()); +} catch (IOException e) { +e.printStackTrace(); +} +} +public static void main(String[] args) { +String fileName = "target.txt"; +ReadFromFile.readFileByBytes(fileName); +ReadFromFile.readFileByChars(fileName); +ReadFromFile.readFileByLines(fileName); +ReadFromFile.readFileByRandomAccess(fileName); +} +} + + +//add contents to the end of a file +import java.io.FileWriter; +import java.io.IOException; +import java.io.RandomAccessFile; +/** +* +*/ +public class AppendToFile { +/** +* RandomAccessFile +* @param fileName +* @param content +*/ +public static void appendMethodA(String fileName, + +String content){ +try { +// random access a file using rw +RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw"); +// byte number +long fileLength = randomFile.length(); +//pointer move to the end of the file +randomFile.seek(fileLength); +randomFile.writeBytes(content); +randomFile.close(); +} catch (IOException e){ +e.printStackTrace(); +} +} +/** +* FileWriter +* @param fileName +* @param content +*/ +public static void appendMethodB(String fileName, String content){ +try { +//open a writer method, use 'true' means to add contents to the file +FileWriter writer = new FileWriter(fileName, true); +writer.write(content); +writer.close(); +} catch (IOException e) { +e.printStackTrace(); +} +} +public static void main(String[] args) { +String fileName = "target.txt"; +String content = "new append!"; +// +AppendToFile.appendMethodA(fileName, content); +AppendToFile.appendMethodA(fileName, "append end. n"); +// +ReadFromFile.readFileByLines(fileName); +// +AppendToFile.appendMethodB(fileName, content); +AppendToFile.appendMethodB(fileName, "append end. n"); +// +ReadFromFile.readFileByLines(fileName); +} +} diff --git a/basic/file/file_instruction.java b/basic/file/file_instruction.java new file mode 100644 index 0000000..48c0f96 --- /dev/null +++ b/basic/file/file_instruction.java @@ -0,0 +1,41 @@ +//This file is written for file reading and wirting under different circumstances +//Since Java always uses Reader and Writer abstract class and their inheritance class, read, write, flush and close methods +//need to be override. +//If we are trying to treat with text file + +//use FileReader for .txt file +FileReader fr = new FileReader("targetpath/targetfile.txt"); +int next = 0; +while((next = fr.read())!=-1) //also can use read(char[] next, int off, int length) +{ + System.out.println(next); +} + +//Actually, all FileReader class is from the InputStreamReader. To imporve efficiency, BufferedReader class has the readLine() method +BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("targetpath/targetfile.txt"))); +String next = null; +while(next = (br.readLine())! = null) +{ + System.out.println(next); +} + +//Use Writer class for .txt writing +FileWriter fw = new FileWriter("targetpath/targetfile.txt"); +String next = "hello world!"; +fw.write(next,0,next.length()); +fw.flush(); + +//Use OutputStreamWriter +OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("targetpath/targetfile.txt")); +osw.write(next,0,next.length()); +osw.flush(); + +//Use PrintWriter, what is the difference? +PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("targetpath/targetfile.txt")),true); +pw.println(next); + +//Use BufferedWriter + + + +//multi-thread comparing the time-consuming diff --git a/basic/file/folderAndFile b/basic/file/folderAndFile new file mode 100644 index 0000000..57398c9 --- /dev/null +++ b/basic/file/folderAndFile @@ -0,0 +1,39 @@ +// this file contains some methods for creating and deleting a folder and a file + +//1. create a folder +public void createDir(String path)...{ + File dir=new File(path); + if(!dir.exists()) + dir.mkdir(); +} + +//2. create a new file +public void createFile(String path,String filename) throws IOException...{ + File file=new File(path+"/"+filename); + if(!file.exists()) + file.createNewFile(); +} + +//3. delete a file +public void delFile(String path,String filename)...{ + File file=new File(path+"/"+filename); + if(file.exists()&&file.isFile()) + file.delete(); +} + + +//4. delete a folder +public void delDir(String path)...{ + File dir=new File(path); + if(dir.exists())...{ + File[] tmp=dir.listFiles(); + for(int i=0;i list1 =new ArrayList (); + ArrayList sublist = new ArrayList (); + list1.add("test1"); + sublist.add("test2"); + list1.addAll(sublist); + + System.out.println("The super list: " + list1); + System.out.println("The sub list: " + sublist); + + System.out.println("--------------------------------------------------------------------"); + System.out.println("Whether the super list contains test1: " + list1.contains("test1")); + System.out.println("Whether the super list contains sublist: " + list1.containsAll(sublist)); + System.out.println("Whether the super list equals sublist: " + list1.equals(sublist)); + System.out.println("Hash code for super and sub list: "+ list1.hashCode() +" "+ sublist.hashCode()); + sublist.clear(); + System.out.println("Clear all elements in sublist: "+sublist.isEmpty()); + + Iterator it1 = list1.iterator(); + System.out.println("The first element in iterator: " + it1.next()); + + ArrayList sublist2 = new ArrayList (); + sublist2.add("test3"); + list1.addAll(sublist2); + System.out.println("--------------------------------------------------------------------"); + System.out.println("After add another sublist, the new list1 is " + list1 + " size: "+ list1.size()); + list1.remove("test2"); + list1.removeAll(sublist2); + System.out.println("Remove sublist and sublist2: " + list1.toString()); + + //System.out.println(list1.toArray()); + + } + + public void advancedExample(){ + //ArrayList has three main constructors shown: + //ArrayList(), ArrayList(Collection c), ArrayList(int Capacity) + long heapSize = Runtime.getRuntime().freeMemory(); + System.out.println("Size : "+ heapSize); + + ArrayList list1 = new ArrayList (); + //ArrayList list2 = new ArrayList (); + list1.add("test"); + + //ensureCapacity(int) method does influence the freeMemory remain. + System.out.println("Size before take larger memory space: "+ heapSize); + + list1.ensureCapacity(100000); + heapSize = Runtime.getRuntime().freeMemory(); + System.out.println("Size after take larger memory space: "+ heapSize); + + //trimToSize() can reduce the space and set the arraylist to the actual size, but cannot really influence the memory space + list1.trimToSize(); + heapSize = Runtime.getRuntime().freeMemory(); + System.out.println("Size after trim memory space: "+ heapSize); + } + + public void ArrayListToArray(){ + ArrayList list1 = new ArrayList (); + list1.add("1"); + list1.add("second"); + String array[] = new String[list1.size()]; + list1.toArray(array); + for(String s:array) + System.out.println(s); + } + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + List newList = new List(); + newList.exampleList(); + newList.advancedExample(); + newList.ArrayListToArray(); + + } + +} + +//LinkedList + + + diff --git a/interview/ctci/basic/Mapimp.java b/interview/ctci/basic/Mapimp.java new file mode 100644 index 0000000..fa1a0aa --- /dev/null +++ b/interview/ctci/basic/Mapimp.java @@ -0,0 +1,66 @@ +package com.dreamx.collection; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.TreeMap; + +public class Mapimp { + + public void treemapex(){ + //THE KEY OF TREEMAP is sorted! + Map map = new TreeMap (); + map.put("a","a"); + map.put("w","b"); + map.put("s","c"); + map.put("c","b"); + map.put("wds","d"); + map.put("aaa","f"); + + Iterator it = map.values().iterator(); + while(it.hasNext()){ + System.out.println(it.next()); + } + System.out.println("The values are not sorted while keys are sorted."); + System.out.println(map.keySet().toString()); + System.out.println(map.values().toString()); + Iterator it2 = map.keySet().iterator(); + while(it2.hasNext()){ + System.out.println(it2.next()); + } + } + + public void hashmapex(){ + //THE KEY OF TREEMAP is sorted! + HashMap map = new HashMap (); + map.put("a","a"); + map.put("w","n"); + map.put("s","b"); + map.put("c","c"); + map.put("wds","b"); + map.put("aaa","d"); + + Iterator it = map.values().iterator(); + while(it.hasNext()){ + System.out.println(it.next()); + } + System.out.println("The values and keys are not sorted."); + System.out.println(map.keySet().toString()); + System.out.println(map.values().toString()); + Iterator it2 = map.keySet().iterator(); + while(it2.hasNext()){ + System.out.println(it2.next()); + } + } + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + Mapimp imp = new Mapimp(); + imp.treemapex(); + imp.hashmapex(); + } + +} diff --git a/interview/ctci/basic/Queueimp.java b/interview/ctci/basic/Queueimp.java new file mode 100644 index 0000000..fc8ceda --- /dev/null +++ b/interview/ctci/basic/Queueimp.java @@ -0,0 +1,90 @@ +package com.dreamx.collection; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.Queue; + +public class Queueimp { + + public void queueexample(){ + Queue q1 = new LinkedList(); + q1.add("test1"); + q1.add(12); + System.out.println(q1.peek()); + System.out.println(q1.peek()); + q1.remove(); + System.out.println(q1.peek()); + } + + public LinkedList bfsexample(Node root){ + //use bfs to get the Node whose no is larger than 3 but less than 5 + Queue queue = new LinkedList(); + LinkedList nodes = new LinkedList(); + queue.add(root); + while(!queue.isEmpty()){ + Node current = queue.remove(); + current.visited = true; + if(current.left!=null){ + queue.add(current.left); + } + if (current.right!=null){ + queue.add(current.right); + } + if(current.no>=3&¤t.no<=5){ + nodes.add(current); + current.printNode(); + } + } + return nodes; + } + + public Node setNode(Node root){ + //construct a simple tree structure + Node h21 = new Node(2,"height2-1"); + Node h22 = new Node(2,"height2-2"); + root.left = h21; + root.right = h22; + Node h31 = new Node(3,"height3-1"); + Node h32 = new Node(3,"height3-2"); + Node h33 = new Node(0,"height3-3"); + h21.left = h31; + h22.left = h32; + h22.right = h33; + return root; + } + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + Queueimp newqueue = new Queueimp(); + //newqueue.queueexample(); + Node root = new Node(1,"root"); + newqueue.setNode(root); + LinkedList nodes = newqueue.bfsexample(root); + } +} + +class Node{ + int no = 0; + boolean visited = false; + String data = null; + public Node left = null; + public Node right = null; + + public Node(int size, String data){ + this.no = size; + this.data = data; + } + + public void visit(){ + this.visited = true; + } + + public void printNode(){ + System.out.println(this.visited + ", "+this.data); + } + +} + diff --git a/interview/ctci/basic/Stackimp.java b/interview/ctci/basic/Stackimp.java new file mode 100644 index 0000000..df50228 --- /dev/null +++ b/interview/ctci/basic/Stackimp.java @@ -0,0 +1,107 @@ +package com.dreamx.collection; + +import java.util.*; + +public class Stackimp { + + public static Stack stackexample(){ + Stack s1 = new Stack(); + s1.add("test1"); + s1.add("test2"); + System.out.println(s1); + s1.pop(); + System.out.println(s1); + return s1; + } + + public void example2(){ + Stack s = new Stack(); + s.add("test1"); + s.add(1); + System.out.println(s); + s.add(1, 2);//stack can choose the element adding position + System.out.println(s); + s.push("test2"); + System.out.println(s); + s.pop(); + System.out.println(s); + System.out.println(s.peek()); + s.pop(); + System.out.println(s.peek()); + } + + public HashMap dfsexample(Node root){ + HashMap map = new HashMap(); + Stack stack = new Stack (); + stack.push(root); + while(!stack.isEmpty()){ + Node current = stack.pop(); + current.printNode(); + current.visited = true; + if(current.left != null){ + stack.push(current.left); + } + if (current.right!= null){ + stack.push(current.right); + } + } + return map; + } + + public Node setNode(Node root){ + //construct a simple tree structure + Node h21 = new Node(2,"height2-1"); + Node h22 = new Node(2,"height2-2"); + root.left = h21; + root.right = h22; + Node h31 = new Node(3,"height3-1"); + Node h32 = new Node(3,"height3-2"); + Node h33 = new Node(3,"height3-3"); + Node h41 = new Node(4,"height4-1"); + Node h51 = new Node(5,"height5-1"); + h21.left = h31; + h22.left = h32; + h22.right = h33; + h31.left = h41; + h41.left = h51; + return root; + } + + /** + * @param args + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + Stackimp newstack = new Stackimp(); + //Stack s2 = Stackimp.stackexample(); + //newstack.example2(); + Node root = new Node(1,"root"); + newstack.setNode(root); + root.left.left.left.left.printNode(); + HashMap map = newstack.dfsexample(root); + } + +} +/*already defined in Queueimp.java +class Node{ + int no = 0; + boolean visited = false; + String data = null; + public Node left = null; + public Node right = null; + + public Node(int size, String data){ + this.no = size; + this.data = data; + } + + public void visit(){ + this.visited = true; + } + + public void printNode(){ + System.out.println(this.visited + ", "+this.data); + } + +} +*/ diff --git a/interview/ctci/basic/collections.java b/interview/ctci/basic/collections.java new file mode 100644 index 0000000..d950fee --- /dev/null +++ b/interview/ctci/basic/collections.java @@ -0,0 +1,5 @@ +//java has a lot of useful collection including the list, queue, map, etc... +/* abstract collection: AbstractList, AbstractMap, AbstractQueue, AbstractSequentialList, AbstractSet +interface: Collection, List, Queue, Comparator, ListIterator, RandomAccess, Deque, Map, Set, Enumeration, Map.Entry, + SortedMap, EventListener, NavigableMap, SortedSet, Formattable, NavigableSet, Iterator, Observer + diff --git a/interview/question/CountDistinctPair.java b/interview/question/CountDistinctPair.java new file mode 100644 index 0000000..a0a25b4 --- /dev/null +++ b/interview/question/CountDistinctPair.java @@ -0,0 +1,53 @@ +/* +Count all distinct pairs with difference equal to k +Given an integer array and a positive integer k, count all distinct pairs with difference equal to k. + +Examples: + +Input: arr[] = {1, 5, 3, 4, 2}, k = 3 +Output: 2 +There are 2 pairs with difference 3, the pairs are {1, 4} and {5, 2} + +Input: arr[] = {8, 12, 16, 4, 0, 20}, k = 4 +Output: 5 +There are 5 pairs with difference 4, the pairs are {0, 4}, {4, 8}, +{8, 12}, {12, 16} and {16, 20} +*/ +//http://www.geeksforgeeks.org/count-pairs-difference-equal-k/ +//The method2 in that page is more efficient than this one + +import java.util.ArrayList; +import java.util.List; +public class CountDistinctPair { + + public void count(int[] arr, int k){ + List list = new ArrayList(); + int[] arr2 = arr; + for(int i:arr){ + for(int j:arr2){ + if(i>j){ + if(i-j==k){ + list.add(i); + list.add(j); + } + } + } + } + System.out.println("Output Num: "+list.size()/2); + for(int z=0;z y^x +Given two arrays X[] and Y[] of positive integers, find number of pairs such that x^y > y^x where x is an element from X[] and y is an element from Y[]. + +Examples: + + Input: X[] = {2, 1, 6}, Y = {1, 5} + Output: 3 + // There are total 3 pairs where pow(x, y) is greater than pow(y, x) + // Pairs are (2, 1), (2, 5) and (6, 1) + + + Input: X[] = {10, 19, 18}, Y[] = {11, 15, 9}; + Output: 2 + // There are total 2 pairs where pow(x, y) is greater than pow(y, x) + // Pairs are (10, 11) and (10, 15) +*/ + +//http://www.geeksforgeeks.org/find-number-pairs-xy-yx/ + +/*mathmatical analysis: +x^y = y^x +take natural log on both sides. +=> yln(x)=xln(y) +=> ln(x)/x = ln(y)/y + +now differentiate ln(x)/x wrt x and compare it with zero. + +=> d/dx(ln(x)/x) +=> 1/x^2 - ln(x)/x^2 +=> (1-ln(x))/x^2 + +for all real x, x^2 >=0 +therefore : (1-ln(x)) >=0 for x<=e (~ 2.71 ) + +1-ln(x) < 0 for x>e +So ln(x)/x is increasing in range <=e, i.e. for integers, its increasing for 1,2 +and decreasing else where. + +(1) x<3, y<3: x need > y +(2) x<3 (x =2): y > 4 because 2^3 < 3^2, 2^4 = 4^2, 2^5>5^2 +(3) x>=3, y>=3: x need > y +(4) x>=3, y <3 (y=1): all + (y=2): x need =3 +*/ diff --git a/interview/question/MoveAllZero.java b/interview/question/MoveAllZero.java new file mode 100644 index 0000000..e7d971d --- /dev/null +++ b/interview/question/MoveAllZero.java @@ -0,0 +1,54 @@ +/*Given an array of random numbers, Push all the zero’s of a given array to the end of the array. +For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to +{1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same. Expected time +complexity is O(n) and extra space is O(1). +*/ + +public class MoveAllZero { + //This will use O(n^2) time and O(1) space + public int[] moveall (int[] arr){ + int[] re = arr; + int i,j; + for (i=0;i=n-1 && j=m-1 && i badd("101", "11") -> "1000" + * ------ + * "1000" + * + * "11" + * + "10" => badd("11", "10") -> "101" + * ------ + * "101" + * + * "01" + * + "10" => badd("01", "10") -> "011" + * ------ (leading '0' is optional) + * "011" + * + */ +import java.util.Stack; +public class computeString{ +public String badd(String x, String y) { + Stack stack1 = new Stack (); + Stack stack2 = new Stack (); + Stack stack3 = new Stack (); + String z = ""; + + for(int i=0; i