If2225d - Tugas 6 & 7 - 3411181167

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

TUGAS PERTEMUAN 6 DAN 7

ANALISIS DAN PERANCANGAN ALGORITMA

Review Ulang Algoritma Greedy dan Penerapannya

Disusun oleh :

Anissa Azhari

3411181167

PROGRAM STUDI INFORMATIKA


FAKULTAS SAINS DAN INFORMATIKA
UNIVERSITAS JENDERAL ACHMAD YANI
2020
DAFTAR ISI

DAFTAR ISI..................................................................................................................i
1. Soal 1.....................................................................................................1
2. Soal 2.....................................................................................................4
3. Soal 3.....................................................................................................7
4. Soal 4.....................................................................................................8
5. Soal 5...................................................................................................12
6. Soal 6...................................................................................................14

i
1. Soal 1

a. Source Code
package tugas8;
import java.util.ArrayList;
import java.util.List;

public class Knapsack {


// items of our problem
private Item[] items;
// capacity of the bag
private int capacity;

public Knapsack(Item[] items, int capacity) {


this.items = items;
this.capacity = capacity;
}

public void display() {


if (items != null && items.length > 0) {
System.out.println("Knapsack problem");
System.out.println("Capacity : " +
capacity);
System.out.println("Items :");

for (Item item : items) {


System.out.println("- " +
item.str());
}
}
}
// we write the solve algorithm
public Solution solve() {
int NB_ITEMS = items.length;
// we use a matrix to store the max value at each
n-th item
int[][] matrix = new int[NB_ITEMS + 1][capacity +
1];
// first line is initialized to 0
for (int i = 0; i <= capacity; i++)
matrix[0][i] = 0;
// we iterate on items
for (int i = 1; i <= NB_ITEMS; i++) {
// we iterate on each capacity

1
for (int j = 0; j <= capacity; j++) {
if (items[i - 1].weight > j)
matrix[i][j] = matrix[i-1]
[j];
else
// we maximize value at this
rank in the matrix
matrix[i][j] =
Math.max(matrix[i-1][j], matrix[i-1][j - items[i-1].weight]
+ items[i-1].value);
}
}
int res = matrix[NB_ITEMS][capacity];
int w = capacity;
List<Item> itemsSolution = new ArrayList<>();
for (int i = NB_ITEMS; i > 0 && res >
0; i--) {
if (res != matrix[i-1][w]) {
itemsSolution.add(items[i-
1]);
// we remove items value and
weight
res -= items[i-1].value;
w -= items[i-1].weight;
}
}
return new Solution(itemsSolution,
matrix[NB_ITEMS][capacity]);
}

public static void main(String[] args) {


// we take the same instance of the problem
displayed in the image
Item[] items = {new Item("O1", 11, 6),
new Item("O2", 23, 9),
new Item("O3", 1, 4),
new Item("O4", 5, 12),
new Item("O5", 9, 10),
new Item("O6", 20, 3),
new Item("O7", 32, 2),
new Item("O8", 15, 1)};

Knapsack knapsack = new Knapsack(items, 30);


knapsack.display();
Solution solution = knapsack.solve();
solution.display();
}
}

package tugas8;

public class Item {


public String name;
public int value;
public int weight;

2
public Item(String name, int value, int weight) {
this.name = name;
this.value = value;
this.weight = weight;
}

public String str() {


return name + " [profit = " + value + ", weight
= " + weight + "]";
}
}

package tugas8;

import java.util.List;

