Jumat, 08 Juli 2011

Contoh Program C++ LINKED LIST

Linked list (list bertaut) adalah salah satu struktur data dasar yang sangat fundamental dalam bidang ilmu komputer. Dengan menggunakan linked list maka programmer dapat menimpan datanya kapanpun dibutuhkan. Linked list mirip dangan array, kecuali pada linked list data yang ingin disimpan dapat dialokasikan secara dinamis pada saat pengoperasian program (run-time).

Linked List sering disebut juga Senarai Berantai
Linked List saling terhubung dengan bantuan variabel pointer
Masing-masing data dalam Linked List disebut dengan node (simpul) yang menempati alokasi memori secara dinamis dan biasanya berupa struct yang terdiri dari beberapa field.

Operasi-Operasi yang ada pada Linked List
Insert
Istilah Insert berarti menambahkan sebuah simpul baru ke dalam suatu linked list.
IsEmpty
Fungsi ini menentukan apakah linked list kosong atau tidak.
Find First
Fungsi ini mencari elemen pertama dari linked list
Find Next
Fungsi ini mencari elemen sesudah elemen yang ditunjuk now
Retrieve
Fungsi ini mengambil elemen yang ditunjuk oleh now. Elemen tersebut lalu dikembalikan oleh fungsi.
Update
Fungsi ini mengubah elemen yang ditunjuk oleh now dengan isi dari sesuatu
Delete Now
Fungsi ini menghapus elemen yang ditunjuk oleh now. Jika yang dihapus adalah elemen pertama dari linked list (head), head akan berpindah ke elemen berikut.
Delete Head
Fungsi ini menghapus elemen yang ditunjuk head. Head berpindah ke elemen sesudahnya.
Clear
Fungsi ini menghapus linked list yang sudah ada. Fungsi ini wajib dilakukan bila anda ingin mengakhiri program yang menggunakan linked list. Jika anda melakukannya, data-data yang dialokasikan ke memori pada program sebelumnya akan tetap tertinggal di dalam memori.

Operasi-operasi untuk Stack dengan Linked List
IsEmpty
Fungsi memeriksa apakah stack yang adamasih kosong.
Push
Fungsi memasukkan elemen baru ke dalam stack. Push di sini mirip dengan insert dalam single linked list biasa.
Pop
Fungsi ini mengeluarkan elemen teratas dari stack.
Clear
Fungsi ini akan menghapus stack yang ada.

Operasi-operasi Queue dengan Double Linked List
IsEmpty
Fungsi IsEmpty berguna untuk mengecek apakah queue masih kosong atau sudah berisi data. Hal ini dilakukan dengan mengecek apakah head masih menunjukkan pada Null atau tidak. Jika benar berarti queue masih kosong.
IsFull
Fungsi IsFull berguna untuk mengecek apakah queue sudah penuh atau masih bisa menampung data dengan cara mengecek apakah Jumlah Queue sudah sama dengan MAX_QUEUE atau belum. Jika benar maka queue sudah penuh.
EnQueue
Fungsi EnQueue berguna untuk memasukkan sebuah elemen ke dalam queue (head dan tail mula-mula meunjukkan ke NULL).
DeQueue
Procedure DeQueue berguna untuk mengambil sebuah elemen dari queue. Hal ini dilakukan dengan cara menghapus satu simpul yang terletak paling depan (head).

Single Linked List Circular

Single Linked List Circular (SLLC) adalah Single Linked List yang pointer nextnya menunjuk pada dirinya sendiri. Jika Single Linked List tersebut terdiri dari beberapa node, maka pointer next pada node terakhir akan menunjuk ke node terdepannya.
Pengertian:
Node : rangkaian beberapa simpul
Single : artinya field pointer-nya hanya satu buah saja dan satu arah.
Linked List : artinya node-node tersebut saling terhubung satu sama lain.
Circular : artinya pointer next-nya akan menunjuk pada dirinya sendiri sehingga berputar

Deklarasi:
Deklarasi node dibuat dari struct berikut ini:
typedef struct TNode{
int data;
TNode *next;
};

Pembentukan node baru
Digunakan keyword new yang berarti mempersiapkan sebuah node baru
berserta alokasi memorinya.

