package org.code;
import java.util.Arrays;
import java.util.Random;
/**
* @author Purna
*
* this class just shuffles the given set of cards assuming there are 52
* cards 1-52
*/
public class CardsShuffler {
public static Random randomGenerator = new Random();
public static void main(String args[]) {
int[] cards = new int[5];
for (int index = 0; index < cards.length; index++) {
cards[index] = index + 1;
}
printCards(cards);
shuffleCards(cards);
}
/**
* shuffles the cards using
*
* Knuth Shuffle
*
* @param cards
*/
private static void shuffleCards(int[] cards) {
for (int index = 1; index < cards.length; index++) {
int cardToShuffleWith = randomGenerator.nextInt(index);
swapNumbers(cards, index, cardToShuffleWith);
// printing the cards on every shuffle
printCards(cards);
}
}
/**
* Swaps two Cards
*
* @param cards
* @param index
* @param cardToShuffleWith
*/
private static void swapNumbers(int[] cards, int index,
int cardToShuffleWith) {
int temp = cards[index];
cards[index] = cards[cardToShuffleWith];
cards[cardToShuffleWith] = temp;
}
/**
* prints the cards
*
* @param cards
*/
private static void printCards(int[] cards) {
System.out.println(Arrays.toString(cards));
}
}
Labels
Showing posts with label algorithms. Show all posts
Showing posts with label algorithms. Show all posts
Cards Shuffle Code in Java
Remove duplicate Characters without extra memory in java
/**
* Without using extra(large) memory Complexity O(n^2)
* @param word
*/
private static void removeDuplicates(char[] word) {
int currentIndex = 1;
for (int i = 0; i < word.length; i++) {
int j;
for (j = 0; j < currentIndex; j++) {
if (word[i] == word[j]) {
break;
}
}
if (currentIndex == j) {
word[currentIndex++] = word[i];
}
}
while (currentIndex < word.length) {
word[currentIndex++] = ' ';
}
}
Insertion Sort in Java
Before Sorting, Input :0 10 2 9 3 8 1 6 5 7 4 the first element is sorted here
0 10 2 9 3 8 1 6 5 7 4 first 2 elements are sorted
0 2 10 9 3 8 1 6 5 7 4 and so on….
0 2 9 10 3 8 1 6 5 7 4
0 2 3 9 10 8 1 6 5 7 4
0 2 3 8 9 10 1 6 5 7 4
0 1 2 3 8 9 10 6 5 7 4
0 1 2 3 6 8 9 10 5 7 4
0 1 2 3 5 6 8 9 10 7 4
0 1 2 3 5 6 7 8 9 10 4
0 1 2 3 4 5 6 7 8 9 10
After Sorting, output :0 1 2 3 4 5 6 7 8 9 10
/*** every element before the index is sorted. so select the number at the* index location and put it in appropriate position** @param numbers*/private static void sortList(Integer[] numbers) {for (int index = 0; index < numbers.length; index++) {for (int sortIndex = index; sortIndex > 0; sortIndex--) {if (numbers[sortIndex] < numbers[sortIndex - 1]) {swap(sortIndex, sortIndex - 1, numbers);} else {break;}}printArray(numbers);}}/*** swap 2 numbers at the index** @param indexOne* @param indexTwo* @param numbers*/private static void swap(int indexOne, int indexTwo, Integer[] numbers) {Integer temp = numbers[indexOne];numbers[indexOne] = numbers[indexTwo];numbers[indexTwo] = temp;}
Selection Sort in Java
- Find the smallest entry for an Index
- Swap it with the index element do this iteratively till the end of the array
Complexity: (n power 2)/2 comparisions & n exchanges
/*** find the minimum in the series and swap it to the index* @param numbers*/private static void sortList(Integer[] numbers) {for (int index = 0; index < numbers.length; index++) {int minIndex = findMininRest(index, numbers);if (minIndex != index) {swap(minIndex, index, numbers);printArray(numbers);}}}/*** swap 2 numbers at the index* @param minIndex* @param index* @param numbers*/private static void swap(int minIndex, int index, Integer[] numbers) {Integer temp = numbers[minIndex];numbers[minIndex] = numbers[index];numbers[index] = temp;}/*** find the minimum in the rest of the series** @param index* the current index to fill* @param numbers* all the numbers* @return returns the index of the minimum element in the rest series from* index*/private static int findMininRest(int index, Integer[] numbers) {int currentMin = index;for (int restIndex = index + 1; restIndex < numbers.length; restIndex++) {if (numbers[currentMin] > numbers[restIndex]) {currentMin = restIndex;}}return currentMin;}
Trace of the sort per Iteration
0 10 2 9 3 8 1 6 5 7 4 INPUT
0 1 2 9 3 8 10 6 5 7 4
0 1 2 3 9 8 10 6 5 7 4
0 1 2 3 4 8 10 6 5 7 9
0 1 2 3 4 5 10 6 8 7 9
0 1 2 3 4 5 6 10 8 7 9
0 1 2 3 4 5 6 7 8 10 9
0 1 2 3 4 5 6 7 8 9 10 OUTPUT
Recursively print Permutations of a String
recursivelyReverse("", "helloWorld");private static void recursivelyReverse(String first, String second) {if (second.length() == 0) {System.out.println(first);return;}for (int index = 0; index < second.length(); index++) {recursivelyReverse(first + second.charAt(index), second.substring(0, index) + second.substring(index + 1));}}
Approximate Search or Spell Check using Trie in Java
the sample code in java which uses TRIE ds can be found <<Click here>>
the main program which has to be run is MainRunner.Java
modify the searchString variable in the main program.
books.txt : this file has the list of books which are indexed for the approximate search.
commonwords.txt this file has the words which will be ignored.
Features:
can detect 4 types of errors
the exact word say is programming
1) Transposition : prorgamming
2) Insertion: programNming
3) Deletion: programing {m is deleted}
4) Substitution: projramming
would all list the results of books which have programming text.
the main program which has to be run is MainRunner.Java
modify the searchString variable in the main program.
books.txt : this file has the list of books which are indexed for the approximate search.
commonwords.txt this file has the words which will be ignored.
Features:
can detect 4 types of errors
the exact word say is programming
1) Transposition : prorgamming
2) Insertion: programNming
3) Deletion: programing {m is deleted}
4) Substitution: projramming
would all list the results of books which have programming text.
Heap Sort
Heap Sort in C++
#include < iostream.h >
#include < conio.h >
int heapSize = 10;
void print(int a[]) {
for (int i = 0; i <= 9; i++) {
cout << a[i] << "-";
}
cout << endl;
}
int parent(int i) {
if(i==1)
return 0;
if(i%2==0)
return ( (i / 2)-1);
else
return ( (i / 2));
}
int left(int i) {
return (2 * i) + 1;
}
int right(int i) {
return (2 * i) + 2;
}
void heapify(int a[], int i) {
int l = left(i), great;
int r = right(i);
if ( (a[l] > a[i]) && (l < heapSize)) {
great = l;
}
else {
great = i;
}
if ( (a[r] > a[great]) && (r < heapSize)) {
great = r;
}
if (great != i) {
int temp = a[i];
a[i] = a[great];
a[great] = temp;
heapify(a, great);
}
}
void BuildMaxHeap(int a[]) {
for (int i = (heapSize - 1) / 2; i >= 0; i--) {
heapify(a, i);
print(a);
}
}
void HeapSort(int a[]) {
BuildMaxHeap(a);
for (int i = heapSize; i > 0; i--) {
int temp = a[0];
a[0] = a[heapSize - 1];
a[heapSize - 1] = temp;
heapSize = heapSize - 1;
heapify(a, 0);
}
}
void main() {
int arr[] = {
2, 9, 3, 6, 1, 4, 5, 7, 0, 8};
HeapSort(arr);
print(arr);
}
Quick Sort
Quick Sort in c++
#include < iostream.h >
#include < stdio.h >
#include < conio.h >
void print(int a[]) {
for (int i = 0; i < 10; i++) {
cout << a[i] << "-";
}
cout << endl;
}
int partition(int a[], int p, int r) {
int x = a[r];
int j = p - 1;
for (int i = p; i < r; i++) {
if (x <= a[i]) {
j = j + 1;
int temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
a[r] = a[j + 1];
a[j + 1] = x;
return (j + 1);
}
void quickSort(int a[], int p, int r) {
if (p < r) {
int q = partition(a, p, r);
quickSort(a, p, q - 1);
quickSort(a, q + 1, r);
}
}
void main() {
int a[] = {
1, 9, 0, 5, 6, 7, 8, 2, 4, 3};
quickSort(a, 0, 9);
print(a);
getch();
}
Merge Sort
Merge sort in C
#include < iostream.h >
#include < conio.h >
#include < stdio.h >
void print(int * a) {
for (int i = 0; i < 10; i++) {
cout << a[i] << "-";
}
cout << endl;
}
void mergeConquer(int * a, int left, int mid, int right) {
int lno = mid - left + 1;
int rno = right - mid;
int * L = new int[lno];
int * R = new int[rno];
for (int y = 0; y < lno; y++) {
L[y] = a[left + y];
cout << L[y] << "l";
}
cout << endl;
for (int z = 0; z < rno; z++) {
R[z] = a[mid + z + 1];
cout << R[z] << " r "; ;
}
cout << endl;
y = 0;
z = 0;
for (int i = left; i <= right; i++) {
if ( (y < lno) && (z < rno)) {
if (L[y] <= R[z]) {
a[i] = L[y];
y++;
}
else {
a[i] = R[z];
z++;
}
}
else if ( (y < lno) && (z >= rno)) {
a[i] = L[y];
y++;
}
else if ( (y >= lno) && (z < rno)) {
a[i] = R[z];
z++;
}
}
}
void mergeDivide(int * a, int left, int right) {
int mid = (left + right) / 2;
if (left < right) {
cout << "============";
mergeDivide(a, left, mid);
mergeDivide(a, mid + 1, right);
mergeConquer(a, left, mid, right);
}
}
void main() {
clrscr();
int a[] = {
5, 24, 6, 48, 9, 40, 42, 3, 1, 7};
mergeDivide(a, 0, 9);
print(a);
}
Stack
#include <stdio.h>
#include <conio.h>
#include <iostream.h>
#include <stdlib.h>
class element
{
public:
int value;
element* next;
};//class element
class stack
{
public:
int size;
element* current;
stack()
{
size=0;
current=NULL;
}//default constructor
bool push(int,element*);
bool pop();
bool isEmpty();
int getStackSize();
void printStackSize();
void printStackElements(element*);
void printStackMenu();
};
bool stack::push(int ele,element* temp)
{
temp=new element;
if(current==NULL)
{
temp->next=NULL;
}
else
{
temp->next=current;
}
temp->value=ele;
current=temp;
printf("%d inserted\n\n",ele);
size++;
return false;
}
bool stack::pop()
{
if(isEmpty())
{
cout<<"\nStack is Empty\n";
return false;
}
else
{
cout<<"\n Element To POP :"<<current->value;
cout<<"\n Before POP";
printStackElements(current);
current=current->next;
cout<<"\n After POP";
printStackElements(current);
size=size--;
}
return true;
}
bool stack::isEmpty()
{
if(getStackSize()==0)
return true;
return false;
}
int stack::getStackSize()
{
return size;
}//returns size of the stack
void stack::printStackSize()
{
cout<<"\nThe Size of the Stack:"<<size<<"\n";
}//print the stack size
void stack::printStackElements(element* base)
{
element* curr2;
curr2= base;
cout<<"\n-----\n";
cout<<"STACK\n";
cout<<"-----\n";
while(curr2!=NULL)
{
cout<<" |"<<curr2->value<<"|\n";
curr2=curr2->next;
}
}// print the stack
void stack::printStackMenu()
{
cout<<"Welcome to Stack \n";
cout<<"1.Push an element\n";
cout<<"2.Pop an element\n";
cout<<"3.Display Stack\n";
cout<<"4.Size Of Stack\n";
cout<<"5.Exit\n";
}
void main()
{
stack st;
char Option=0;
int val;
while(1)
{
st.printStackMenu();
cin>>Option;
switch(Option)
{
case '1':
cout<<"Enter a Number \n";
cin>>val;
st.push(val,st.current);
break;
case '2':
st.pop();
break;
case '3':
st.printStackElements(st.current);
break;
case '4':
st.printStackSize();
break;
case '5':
exit(0);
break;
}
}
}
Queue
#include <iostream.h>
class element
{
public:
int value;
element* next;
};//class element
class Queue
{
public:
int size;
element* head;
element* tail;
Queue()
{
size=0;
head=NULL;
tail=NULL;
}//default constructor
void Enqueue(int);
void Dequeue();
int isEmpty();
int getQueueSize();
void printQueueSize();
void printQueueElements();
void printQueueMenu();
};
void Queue::Enqueue(int ele)
{
if(head==NULL) // first element
{
head=new element;
tail=head; //head==tail if one element
head->value=ele;
head->next=NULL;
}
else
{
tail->next=new element;
tail->next->value=ele;
tail->next->next=NULL;
cout<<tail->next->value<<endl;
tail=tail->next;
}
size++;
//printQueueElements();
}
void Queue::Dequeue()
{
if(getQueueSize()==0)
return;
else if(head==tail)
{
head=NULL;
}
else
{
element *curr,*prev; //remove the first element inserted and
curr=head; //point the head to next element
head=curr->next;
curr=NULL;
}
size--;
}
int Queue::isEmpty()
{
if(getQueueSize()==0)
return 1;
return 0;
}
int Queue::getQueueSize()
{
return size;
}//returns size of the Queue
void Queue::printQueueSize()
{
cout<<"\nThe Size of the Queue:"<<size<<"\n";
}//print the Queue size
void Queue::printQueueElements()
{
element* curr2;
curr2= head;
cout<<"\n-----\n";
cout<<"Queue\n";
cout<<"-----\n";
cout<<"size:"<<getQueueSize()<<endl;
while(curr2!=NULL)
{
cout<<" |"<<curr2->value<<"|";
curr2=curr2->next;
}
cout<<endl;
}// print the Queue
void Queue::printQueueMenu()
{
cout<<"Welcome to Queue \n";
cout<<"1.Enqueue an element\n";
cout<<"2.Dequeue an element\n";
cout<<"3.Display Queue\n";
cout<<"4.Size Of Queue\n";
cout<<"5.Exit\n";
}
void main()
{
Queue qt;
qt.printQueueMenu();
char Option=0;
int val;
while(1)
{
qt.printQueueMenu();
cin>>Option;
switch(Option)
{
case '1':
cout<<"Enter a Number \n";
cin>>val;
qt.Enqueue(val);
break;
case '2':
qt.Dequeue();
break;
case '3':
qt.printQueueElements();
break;
case '4':
qt.printQueueSize();
break;
case '5':
exit(0);
break;
}
}
}
Double Linked List
#include <iostream.h>
class node
{
public:
int value; //value stored in the node
node *next; //pointer to next node
node *prev; //pointer to previous node
};
class dlist
{
public:
node *front; //pointer to front of list
node *back; //pointer to back of list
dlist()
{
front=NULL;
back=NULL;
}
void insertFront(int value);
void insertBack(int value);
void removeFront();
void removeBack();
void insertBefore(int value,node *nodeB);
void insertAfter(int value,node *nodeA);
void removeBefore(node *nodeB);
void removeAfter(node *nodeA);
void removeNode(node *newNode);
void printDListFront();
void printDListBack();
};
//insert a node before nodeB
void dlist::insertBefore(int value,node *nodeB)
{
node *newNode;
newNode=new node();
newNode->prev=nodeB->prev;
newNode->next =nodeB;
newNode->value =value;
if(nodeB->prev==NULL)
{
this->front=newNode;
}
nodeB->prev=newNode;
}
//insert a node before the front node
void dlist::insertFront (int value)
{
node *newNode;
if(this->front==NULL)
{
newNode=new node();
this->front=newNode;
this->back =newNode;
newNode->prev=NULL;
newNode->next=NULL;
newNode->value=value;
}
else
{
insertBefore(value,this->front );
}
}
//insert a node after nodeB
void dlist::insertAfter(int value,node *nodeB)
{
node *newNode;
newNode=new node();
newNode->next= nodeB->next ;
newNode->prev =nodeB;
newNode->value =value;
if(nodeB->next==NULL)
{
cout<<"\n "<< endl;
this->back =newNode;
}
nodeB->next=newNode;
cout<<"2"<<endl;
}
//insert a node after the last node
void dlist::insertBack (int value)
{
if(this->back==NULL)
{
cout<<"insert at back";
insertFront(value);
}
else
{
cout<<"insert at back";
insertAfter(value,this->back );
}
}
//remove the front node
void dlist::removeFront ()
{
removeNode(this->front);
}
//remove a back node
void dlist::removeBack ()
{
removeNode(this->back);
}
//remove before a node
void dlist::removeBefore(node *nodeB)
{
if(nodeB->prev==this->front)
{
this->front=nodeB;
this->front->prev=NULL;
}
else
{
removeNode(nodeB->prev);
}
}
//remove after a node
void dlist::removeAfter(node *nodeA)
{
if(nodeA->next==this->back)
{
this->back=nodeA;
this->back->next=NULL;
}
else
{
removeNode(nodeA->next);
}
}
//remove a perticular node
void dlist::removeNode(node *nodeToRemove)
{
if(nodeToRemove==this->front)
{
this->front=this->front->next;
this->front->prev=NULL;
}
else if (nodeToRemove==this->back)
{
this->back=this->back->prev;
this->back->next=NULL ;
}
else
{
nodeToRemove->prev->next=nodeToRemove->next;
nodeToRemove->next->prev=nodeToRemove->prev;
}
}
//Print the list from front
void dlist::printDListFront()
{
node* curr2;
curr2= this->front;
cout<<"\n-----\n";
cout<<"Queue\n";
cout<<"-----\n";
//cout<<"size:"<<getQueueSize()<<endl;
while(curr2!=NULL)
{
cout<<" |"<<curr2->value<<"|";
curr2=curr2->next;
}
cout<<endl;
}// print the Double Linked List from front
// print the Double Linked List from backwards
void dlist::printDListBack()
{
node* curr2;
curr2= this->back;
cout<<"\n-----\n";
cout<<"Queue\n";
cout<<"-----\n";
//cout<<"size:"<<getQueueSize()<<endl;
while(curr2!=NULL)
{
cout<<" |"<<curr2->value<<"|";
curr2=curr2->prev;
}
cout<<endl;
}// print the Double Linked List from back
void main()
{
dlist *st ;
st= new dlist();
st->insertBack(8);
st->printDListFront ();
st->insertBack(5);
st->printDListFront ();
st->insertBack(6);
st->printDListFront ();
st->insertFront(1) ;
st->printDListFront ();
st->insertFront(3) ;
st->printDListFront ();
st->insertBack(7);
st->printDListFront ();
st->removeFront();
st->printDListFront ();
st->removeBack();
st->printDListFront ();
}Binary Search Tree
Binary Search Tree
import java.*;
import java.lang.*;
//node of the binary tree
class bnode {
String key;
bnode left;
bnode right;
bnode() {
key = null;
left = null;
right = null;
}
bnode(String key) {
this.key = key;
left = null;
right = null;
}
};
//binary tree
class btree {
bnode root;
btree() {
root = null;
}
//insert a node into the tree
void put(String key) {
bnode current = root;
bnode prev = current;
if (root == null) {
root = new bnode(key);
}
else {
boolean insert = false;
while (insert == false) {
prev = current;
if (key.compareTo(current.key) < 0) {
if (current.left == null) {
current.left = new bnode(key);
insert = true;
}
current = current.left;
}
else {
if (current.right == null) {
current.right = new bnode(key);
insert = true;
}
current = current.right;
}
}
}
}
//delete a node with a key
boolean delete(String key) {
boolean deleted = true;
bnode current = root;
bnode prev = current;
while (current != null) {
if (key.compareTo(current.key) > 0) {
prev = current;
current = current.right;
}
else if (key.compareTo(current.key) < 0) {
prev = current;
current = current.left;
}
else if (key.compareTo(current.key) == 0) {
deleted = false;
break;
}
}
if (check(current) == 0) {
if (current.key.compareTo(prev.key) > 0) {
prev.right = null;
}
else {
prev.left = null;
}
}
else if (check(current) == 1) {
if (current.key.compareTo(prev.key) > 0) {
if (current.left != null) {
prev.right = current.left;
}
else {
prev.right = current.right;
}
}
else {
if (current.left != null) {
prev.left = current.left;
}
else {
prev.left = current.right;
}
}
}
else if (check(current) == 2) {
bnode temp = inord(current);
if (current == root) {
root.key = temp.key;
}
else {
if (current.key.compareTo(prev.key) > 0) {
prev.right.key = temp.key;
}
else {
prev.left.key = temp.key;
}
}
}
return deleted;
}
//in order
bnode inord(bnode a) {
int t = 0;
bnode ret, prev = new bnode();
prev = a;
a = a.right;
while (a.left != null) {
prev = a;
a = a.left;
t = 1;
}
ret = a;
if (t == 0) {
prev.right = null;
}
else {
prev.left = null;
}
a = null;
return ret;
}
//check if a node is there
int check(bnode a) {
int ret;
if ( (a.left != null) && (a.right != null)) {
ret = 2;
}
else if ( (a.left == null) && (a.right == null)) {
ret = 0;
}
else {
ret = 1;
}
return ret;
}
//print the node
void printIn(bnode oot) {
if (oot.left != null) {
printIn(oot.left);
}
System.out.println("--------" + oot.key + "----------");
if (oot.right != null) {
printIn(oot.right);
}
}
public static void main(String[] args) {
btree a = new btree();
a.put("h");
a.put("g");
a.put("e");
a.put("d");
a.put("f");
a.put("c");
a.put("b");
a.put("a");
a.put("i");
a.printIn(a.root);
a.delete("h");
a.delete("e");
a.printIn(a.root);
}
}
Towers OF hanoi program in c++
#include <iostream.h>
// a disk with a value , which is an element of the stack ,tower in this case
class Disk
{
public:
int value;
Disk* next;
};//class Disk
class Tower //a stack data structure representing a tower
{
public:
int size;
Disk* current;
Tower()
{
size=0;
current=NULL;
}//default constructor
int peep();
bool push(int);
bool pop();
bool isEmpty();
int getTowerSize();
void printTowerSize();
void printTowerDisks();
void printTowerMenu();
};
int Tower::peep()
{
return this->current->value;
}
bool Tower::push(int ele)
{
Disk* temp;
temp=new Disk;
if(current==NULL)
{
temp->next=NULL;
}
else
{
temp->next=current;
}
temp->value=ele;
this->current=temp;
size++;
return false;
}
bool Tower::pop()
{
if(isEmpty())
{
cout<<"\nTower is Empty\n";
return false;
}
else
{
current=current->next;
size=size--;
}
return true;
}
bool Tower::isEmpty()
{
if(getTowerSize()==0)
return true;
return false;
}
int Tower::getTowerSize()
{
return size;
}//returns size of the Tower
void Tower::printTowerSize()
{
cout<<"\nThe Size of the Tower:"<<size<<"\n";
}//print the Tower size
void Tower::printTowerDisks()
{
if(this->isEmpty())
{
cout<<"-----\n";
cout<<" "<<endl;
cout<<"-----\n";
return;
}
Disk *curr2;
curr2=this->current ;
cout<<"-----\n";
cout<<"Tower\n";
cout<<"-----\n";
int i=0;
while(curr2 !=NULL)
{
if(i>4)
break;
i++;
cout<<" |"<<curr2->value<<"|\n";
curr2=curr2->next;
}
}// print the Tower
void createSourceTower(Tower *source,int numberOfDisks)
{
for(int i=numberOfDisks;i>0;i--)
{
source->push(i);
}
}
void moveDisk(Tower *source,Tower *dest) // movinng a disk from source to destionation
{
dest->push(source->current->value );
source->pop();
}
void hanoi( int N, Tower *source, Tower *dest,Tower *aux ) // move N disks from source to destination
{
if (N > 0 )
{
hanoi(N - 1, source, aux, dest); //move n-1 disks from source to auxxilary (sub problem)
moveDisk(source,dest); //move nTH disk from source to destination
hanoi(N - 1, aux, dest, source); //move n-1 disks from auxillary to destination (sub problem)
}
}
void main()
{
Tower *source,*destination,*auxillary;
//Towers required for the 3 towers source destination and auxillary
source=new Tower;
destination=new Tower;
auxillary=new Tower;
//take number of disks from user
int numberOfDisks;
cout<<"Enter number of Disks in the source Tower";
cin>>numberOfDisks;
//inserting the disks into the source tower
createSourceTower(source,numberOfDisks);
cout<<"==============================================="<<endl;
cout<<"Initial Scenario of the Towers "<<endl;
cout<<"Source"<<endl;
source->printTowerDisks ();
cout<<"Auxillary"<<endl;
auxillary->printTowerDisks ();
cout<<"Destination"<<endl;
destination->printTowerDisks ();
hanoi( numberOfDisks,source, destination, auxillary );
cout<<"==============================================="<<endl;
cout<<"Final Scenario of the Towers "<<endl;
cout<<"Source"<<endl;
source->printTowerDisks();
cout<<"Auxillary"<<endl;
auxillary->printTowerDisks ();
cout<<"Destination"<<endl;
destination->printTowerDisks ();
cout<<"==============================================="<<endl;
}
Is Prime Number
#include<iostream.h>
#include <math.h>
void main()
{
int number;
cout<<" ---------------------------------------------"<<endl;
cout<<" Enter a number to find if its a prime number "<<endl;
cout<<" ---------------------------------------------"<<endl;
cin>>number;
bool a =true;
for(int i=2;i<sqrt(number);i++) //check untill the square root
{
if(number%i==0) // if it is divisible it is non prime
{
a=false;
break;
}
}
if(a==false)
cout<<number<<" is not a prime number"<<endl;
else
cout<<number<<" is a prime number"<<endl;
}
GCD (Greatest Common Divisor ) Euclids way
GCD (Greatest Common Divisor ) Euclids way
public class GreatestCommonDivisor {
//using euclid's way of calculating GCD
static int greatestCommonDivisor(int a, int b) {
int gdivisor = 1, divider, dividend;
if (a < b) { // the one less is divisor the one greater is dividend
divider = a;
dividend = b;
}
else {
divider = b;
dividend = a;
}
if (dividend % divider == 0) { //its the GCD
return divider;
}
else { //proceed further
greatestCommonDivisor(divider, dividend % divider);
}
return gdivisor; //the GCD of the 2 numbers
}
public static void main(String args[]) {
System.out.println(greatestCommonDivisor(5, 144));
}
}
GCD (Greatest Common Divisor ) Euclids way
Permutations program in java
class permutations {
static void print(int v[], int n) {
for (int i = 0; i < n; i++) {
System.out.print(v[i] + " ");
}
System.out.println("\n");
}
static void permute(int v[], int start, int n) {
if (start == (n - 1)) {
//if its the end of the sequence genereated then print them
print(v, n);
}
else {
for (int i = start; i < n; i++) {
//swap the start element woith the ith element to get n first sequeces
int temp = v[start];
v[start] = v[i];
v[i] = temp;
permute(v, start + 1, n);
//of the n the first is kept constant the same is applied for the rest sequence
v[i] = v[start];
v[start] = temp;
}
}
}
public static void main(String[] args) {
System.out.println("learn 2day permutaions!");
int v[] = {
1, 2, 3};
//this is the array which should contain the items to be permuted
permute(v, 0, v.length);
}
}
Simple Permutations program in java
Selection Sort
#include <iostream.h>
void selectionSort(int *array,int length)//selection sort function
{
int i,j,min,minat;
for(i=0;i<(length-1);i++)
{
minat=i;
min=array[i];
for(j=i+1;j<(length);j++) //select the min of the rest of array
{
if(min>array[j]) //ascending order for descending reverse
{
minat=j; //the position of the min element
min=array[j];
}
}
int temp=array[i] ;
array[i]=array[minat]; //swap
array[minat]=temp;
}
}
void printElements(int *array,int length) //print array elements
{
int i=0;
for(i=0;i<10;i++)
cout<<array[i]<<endl;
}
void main()
{
int a[]={9,6,5,23,2,6,2,7,1,8}; // array to sort
selectionSort(a,10); //call to selection sort
printElements(a,10); // print elements
}
Count Sort
#include < iostream.h >
#include < stdio.h >
#include < conio.h >
void print(int a[]) {
for (int i = 0; i < 10; i++) {
cout < < a[i] < < "-";
}
cout < < endl;
}
int max(int a[]) {
int mac = 0;
for (int i = 0; i < 10; i++) {
if (a[i] > mac) {
mac = a[i];
}
}
cout < < "ths is mac " < < mac < < endl;
return mac;
}
void countTimes(int a[], int b[]) {
int maxi = max(a);
for (int i = 0; i < = maxi; i++) {
b[i] = 0;
}
for (i = 0; i < 10; i++) {
b[a[i]] = b[a[i]] + 1;
}
}
void countRanks(int b[]) {
for (int i = 1; i < = 7; i++) {
b[i] += b[i - 1];
}
}
void countSort(int a[], int b[], int c[]) {
int l = 0;
for (int i = 9; i >= 0; i--) {
cout < < a[i] < < "-" < < b[a[i]] < < "\n";
c[b[a[i]] - 1] = a[i];
b[a[i]] = b[a[i]] - 1;
}
print(c);
}
void main() {
clrscr();
int a[] = {
1, 2, 4, 6, 7, 7, 0, 6, 3, 5};
print(a);
int * b;
int mac = max(a);
int c[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
b = new int[mac];
countTimes(a, b);
countRanks(b);
countSort(a, b, c);
print(c);
}
Insertion Sort
Insertion Sort in c++
#include < iostream.h >
#include < conio.h >
void sort(int * a) {
for (int j = 2; j < 10; j++) {
for (int k = 0; k < j; k++) {
if (a[j] < a[k]) {
int temp = a[k];
a[k] = a[j];
a[j] = temp;
}
}
}
for (int i = 0; i < 10; i++) {
cout << a[i] << "\n";
}
}
void main() {
clrscr();
int a[] = {
1, 4, 6, 8, 0, 9, 7, 5, 2, 3};
sort(a);
}
Insertion Sort in c++
Subscribe to:
Posts (Atom)