Document 11451794

advertisement
Θ
Θ
Θ
Θ
Θ
Θ
Θ
Θ
Θ(
Θ(
Θ(
Θ(
Θ
Θ
Θ
Θ
Θ
Θ
Θ
private void sortTopologically() {
//Prioritetksø sortert på minDistanse til hverandre
PriorityQueue<Task> queue = new PriorityQueue<Task>();
//Finner noder med null inngrader, legger de i køen
for (Task t : tasks) {
if (!t.hasDependencies()) {
queue.add(t);
}
}
//Så lenge køen ikke er tom, da ut første element og minsk naboers
// (utgraders) inngrad. For de nodene som nå har null i inngrad; legg i kø
while (!queue.isEmpty()) {
Task tmp = queue.remove(0);
topSort.add(tmp);
for (Edge edge = tmp.getOutEdges(); edge != null; edge = edge.next) {
Task neighbour = edge.getTaskTo();
if (neighbour.decreasePredecessors() == 0) {
queue.add(neighbour);
}
}
}
}
public void shortestPathFrom(Node source) {
PriorityQueue<Node> queue = new PriorityQueue<Node>();
/* Legger til noden det skal finnes distanse fra
i prioritetskøen. */
queue.add(source);
while (!queue.isEmpty()) {
//Henter første element i køen
Node node = queue.get(0);
//Går gjennom alle node's naboer
for (Edge e : node.adjList) {
Node n = e.target;
/*Setter vekten til kanten og vekten for å gå
forbi noden (altså kantens vekt + nodens distanse)
*/
int weight = e.weight;
int distanceThroughN = n.distance + weight;
/*Hvis "n"'s distance nå er mindre enn en tidligere
satt distanse; oppdater "n"'s distanse og sett forrige-pekeren
til "n" til "node" (som er "n" sin utgrad
Legg så til "n" i køen slik at "n"'s naboer kan oppdateres
med den nye distansen som «n» har fått
*/
if (distanceThroughN < n.minDistance) {
queue.remove(n);
n.minDistance = distanceThroughN;
n.previous = node;
queue.add(n);
}
}
}
}
public void MinimalSpanningTree(Node source) {
PriorityQueue<Node> queue = new PriorityQueue<Node>();
/* Legger til noden det skal finnes distanse fra
i prioritetskøen. */
queue.add(source);
while (!queue.isEmpty()) {
//Henter første element i køen
Node node = queue.get(0);
//Går gjennom alle node's naboer
for (Edge e : node.adjList) {
Node n = e.target;
//Setter vekten til å være lik kanten (fra og til)
int weight = e.weight;
//Hvis den nye vekten er mindre enn nåværende, oppdater vekten
//og legg til i køen.
if (weight < n.minDistance) {
queue.remove(n);
n.minDistance = weight;
n.previous = node;
queue.add(n);
}
}
}
}
//DFS for biconnectivity
public void assignLow(Node v) {
//Alle noder har fått sitt HN satt. Initielt settes nodens LN til sitt HN.
v.low = v.number;
//Går gjennom alle naboer W til V
for (Node w : v.neighbours) {
//Hvis en nabo W’s HN er større enn V’s HN, og nabo W’s LN er større
//eller lik V’s HN, så har vi et articulation point.
if (w.number > v.number) {
if (w.low >= v.number) //Articulation point!!!
//Setter V’s LN til det minste av V’s og nabo W’s LN
v.low = min (v.low, w.low)
} else {
//Hvis naboens HN er mindre eller lik V’s HN, og V sin forelder ikke er
nabo W
//så har man en backedge fra nabo W til V, og V’s LN blir det minste av
V’s LN og
//nabo W sitt HN.
if (v.parent != w) //back edge
v.low = min (v.low, w.number);
}
}
}


heap[currentSize+1] = newNode;
for (int i = currentSize+1; i > 1; i = i/2) {
if (heap[i] < heap[i/2]) {
svitsj de to;
}
}
temp = heap[1];
for (int i = 1; i < currentSize; i = i*2) {
if (heap[i * 2] < heap[(i * 2) + 1]) {
currentChild = i * 2;
} else {
currentChild = (i * 2) + 1;
}
if (heap[i] > heap[currentChild]) {
temp = heap[i];
heap[i] = heap[currentChild];
heap[currentChild] = temp;
}
}
return temp;
public Node merge(Node x, Node y) {
if (x == null) return y;
if (y == null) return x;
// if this was a max height biased leftist tree, then the
// next line would be: if(x.element < y.element)
if (x.element.compareTo(y.element) > 0) {
// x.element > y.element
Node temp = x;
x = y;
y = temp;
}
x.rightChild = merge(x.rightChild, y);
if (x.leftChild == null) {
// left child doesn't exist, so move right child to the left side
x.leftChild = x.rightChild;
x.rightChild = null;
x.s = 1;
} else {
// left child does exist, so compare s-values
if(x.leftChild.s < x.rightChild.s) {
Node temp = x.leftChild;
x.leftChild = x.rightChild;
x.rightChild = temp;
}
// since we know the right child has the lower s-value, we can just
// add one to its s-value
x.s = x.rightChild.s + 1;
}
return x;
}
int[] hashArray, tableSize;
Hash(int size) {
tableSize = size;
hashArray = new int[tableSize];
for (int i = 0; i < tableSize; i++) {
hashArray[i] = -1;
}
}
public void insert(int key) {
hashArray[hash(key)] = key;
currNr++;
if (rehashNeeded()) rehash();
}
public int get(int key) {
int index = key % tableSize;
int count = 0;
while (hashArray[index] != key) {
index += linearprobing(count++);
index += quadraticProbing(count++);
index += hash2(key, count++);
}
return hashArray[index];
}
public int remove(int key) {
int index = key % tableSize;
int count = 0;
while (hashArray[index] != key) {
index += linearprobing(count++);
index += quadraticProbing(count++);
index += hash2(key, count++);
}
int removed = hashArray[index];
hashArray[index] = -1;
return removed;
}
int hash(int key) {
int index = key % tableSize;
int count = 0;
while (isOccupied(index)) {
index += linearprobing(count++);
index += quadraticProbing(count++);
index += hash2(key, count++);
}
return index;
}
//DOUBLE HASHING
private int hash2(int key, int count) {
int r = getLargestPrime();
return count * (r - (key % r));
}
private int getLargestPrime() {
int prime = 0;
for (int i = 0; i < tableSize; i++) {
if (isPrime(i)) {
prime = i;
}
}
return prime;
}
boolean isPrime(int n) {
for (int i = 2; 2 * i < n; i++) {
if (n % i==0)
return false;
}
return true;
}
//LINIEAR PROBING
private int linearprobing(int count) {
return count;
}
//QUADRATIC PROBING
private int quadraticProbing(int count) {
return count * count;
}
// REHASHING
private boolean rehashNeeded() {
return ( (double) currNr / tableSize >
0.75);
}
private void rehash() {
int[] newHashArray = new
int[hashArray.size*2];
int[] oldHashArray = hashArray;
hashArray = newHashArray;
tableSize = tableSize*2;
for (int i = 0;
i < oldHashArray.length; i++) {
insert(oldHashArray[i]);
}
}
HashMap <Character, Integer> shiftTable = new HashMap();
// needle.length - 1 for å ikke sette siste char
for (int i = 0; i < needle.length -1; i++) {
int jump = (needle.length - i) - 1;
if (shiftTable.containsKey(needle[i]) {
shiftTable.remove(needle[i]);
}
shiftTable.add(needle[i], jump);
int hsCount = 0;
int maxHsCount = haystack.length - needle.length;
while (hsCount <= maxHsCount) {
for (int i = needle.length; needle[i] == haystack[hsCount - i]; i--){
if (i == 0) {
S.O.P("Match found!");
}
}
hsCount += shiftTable.get(hsCount + needle.length);
}
public class Huffman {
Node root;
String bitFile = "", text, convertedText;
int counter = 0;
int[] freq = new int[256];
BitCode[] bitTable;
Heap binHeap;
public static void main(String[] args) throws Exception{
new Huffman(args[0], args[1]);
}
Huffman(String file, String size) throws Exception{
this.text = new Scanner(new File(file)).nextLine();
genFreqTable(text);
binHeap = new Heap(Integer.parseInt(size));
}
/* Use an int-array and char-indexes to increase each char's frequences
private void genFreqTable(String text) {
char[] arr = text.toCharArray();
for (int i = 0; i < arr.length; i++) {
freq[arr[i]]++;
}
buildHeap();
}
//Insert every char with a frequency > 0 in the Heap
private void buildHeap() {
int freqCounter = 0;
for (int i = 0; i < freq.length; i++) {
if (freq[i] > 0) {
Node n = new Node(""+(char)i, freq[i], null, null);
n.leaf = true;
binHeap.insert(n);
freqCounter++;
}
}
bitTable = new BitCode[freqCounter];
buildFreqTree();
}
/* While the heap contains more than one item, do two deleteMins and use the two nodes
return to construct a parent with the two nodes as children (left and right)
and their
combined frequences as the parents frequency */
private void buildFreqTree() {
while(binHeap.getSize() > 1) {
Node right = binHeap.deleteMin();
Node left = binHeap.deleteMin();
Node parent = new Node(left.getChar()+ " " + right.getChar(), left.getFreq()+
right.getFreq(), left, right);
parent.leaf = false;
binHeap.insert(parent);
}
root = binHeap.deleteMin();
traverseTreeAndSetBitCodes(root, «");
}
}
/* Do an ordinary binary tree traversal and set bit codes for left (0) and right (1)
until you reach a leaf-node (which is a char) */
private void traverseTreeAndSetBitCodes(Node node, String bit) {
if (node != null && !node.isLeaf()) {
traverseTreeAndSetBitCodes(node.left, bit+"0");
traverseTreeAndSetBitCodes(node.right, bit+"1");
} else {
node.setBitRep(bit);
bitTable[counter] = new BitCode(node.getChar(), node.getBitRep());
}
generateBitFile();
}
//Generate the bitFile by getting the code representing each char in the string
private void generateBitFile() {
for (int i = 0; i < text.length(); i++) {
bitFile += getBitCode(""+text.charAt(i));
}
}
//Generate the text from the bitcode by getting the char represented by each code
private void generateTextFromBitCode() {
int currIndex = 0;
for (int i = 0; i <= bitFile.length(); i++) {
String letter = bitFile.substring(currIndex,i);
String c = getBitValue(letter);
if (!c.equals("9")) {
convertedText += ""+c;
currIndex = i;
}
}
}
private String getBitCode(String c) {
for (int i = 0; i < bitTable.length; i++) {
if (bitTable[i].c.equals(c)) {
return bitTable[i].code;
}
}
return "-1";
}
private String getBitValue(String code) {
for (int i = 0; i < bitTable.length; i++) {
if (bitTable[i] != null && bitTable[i].code.equals(code)) {
return bitTable[i].c;
}
}
return "9";
}
}
public static void kortesteVeiAlleTilAlle (int [][] nabo, int[][] avstand, int[][] vei) {
int n = avstand.length;
// Forutsetning: arrayene er kvadratiske med samme dimensjon //Initialisering:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
avstand[i][j] = nabo [i][j]; vei[i][j] = −1; // Ingen vei foreløpig
}
}
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j ++) {
if (avstand[i][k] + avstand[k][j] < avstand[i][j]) {
//Kortere vei fra i til j funnet via k
avstand[i][j] = avstand[i][k]+avstand[k][j]; vei[i][j] = k;
}
}
}
}
}
void bytt(int[] a, int i, int j) {
int t = a[i];
a[i]=a[j];
a[j] = t;
}
void bobleSort (int [] a) {
int i = 0, max = a.length - 1;
while (i < max) {
if (a[i] > a[i+1]) {
bytt (a, i, i+1);
if (i > 0 ) i--;
} else {
i++;
}
}
}
void insertSort(int [] a ) {
int i, t, max = a.length -1;
for (int k = 0 ; k < max; k++) {
// Invariant: a[0..k] er sortert, skal
// nå sortere a[k+1] inn på riktig plass
if (a[k] > a[k+1]) {
t = a[k+1];
i = k;
do{
// gå bakover, skyv de andre
// og finn riktig plass for ’t’
a[i+1] = a[i];
i--;
} while (i >= 0 && a[i] > t);
a[i+1] = t;
}
}
}
void quicksort ( int [] a, int l, int r) {
int i= l, j=r;
int t, part = a[(l+r)/2];
while ( i <= j) {
while ( a[i] < part ) i++; //hopp forbi små
while (part < a[j] ) j--; // hopp forbi store
if (i <= j) {
// swap en for liten a[j] med for stor a[i]
t = a[j];
a[j]= a[i];
a[i]= t;
i++;
j--;
}
}
if ( l < j ) quicksort (a,l,j);
if ( i < r ) quicksort (a,i,r);
}
import java.util.Arrays;
class Merge{
public static void main(String[] args) {
int[] a = {1,5,7,88,101,102,117};
int[] b = {2,3,4,66,96,97,97};
System.out.println(Arrays.toString( flett(a,b) ));
}
public static int[] flett(int[] a, int[] b){
int[] merged = new int[a.length+b.length];
int left = 0, leftEnd = a.length - 1;
int right = 0, rightEnd = b.length - 1;
int curPos = 0;
while (left <= leftEnd && right <= rightEnd){
if (a[left] < b[right]){
merged[curPos++] = a[left++];
} else {
merged[curPos++] = b[right++];
}
}
// resten
while (left <= leftEnd){
merged[curPos++] = a[left++];
}
while (right <= rightEnd){
merged[curPos++] = b[right++];
}
return merged;
}
}
import java.util.Arrays;
import java.util.LinkedList;
public class RadixSort {
// base 10
// LinkedList is also a Queue
private LinkedList<Integer>[] counter = new LinkedList[] {
new LinkedList<Integer>(),
new LinkedList<Integer>(),
new LinkedList<Integer>(),
new LinkedList<Integer>(),
new LinkedList<Integer>(),
new LinkedList<Integer>(),
new LinkedList<Integer>(),
new LinkedList<Integer>(),
new LinkedList<Integer>(),
new LinkedList<Integer>()
};
private RadixSort() {}
public void sortLSD(int[] array, int maxDigitSymbols) {
int mod = 10;
int dev = 1;
for (int i = 0; i < maxDigitSymbols; i++, dev *= 10, mod *= 10) {
//System.out.println(Arrays.toString(array));
for(int j = 0; j < array.length; j++) {
int bucket = (array[j] % mod) / dev;
counter[bucket].add(array[j]);
}
int pos = 0;
for(int j = 0; j < counter.length; j++) {
Integer value = null;
while ((value = counter[j].poll()) != null) {
//System.out.println(value);
array[pos++] = value;
}
}
}
}
class BordGenerator2{
String[] elements = {"1", "2", "3"};
int n = elements.length;
public static void main(String[] args) {
new BordGenerator2().permuter(0);
}
public void permuter(int i){
if (i == n - 1){
System.out.println( elements[0] + " " + elements[1] + " " +elements[2] );
} else {
permuter(i+1);
for (int k = i+1; k<n; k++){
bytt(i,k);
permuter(i+1);
}
roterVenstre(i);
}
}
public void bytt(int i, int j){
String tmp = elements[i];
elements[i] = elements[j];
elements[j] = tmp;
}
public void roterVenstre(int i){
String tmp = elements[i];
for (int k = i+1; k<n; k++){
elements[k-1] = elements[k];
}
elements[n-1] = tmp;
}
}
Download