TNode *baru;
baru = new TNode;
baru->data = databaru;
baru->next = baru;
Dibutuhkan satu buah variabel pointer: head
Head akan selalu menunjuk pada node pertama
Penambahan data di depan
Penambahan node baru akan dikaitan di node paling depan, namun pada saat pertama kali (data masih kosong), maka penambahan data dilakukan pada head nya.
Pada prinsipnya adalah mengkaitkan data baru dengan head, kemudian head akan menunjuk pada data baru tersebut sehingga head akan tetap selalu menjadi data terdepan. Untuk menghubungkan node terakhir dengan node terdepan dibutuhkan pointer bantu.

Penambahan data di depan

void insertDepan(int databaru){
TNode *baru,*bantu;
baru = new TNode;
baru->data = databaru;
baru->next = baru;
if(isEmpty()==1){
head=baru;
head->next=head;
}
else {
bantu = head;
while(bantu->next!=head){
bantu=bantu->next;
}
baru->next = head;
head = baru;
bantu->next = head;
}
printf(”Data masuk\n“);
}
Penambahan data di belakang
Penambahan data dilakukan di belakang, namun pada saat pertama kali data langsung ditunjuk pada head-nya.
Penambahan di belakang lebih sulit karena kita membutuhkan pointer bantu untuk mengetahui data terbelakang, kemudian dikaitkan dengan data baru. Untuk mengetahui data terbelakang perlu digunakan perulangan.

Penambahan data di belakang

void insertBelakang (int databaru){
TNode *baru,*bantu;
baru = new TNode;
baru->data = databaru;
baru->next = baru;
if(isEmpty()==1){
head=baru;
head->next=head;
}
else {
bantu = head;
while(bantu->next != head){
bantu=bantu->next;
}
bantu->next = baru;
baru->next = head;
}
printf(”Data masuk\n“);
}

Operasi Penghapusan

Penghapusan node dilakukan dengan memutus rantai node kemudian menghapus node. Jika node berada di tengah rangkaian, rangkaian yang terputus perlu disambung kembali. Untuk memudahkan penghapusan simpul dibutuhkan dua cursor sebagai simpul bantu. Selain cursor juga dibutuhkan simpul head sebagai acuan awal simpul dalam rangkaian.

Berikut langkah langkah untuk menghapus simpul dalam rangkaian:
Buat cursor bantu yang menunjuk ke awal node(simpul).
Pindahkan cursor ke node berikutnya
Putus sambungan awal node dengan node berikutnya.
Hapus rangkaian
Jika berada di akhir rangkaian, putuskan dari rangkaian sebelumnya
Jika di tengah rangkaian, pindahkan penunjukan node berikutnya, atau di akhir, atau setelah node yang akan dihapus

Ilustrasi Hapus Depan

void hapusDepan (){
TNode *hapus,*bantu;
if (isEmpty()==0){
int d;
hapus = head;
d = head->data;
if(head->next != head){
bantu = head;
while(bantu->next!=head){
bantu=bantu->next;
}
head = head->next;
delete hapus;
bantu->next = head;
}else{
head=NULL;
}
printf(“%d terhapus\n“,d);
} else printf(”Masih kosong\n“);
}

Ilustrasi Hapus Belakang

void hapusBelakang(){
TNode *hapus,*bantu;
if (isEmpty()==0){
int d;
hapus = head;
if(head->next == head){
head = NULL;
}else{
bantu = head;
while(bantu->next->next != head){
bantu = bantu->next;
}
hapus = bantu->next;
d = bantu->data;
bantu->next = head;
delete hapus;
}
printf(“%d terhapus\n“,d);
} else printf(”Masih kosong\n“);
}

Program C++ untuk Template

Cara mendefinisikan template dalam C++ pada fungsi adalah dengan syntax berikut:

template<class namaTipe>
namaTipe namaFungsi(tipeData1 parameter1, tipeData2 parameter2,...){
//pernyataan fungsi
}


dalam pernyataan fungsi, jika diinginkan menggunakan tipe data dari template, maka dapat digunakan namaTipe. Pada contoh dibawah, namaTipe adalah T yang dapat menggantikan int, long, double, char.


#include<iostream>
using namespace std;

template <class T>
T max(T a[],T n)
{
int max=a[0];
for(int i=0;i<n;i++)
if(a[i]>max) max=a[i];
return(max);
}

template <class T>
T min(T a[],T n)
{
int min=a[0];
for(int i=0;i<n;i++)
if(a[i]<min) min=a[i];
return(min);
}