public class Solution {


// list of items to put in the bag to have the
maximal value
public List<Item> items;
// maximal value possible
public int value;

public Solution(List<Item> items, int value) {


this.items = items;
this.value = value;
}

public void display() {


if (items != null && !items.isEmpty()){
System.out.println("\nKnapsack
solution");
System.out.println("Value = " + value);
System.out.println("Items to pick :");

for (Item item : items) {


System.out.println("- " +
item.str());
}
}
}
}

b. Hasil Eksekusi Program

3
2. Soal 2

a. Source Code

package tugas8;
import java.util.*;
public class Job {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of Jobs");
int n=sc.nextInt();
String a[]=new String[n];
int b[]=new int[n];
int c[]=new int[n];
for(int i=0;i<n;i++){
System.out.println("Enter the Jobs");
a[i]=sc.next();
System.out.println("Enter the Profit");
b[i]=sc.nextInt();
System.out.println("Enter the DeadLine");
c[i]=sc.nextInt();
}
System.out.println("--Arranged Order--");

4
System.out.print("Jobs: ");
for(int i=0;i<n;i++){
System.out.print(a[i]+" ");
}
System.out.println();
System.out.print("Profit: ");
for(int i=0;i<n;i++){
System.out.print(b[i]+" ");
}
System.out.println();
System.out.print("DeadLine:");
for(int i=0;i<n;i++){
System.out.print(c[i]+" ");
}
for(int i=0;i<n-1;i++){
for(int j=i+1;j<n;j++){
if(b[i]<b[j]){
int temp=b[i];
b[i]=b[j];
b[j]=temp;
temp=c[i];
c[i]=c[j];
c[j]=temp;
String temp1=a[i];
a[i]=a[j];
a[j]=temp1;
}
}
}
System.out.println();
System.out.println("--Sorted Order--");
System.out.print("Jobs: ");
for(int i=0;i<n;i++){
System.out.print(a[i]+" ");
}
System.out.println();
System.out.print("Profit: ");
for(int i=0;i<n;i++){
System.out.print(b[i]+" ");
}
System.out.println();
System.out.print("DeadLine:");
for(int i=0;i<n;i++){
System.out.print(c[i]+" ");
}
System.out.println();
int max=c[0];
for(int i=0;i<n;i++){
if(c[i]>max){
max=c[i];
}
}
String x[]=new String[max];
int xx[]=new int[max];
int profit=0;
for(int i=0;i<n;i++){
int pp=c[i];
pp=pp-1;
if(x[pp]==null ){

5
x[pp]=a[i];
profit+=b[i];
}else{
while(pp!=-1){
if(x[pp]==null){
x[pp]=a[i];
profit+=b[i];
break;
}
pp=pp-1;
}
}
}
for(int i=0;i<max;i++){
System.out.print("-->"+x[i]);
}
System.out.println();
System.out.print("Profit Earned"+profit);
}
}

b. Hasil Eksekusi Program

6
3. Soal 3

a. Source Code