main()
{
int x[] = {1,3,20,4,5,6};
int mx = max(x,6);
int mn = min(x,6);
cout<<"\nMax = "<<mx<<endl;
cout<<"\nMin = "<<mn<<endl;
}

graph using C++

<code>#ifndef GRAPH_H_
#define GRAPH_H_

/*
* This file has declarations for classes used to represent the graph
*/

#include <vector>
#include <stack>
#include <string>
#include <iostream>

using namespace std;

//enum for the status of a node
enum Status {
NOT_VISITED,
VISITED
};

//forward declaration
class Node;

//An object of this class represents an edge in the graph.
class Edge
{
private:
Node *orgNode;//the originating vertex
Node *dstNode;//the destination vertex
unsigned cost;//cost of the edge

public:
Edge(Node *firstNode, Node *secNode, unsigned inCost)
{
orgNode = firstNode;
dstNode = secNode;
cost = inCost;
}

Node* getDstNode()
{
return dstNode;
}

Node* getOrgNode()
{
return orgNode;
}

unsigned getCost()
{
return cost;
}
};

//An object of this class holds a vertex of the graph
class Node
{
private:
string name;
vector<Edge> adjNodeList;//list of outgoing edges for this vertex
enum Status status;//used in dfs to mark the node visited

public:
Node(string id)
{
name = id;
status = NOT_VISITED;
}

//do not del the adj nodes here...they will be deleted by graph destructor
~Node()
{
adjNodeList.clear();
}

enum Status getStatus()
{
return status;
}

void setStatus(enum Status st)
{
status = st;
}

string getName()
{
return name;
}

void addAdjNode(Node *adj, unsigned cost)
{
//create an edge with 'this' as the originating node and adj as the destination node
Edge newEdge(this, adj, cost);
adjNodeList.push_back(newEdge);
}

vector<Edge>& getAdjNodeList()
{
return adjNodeList;
}

//displays all adjacent verticies of this vertex
void displayList()
{
string edgeOp = " -> " ;
for(int i=0 ; i < adjNodeList.size() ; i++)
{
Edge edg = adjNodeList[i];
cout << name << " -> " << edg.getDstNode()->getName() << endl ;
}

}
};

//An object of class graph holds a directed graph
class Graph
{
private:
vector<Node*> nodeList;//list of verticies
bool foundCycle;//true if a cycle is found, false otherwise
int desiredCycSize;

void clearVisited()
{
for(int i = 0; i < nodeList.size() && !foundCycle ; i++)
{
nodeList[i]->setStatus(NOT_VISITED);
}
}

void addNewNode(Node *nNode)
{
nodeList.push_back(nNode);
}

Node* findNodeByName(string name)
{
for(int i = 0 ; i < nodeList.size() ; i++)
{
if(nodeList[i]->getName() == name)
return nodeList[i];
}
return NULL;
}

public:
Graph()
{
foundCycle = false;
}

~Graph()
{
//free mem allocated to verticies
for(int i=0 ; i < nodeList.size() ; i++)
delete nodeList[i];
nodeList.clear();
}


void displayGraph()
{
for(int i=0 ; i < nodeList.size() ; i++)
{
nodeList[i]->displayList();
}
}

void readFlightSchedules() {

unsigned numOfCities, numOfFlights, cycSize;
//read in number of cities(TODO:in current implementation..not reqd), number of edges and the desired tour size
cin >> numOfCities >> numOfFlights >> cycSize;

while(numOfFlights--)
{
string fromCity, toCity;
unsigned cost;

cin >> fromCity >> toCity >> cost;
//find if a vertex for the city already exists, if so get that
Node *u = findNodeByName(fromCity);
if(u == NULL)
{
u = new Node(fromCity);
addNewNode(u);
}

//find if a vertex for the city already exists, if so get that
Node *v = findNodeByName(toCity);
if(v == NULL)
{
v = new Node(toCity);
addNewNode(v);
}

u->addAdjNode(v,cost);
}
desiredCycSize = cycSize;
}

};
#endif</code>
Hey there I wrote this code some time back for solving a min distance problem or sth like that....
It goes like this..
Make a node class with whatever you want to put in Make edge class as they really help in simplifying the work..
Make a generic class graph which takes inserts and deletes node...
Make any other functions which you want...
As you can see the code is not all that well written but it was done in the midst of an competition in less than a couple of hours...

Program c++ untuk mencari faktorial

#include<iostream> using namespace std;
float factorial(float n)
{

if(n>1)
return n*factorial(n-1);
else
return 1;
}
main()
{

float fac,n;
cout<<"\nMasukkan sebuah angka:\n ";
cin>>n;
cout<<"Faktorialdari "<<n<<" adalah "<<factorial(n)<<endl; }


Program diatas hanya terdiri dari 2 fungsi:
- factorial(float n)
- main()

Fungsi factorial(float n) hanya terdiri dari 4 baris yang sangat pendek. Namun untuk memahaminya, kita perlu memahami fungsi rekursif.

Pada baris pertama statement fungsi, diperiksa apakah n lebih besar dari 1. Jika ya, maka fungsi factorial akan memangil dirinya sendiri dengan argumen n-1. Hal ini akan dilakukan secara terus menerus selama n lebih besar dari 1. Setelah n mencapai 1, maka kondisi if(n>1) ini bernilai salah dan fungsi factorial memberikan return value 1 (tidak memanggil dirinya sendiri lagi).

Untuk lebih jelasnya kita lihat contoh berikut:
misalkan kita masukkan n=3 pada fungsi factorial, sehingga

factorial(3) = 3*factorial(2)......................................(1)
factorial(2) = 2*factorial(1).......................................(2)
factorial(1) = 1..........................................................(3)

Dengan mensubtitusi factorial(1) pada persamaan (2) ke persamaan (3) kita dapatkan:

factorial(2) = 2*1

Dengan mensubtitusi factorial(2) pada persamaan (2) ke persamaan (1) kita dapatkan:

factorial(3) = 3*2*1

Oleh karena itu kondisi (n>1) juga disebut stop condition pada fungsi rekursif karena setelah n=1 fungsi factorial tidak lagi rekursif dan memberikan return value tertentu.

Help With Binary Search Program

HI, everyone. I am having trouble getting the index of the location of the search number to print out. This is my program. Any help would be greatly appreciated!

C++ Syntax (Toggle Plain Text)
#include<iostream.h>
#include<cmath>
void sortit(int x[], int n)
{
int temp,i,j;
for(i=0;i<n;i++)
for(j=i;j<n;j++)
if(x[i]>x[j])
{
temp=x[i];
x[i]=x[j];
x[j]=temp;
}
}
void bsearch(int x[], int max, int searchnum)
{
int mid;
int high=0;
int size;
int low = size-1;
int location = -1;
int found;
while(high <=low && found==false)
{
mid=(high + low)/2;
if(x[mid]==searchnum)
location=mid;
found=true;
else if(searchnum>>x[mid])
high=(mid + 1);
else
low= (mid - 1);
}
}
main()
{
int num[11];
int max=10;
int i,mid,x,location;
int searchnum;
int found;
for(i=0;i<11;i++)
{
cin>>num[i]; //
}
sortit(num,max);
cout<<"The list sorted is: "<<endl;
for(int i=0;i<max;i++)
cout<<num[i]<<"\n";
while(cin>>searchnum)
{
bsearch(num,max,searchnum);
}
cout<<"The number is " <<searchnum<<endl;
if(found=true)
cout<<"The number was found at location" <<location<<endl;
else cout<<"Number not found" <<"\n";
}

Minggu, 03 Juli 2011

Decimal to binary | convert in c

how to convert | decimal number to binary number in c language
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a,i=0,n,bin=0,r;
clrscr();
printf("enter the decimal no \n");
scanf("%d",&n);
while(n != 0)
{
r=n%2;
// a=pow(10,i);
bin=bin+(pow(10,i)*r);
i++;
n=n/2;
}
printf("binary no.=%d \n",bin);
printf("enter the binary no \n");
scanf("%d",&n);
i=0;
bin=0;
while(n != 0)
{
r=n%10;
bin=bin+(pow(2,i)*r);
i++;
n=n/10;
}
printf("decimal no.=%d",bin);

getch();
}

c program reverse number

Reverse function code
#include<stdio.h>
#include<conio.h>
#include<math.h>
long int rev (int);
void main() //rev=function//
{
int num,reverse;
clrscr();
printf("enter the numbet");
scanf("%d",&num);
reverse=rev(num);
printf("rev of %d is %d" , num,reverse);
getch();
}
long int rev(int x)
{
int r;
long int rev=0;
while(x!=0)
{
r=x%10;
rev=rev*10+r;
x/=10;
}
return(rev);
}