package tugas8;
import java.util.Scanner;
import java.util.PriorityQueue;
public class Merge {
//Function to find minimum computation
static int minComputation(int size, int files[]){
// create a min heap
PriorityQueue<Integer> pq = new
PriorityQueue<>();
for (int i = 0; i < size; i++) {
// add sizes to priorityQueue
pq.add(files[i]);
}
// variable to count total computations
int count = 0;
while (pq.size() > 1) {
int temp = pq.poll() + pq.poll();
count += temp;
pq.add(temp);
}
return count;

7
}

public static void main(String[] args) {


// TODO Auto-generated method stub
int size = 6;
// 6 files with their sizes
int files[] = new int[] { 3, 10, 20 , 5 , 25 ,
15};
System.out.println("Optimal merge Cost= "+
minComputation(size, files));
}

b. Hasil Eksekusi Program

4. Soal 4

a. Source Code

package tugas8;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.TreeMap;

public class Huffman {


static final boolean readFromFile = false;
static final boolean newTextBasedOnOldOne = false;

static PriorityQueue<Node> nodes = new


PriorityQueue<>((o1, o2) -> (o1.value < o2.value) ? -1 :
1);

8
static TreeMap<Character, String> codes = new
TreeMap<>();
static String text = "";
static String encoded = "";
static String decoded = "";
static int ASCII[] = new int[128];

public static void main(String[] args) throws


FileNotFoundException {
Scanner scanner = (readFromFile) ? new Scanner(new
File("input.txt")) : new Scanner(System.in);
int decision = 1;
while (decision != -1) {
if (handlingDecision(scanner, decision))
continue;
}
}

private static boolean handlingDecision(Scanner


scanner, int decision) {
if (decision == 1) {
if (handleNewText(scanner)) return true;
}
return false;
}

private static boolean handleNewText(Scanner scanner) {


int oldTextLength = text.length();
System.out.println("Enter the text:");
text = scanner.nextLine();
if (newTextBasedOnOldOne && (oldTextLength != 0
&& !IsSameCharacterSet())) {
System.out.println("Not Valid input");
text = "";
return true;
}
ASCII = new int[128];
nodes.clear();
codes.clear();
encoded = "";
decoded = "";
System.out.println("Text: " + text);
calculateCharIntervals(nodes, true);
buildTree(nodes);
generateCodes(nodes.peek(), "");

printCodes();
System.out.println("-- Encoding/Decoding --");
encodeText();
decodeText();
return false;
}

private static boolean IsSameCharacterSet() {


boolean flag = true;
for (int i = 0; i < text.length(); i++)
if (ASCII[text.charAt(i)] == 0) {

9
flag = false;
break;
}
return flag;
}

private static void decodeText() {


decoded = "";
Node node = nodes.peek();
for (int i = 0; i < encoded.length(); ) {
Node tmpNode = node;
while (tmpNode.left != null && tmpNode.right !=
null && i < encoded.length()) {
if (encoded.charAt(i) == '1')
tmpNode = tmpNode.right;
else tmpNode = tmpNode.left;
i++;
}
if (tmpNode != null)
if (tmpNode.character.length() == 1)
decoded += tmpNode.character;
else
System.out.println("Input not Valid");
}
System.out.println("Decoded Text: " + decoded);
}

private static void encodeText() {


encoded = "";
for (int i = 0; i < text.length(); i++)
encoded += codes.get(text.charAt(i));
System.out.println("Encoded Text: " + encoded);
}

private static void buildTree(PriorityQueue<Node>


vector) {
while (vector.size() > 1)
vector.add(new Node(vector.poll(),
vector.poll()));
}

private static void printCodes() {


System.out.println("--- Printing Codes ---");
codes.forEach((k, v) -> System.out.println("'" + k
+ "' : " + v));
}

private static void


calculateCharIntervals(PriorityQueue<Node> vector, boolean
printIntervals) {
for (int i = 0; i < text.length(); i++)
ASCII[text.charAt(i)]++;

for (int i = 0; i < ASCII.length; i++)


if (ASCII[i] > 0) {
vector.add(new Node(ASCII[i] /
(text.length() * 1.0), ((char) i) + ""));

10
}
}

private static void generateCodes(Node node, String s)


{
if (node != null) {
if (node.right != null)
generateCodes(node.right, s + "1");

if (node.left != null)
generateCodes(node.left, s + "0");

if (node.left == null && node.right == null)


codes.put(node.character.charAt(0), s);
}
}
}

class Node {
Node left, right;
double value;
String character;

public Node(double value, String character) {


this.value = value;
this.character = character;
left = null;
right = null;
}

public Node(Node left, Node right) {


this.value = left.value + right.value;
character = left.character + right.character;
if (left.value < right.value) {
this.right = right;
this.left = left;
} else {
this.right = left;
this.left = right;
}
}
}

b. Hasil Eksekusi Program

11
5. Soal 5

a. Source Code

package tugas8;

import java.io.*;
import java.util.*;
import java.lang.*;

class MST{
private static final int V = 5;
int minKey(int key[], Boolean mstSet[]){
// Initialize min value
int min = Integer.MAX_VALUE, min_index = -1;
for (int v = 0; v < V; v++){
if (mstSet[v] == false && key[v] < min) {
min = key[v];
min_index = v;
}
}
return min_index;
}

void printMST(int parent[], int graph[][]){


System.out.println("Simpul \tBobot");
for (int i = 1; i < V; i++){
System.out.println(parent[i] + " - " + i +
"\t" + graph[i][parent[i]]);

12
}
}

void primMST(int graph[][]){


int parent[] = new int[V];
int key[] = new int[V];

Boolean mstSet[] = new Boolean[V];

for (int i = 0; i < V; i++) {


key[i] = Integer.MAX_VALUE;
mstSet[i] = false;
}

key[0] = 0;
parent[0] = -1;

for (int count = 0; count < V - 1; count++){


int u = minKey(key, mstSet);
mstSet[u] = true;

for (int v = 0; v < V; v++) {


if (graph[u][v] != 0 && mstSet[v] == false
&& graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}
printMST(parent, graph);
}

public static void main(String args[]){


System.out.println("Keterangan:\n0 = A\n1 = B\n2 =
C\n3 = D\n4 = E");
MST t = new MST();
int graph[][] = new int[][] { { 0, 15, 25, 0, 20 },{
15, 0, 10, 0, 0 },
{ 25, 10, 0, 32, 30 },{ 0, 0, 32,
0, 15 },
{ 20, 0, 30, 15, 0 } };
t.primMST(graph);
}
}

b. Hasil Eksekusi Program

13
6. Soal 6

a. Source Code

14
package tugas8;

import java.util.*;
import java.lang.*;
import java.io.*;

class ShortestPath {
// Fungsi utilitas untuk menemukan simpul dengan
nilai jarak minimum,
// dari himpunan simpul yang belum termasuk dalam
pohon jalur terpendek
static final int V = 6;
int minDistance(int dist[], Boolean sptSet[])
{
// Inisialisasi nilai min
int min = Integer.MAX_VALUE, min_index = -1;

for (int v = 0; v < V; v++)


if (sptSet[v] == false && dist[v] <=
min) {
min = dist[v];
min_index = v;
}

return min_index;
}

// Fungsi utilitas untuk mencetak array jarak yang


dibuat
void printSolution(int dist[])
{
System.out.println("Puncak \t\t Jarak dari
Sumber");
for (int i = 0; i < V; i++)
System.out.println(i + " \t\t " +
dist[i]);
}

// Fungsi yang mengimplementasikan jalur terpendek


sumber tunggal Dijkstra
// algoritma untuk grafik direpresentasikan
menggunakan matriks adjacency
// perwakilan
void dijkstra(int graph[][], int src)
{
int dist[] = new int[V]; // The output array.
dist[i] will hold
// jarak terpendek dari src ke i

// sptSet [i] akan benar jika simpul saya


termasuk dalam terpendek
// jalur pohon atau jarak terdekat dari src ke
i telah selesai
Boolean sptSet[] = new Boolean[V];

// Inisialisasi semua jarak sebagai INFINITE


dan stpSet [] sebagai false
for (int i = 0; i < V; i++) {
dist[i] = Integer.MAX_VALUE;

15
sptSet[i] = false;
}

// Jarak titik sumber dari dirinya sendiri


selalu 0
dist[src] = 0;

// Temukan jalur terpendek untuk semua simpul


for (int count = 0; count < V - 1; count++) {
// Pilih titik jarak minimum dari
himpunan titik
// belum diproses. kamu selalu sama
dengan src di pertama
// pengulangan.
int u = minDistance(dist, sptSet);

// Tandai vertex yang dipilih sebagai


diproses
sptSet[u] = true;

// Perbarui nilai dist dari simpul yang


berdekatan dari
// picked vertex.
for (int v = 0; v < V; v++)

// Perbarui dist [v] hanya jika


tidak di sptSet, ada
// tepi dari u ke v, dan total
bobot jalur dari src ke
// v through u lebih kecil dari
nilai saat ini dari dist [v]
if (!sptSet[v] && graph[u][v] != 0
&& dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] <
dist[v])
dist[v] = dist[u] + graph[u]
[v];
}

// cetak array jarak yang dibangun


printSolution(dist);
}

// Driver method
public static void main(String[] args)
{
/* Mari kita buat contoh grafik yang dibahas
di atas */
int graph[][] = new int[][] {
{ 0,
2, 0, 4, 0, 0},
{ 2,
0, 7, 1, 0, 0},
{ 0,
7, 0, 0, 2, 1},
{ 4,
1, 0, 0, 3, 0},
{ 0,
0, 2, 3, 0, 5},
{ 0,

16
0, 1, 0, 5, 0},

};
ShortestPath t = new ShortestPath();
t.dijkstra(graph, 0);
}
}
b. Hasil Eksekusi Program

17

You might also like