c program reverse number

Reverse function code
#include<stdio.h>
#include<conio.h>
#include<math.h>
long int rev (int);
void main() //rev=function//
{
int num,reverse;
clrscr();
printf("enter the numbet");
scanf("%d",&num);
reverse=rev(num);
printf("rev of %d is %d" , num,reverse);
getch();
}
long int rev(int x)
{
int r;
long int rev=0;
while(x!=0)
{
r=x%10;
rev=rev*10+r;
x/=10;
}
return(rev);
}

How to import java.awt.event

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code = "Assign" width = "500" height = "300">
</applet>
*/

public class Assign extends Applet implements ActionListener
{
Button b1;
Button b2;
List l1;
List l2;
String str = "";
String msg = "";
Font f1;
public void init()
{
setBackground(Color.BLACK);
setForeground(Color.RED);
f1 = new Font("Times New Roman",Font.BOLD,20);
setFont(f1);
l1 = new List(4,false);
l2 = new List(4,false);
l1.add("DBMS");
l1.add("MIS");
l1.add("SE");
l1.add("C");
l1.add("ORACLE");
l1.add("VB");
l1.add("D.S");
l1.add("B.A");
b1 = new Button(">>");
b2 = new Button("<<");
add(l1);
add(b1);
add(b2);
add(l2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
repaint();
}

public void paint(Graphics g)
{
msg = l1.getSelectedItem();
l2.add(msg,0);
l1.remove(msg);
}
}

student record in college using c++

A gramophone record, commonly known as a phonograph record (in American English), vinyl record (in reference to vinyl), or colloquially, a record, is an analog sound storage medium consisting of a flat disc with an inscribed, modulated spiral groove. The groove usually starts near the periphery and ends near the center of the disc (the opposite of the spiral of pits in the CD medium, which starts near the centre and works outwards). Phonograph records are generally described by the size of their diameter ("12-inch", "10-inch", "7-inch", etc.), the rotational speed at which they are played ("33⅓ r.p.m.", "78", "45", etc.), their time capacity ("Long Playing"), their reproductive accuracy, or "fidelity", or the number of channels of audio provided ("Mono", "Stereo", "Quadraphonic", etc.).

Gramophone records were the primary medium used for popular music reproduction for most of the 20th century, replacing the phonograph cylinder, with which it had co-existed, by the 1920s. By the late 1980s, digital media had gained a larger market share, and the vinyl record left the mainstream in 1991.[1][2] However, they continue to be manufactured and sold in the 21st century. The vinyl record regained popularity by 2008, with nearly 2.9 million units shipped that year, the most in any year since 1998.[3] They are especially used by DJs and audiophiles for many types of music. As of 2011, vinyl records continue to be used for distribution of independent and alternative music artists. More mainstream pop music releases tend to be mostly sold in compact disc or other digital formats, but have still been released in vinyl in certain instances.
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<iomanip.h>

class stud
{
int rno,dbms,c,cpp,vb,total;
char grade[5],name[10];
float avg;
public:
void getdata();
void putdata();
};

void stud::getdata()
{
char ch;
cout<<"Roll No.:" <<endl;
cin>>rno;
cin.get(ch);
cout<<" Name:" <<endl;
cin.getline(name,10);
cout<<"Marks of DBMS:"<<endl;
cin>>dbms;
cout<<"Marks of C:"<<endl;
cin>>c;
cout<<"Marks of CPP:"<<endl;
cin>>cpp;
cout<<"Marks of VB:"<<endl;
cin>>vb;
total=dbms+c+cpp+vb;
avg=total/4.0;

if(avg>=70)
strcpy(grade,"A+");
if(avg>60 && avg<=60)
strcpy(grade,"A");
if(avg>60 && avg<=55)
strcpy(grade,"B");
if(avg<55 && avg>=35)
strcpy(grade,"C");
if(avg<35)
strcpy(grade,"F");
}
void stud :: putdata()
{
cout<<setw(5)<<rno<<setw(10)<<name<<setw(5)<<dbms<<setw(5)<<c<<setw(5)<<cpp<<setw(5)<<vb<<setw(8)<<total<<setw(10)<<avg<<setw(8)<<grade<<"\n";
}
void main()
{
stud ob[2];
int i;
clrscr();
cout<<"Enter the record of student \n \n";
for(i=0;i<2;i++)
{ ob[i].getdata();
}
cout<<"Records of students:\n\n";
cout<<setw(5)<<"R_NO."<<setw(10)<<"NAME"<<setw(5)<<"DBMS"<<setw(5)<<"C"<<setw(5)<<"CPP"<<setw(5)<<"VB"<<setw(8)<<"TOTAL"<<setw(10)<<"AVG"<<setw(8)<<"GRADE"<<endl;
for(i=0;i<2;i++)
{
ob[i].putdata();
}
getch();
}

Kombinasi dan Program Aplikasinya Menggunakan C++

Kombinasi adalah menggabungkan beberapa objek dari suatu grup tanpa memperhatikan urutan. Sebagai contoh suatu himpunan {1,2,3} adalah sama dengan himpunan {2,3,1} dan {3,1,2}.

Contoh: Seorang anak hanya diperbolehkan mengambil dua buah amplop dari tiga buah amplop yang disediakan yaitu amplop A, amplop B dan amplop C. Tentukan ada berapa banyak kombinasi untuk mengambil dua buah amplop dari tiga buah amplop yang disediakan?
Jawaban: Ada 3 kombinasi yaitu:
1. AB atau BA, karena pengambilan amplop A dan B sama dengan pengambilan B dan A.
2. AC atau CA.
3. BC atau CB.

Salah satu aplikasi kombinasi digunakan untuk mencari peluang suatu kejadian atau menghitung kombinasi kejadian tertentu. Kombinasi dari n dan r kita bisa notasikan nCr, dirumuskan dengan:

nCr = n faktorial/(r factorial * (n-r) faktorial)
dimana n faktorial = n! = 1 * 2 * 3 * … * n.

Misalkan dalam suatu pertemuan arisan keluarga terdapat 7 orang yang melakukan jabat tangan. Berapa jumlah jabat tangan yang dilakukan oleh 7 orang tersebut?
Jawaban:
Diketahui n=7; r=2;
Maka 7 C 2 = 7! /(2! * (7-2)!)
= 5040/(2*120)
= 21 kali jabat tangan.

Kejadian tersebut dapat kita hitung dengan mengunkan rumus kombinasi, karena pada jabat tangan tersebut tidak memperhatikan urutan jabat tangan, maksudnya jabat tangan antara Budi dan Iwan adalah sama urutannya dengan jabat tangan antar Iwan dan Budi.
Dengan bahasa pemograman C++, kita dapat membuat sebuah aplikasi yang dapat mengitung nilai Kombinasi dari dua nilai missal n dan r.

Dibawah ini saya lampirkan sebuah program dengan menggunakan bahasa pemrograman C++ untuk menghitung Combinasi, dimana program tersebut terdiri dari beberapa fungsi yaitu:
1. Fungsi untuk menghitung Faktorial, dan
2. Fungsi untuk menghitung Kombinasi.

Contoh program Kombinasi dengan C++
/*
Deskripsi : Program untuk menghitung nilai Kombinasi dari nCr
Pembuat : Wawan Hendriawan Nur
Tanggal : 15 November 2007
*/

#include
#include

int factorial(int n); //Fungsi untuk menghitung nilai faktorial
int combination(int, int); //fungsi untuk mengitung nilai kombinasi nCr

main()
{ int n,r; //dekalasi variabel
cout <<”Masukan nilai n: “; cin >> n; //input nilai n
cout <<”Masukan nilai r: “; cin >> r; //input nilai r
cout <=1;
}

//Fungsi untuk menghitung nilai Kombinasi nCr
int combination(int n, int r)
{ int f1 = factorial(n); //hitung nilai faktorial n
int f2 = factorial(r); //hitung nilai faktorial r
int f3 = factorial(n-r); //hitung nilai faktorial (n-r)
//mengembalikan nilai Kombinasi, C=(n!/(n!*(n-r)!)))
return (f1/(f2*f3));
}

Linear programming

Linear programming (LP, or linear optimization) is a mathematical method for determining a way to achieve the best outcome (such as maximum profit or lowest cost) in a given mathematical model for some list of requirements represented as linear relationships. Linear programming is a specific case of mathematical programming (mathematical optimization).

More formally, linear programming is a technique for the optimization of a linear objective function, subject to linear equality and linear inequality constraints. Its feasible region is a convex polyhedron, which is a set defined as the intersection of finitely many half spaces, each of which is defined by a linear inequality. Its objective function is a real-valued affine function defined on this polyhedron. A linear programming algorithm finds a point in the polyhedron where this function has the smallest (or largest) value if such point exists.

Linear programs are problems that can be expressed in canonical form:


where x represents the vector of variables (to be determined), c and b are vectors of (known) coefficients and A is a (known) matrix of coefficients. The expression to be maximized or minimized is called the objective function (cTx in this case). The equations Ax ≤ b are the constraints which specify a convex polytope over which the objective function is to be optimized. (In this context, two vectors are comparable when every entry in one is less-than or equal-to the corresponding entry in the other. Otherwise, they are incomparable.)

Linear programming can be applied to various fields of study. It is used most extensively in business and economics, but can also be utilized for some engineering problems. Industries that use linear programming models include transportation, energy, telecommunications, and manufacturing. It has proved useful in modeling diverse types of problems in planning, routing, scheduling, assignment, and design.

Standard form is the usual and most intuitive form of describing a linear programming problem. It consists of the following four parts:
A linear function to be maximized
e.g.
Problem constraints of the following form
e.g.

Non-negative variables
e.g.

Non-negative right hand side constants


The problem is usually expressed in matrix form, and then becomes:


Other forms, such as minimization problems, problems with constraints on alternative forms, as well as problems involving negative variables can always be rewritten into an equivalent problem in standard form.

#include <stdio.h>
#include <math.h>

float a, c, b, F_a, F_c, F_b, tol;
int max_iter;
float f(float x)
{
return ((x*x)*x) + (x*x)- (3*x) – 3;
}

void main ()
{
int it;
float epsilon;
printf(” METODE REGULASI FALSI”);
printf(“\n”);
printf(“Contoh Soal\n”);
printf(“3*x*x – 2*x – 5 \n\n”);
printf(“Masukkan Batas Bawah :”);
scanf(“%f”,&a);
printf(“Masukkan Batas Atas :”);
scanf(“%f”,&b);
printf(“Masukkan Toleransi Error :”);
scanf(“%f”,&tol);

it = 0;
F_a = f(a);
F_b = f(b);
if(F_a * F_b > 0) printf(” Nilai F(a) x F(b) > 0\n”);
else
{
printf(“\n”);
printf(” I a f(a) b f(b) c f(c)\n\n”);
do
{
it = it +1;
c = a – F_a * (b-a) / (F_b – F_a);
F_c = f(c);
printf(“%2d %7.5f %7.5f %7.5f %7.5f %7.5f %7.2e\n\n”,it, a, F_a, b, F_b, c,fabs(F_b-F_a)/2);
epsilon = fabs(c-a);
if(F_a * F_c <=0){ b = c; F_b = F_c; }
else
{
a=c;
F_a=F_c;
}
}

while(epsilon > tol);
if(epsilon <=tol)
{
printf(“\n”);
printf(“\n”);
printf(“Toleransi terpenuhi\n”);
printf(“\n”);
printf(“Hasil akhir=%g\n\n\n”,c);

}

else
printf(“Toleransi tidak terpenuhi\n”);
}

}

Program Menghitung Permutasi dengan C++

pada kali ini saya akan memposting sebuah program untuk menghitung nilai permutasi.Untuk menghitung nilai permutasi kita menggunakan program sebelumnya yaitu prorgam menghitung faktorial.Kenapa kita menggunakan program sebelumnya??jawabannya adalah dalam perhitungan permutasi kita juga menghitung faktorial bilangan n dan bilangan r karena rumus permutasi adalah nfaktorial/(nfaktorial-rfaktorial).

untuk lebih jelasnya silakan teman-teman melihat programnya di bawah ini.

//MENGHITUNG PERMUTASI

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
int nfakt,nrfakt,per;
int n,r;
nfakt=1;
nrfakt=1;

cout<<”\t\t\tMENGHITUG NILAI PERMUTASI”<<endl;
cout<<”\t\t======================================”<<endl;
cout<<endl;
cout<<”masukkan nilai n:”;
cin>>n;
cout<<”masukkan nilai r:”;
cin>>r;

for(int i=n;i>0;i–)
{
nfakt=nfakt*i;
}
for(int i=n-r;i>0;i–)
{
nrfakt=nrfakt*i;
}

per=nfakt/nrfakt;

cout<<”nilai permutasinya adalah:”<<per<<endl;
cout<<endl;
system(“PAUSE”);
return EXIT_SUCCESS;
}