Skip to content

Commit d80e64e

Browse files
Adding activity-selection algo
1 parent ac8f596 commit d80e64e

File tree

2 files changed

+52
-5
lines changed

2 files changed

+52
-5
lines changed

Go/greedy/activity_selection.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
Activity Selection Problem
3+
You are given n activities with their start and finish times. Select the maximum number of activities
4+
that can be performed by a single person, assuming that a person can only work on a single activity at a time.
5+
*/
6+
7+
package greedy
8+
9+
import (
10+
"fmt"
11+
"sort"
12+
)
13+
14+
type activity struct {
15+
startTime int
16+
endTime int
17+
no int
18+
}
19+
20+
func ActivitSelection() {
21+
a := []activity{
22+
{5, 9, 1}, {1, 2, 2}, {3, 4, 3}, {0, 6, 4}, {5, 7, 5}, {8, 9, 6},
23+
}
24+
n := len(a)
25+
sort.SliceStable(a, func(i, j int) bool {
26+
return a[i].endTime < a[j].endTime
27+
})
28+
orderOfActivities := activitySelection(a, n)
29+
fmt.Println(orderOfActivities)
30+
}
31+
32+
func activitySelection(a []activity, n int) []activity {
33+
result := make([]activity, n)
34+
result[0] = a[0]
35+
j := 0
36+
for i := 1; i < n; i++ {
37+
if a[i].startTime >= a[j].endTime {
38+
result[i] = a[i]
39+
j = i
40+
}
41+
}
42+
return result
43+
}

Go/main.go

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,18 @@ package main
33
import (
44
"fmt"
55

6+
"github.com/bhavnavarshney/Algorithms-and-Data-Structures/Go/greedy"
67
"github.com/bhavnavarshney/Algorithms-and-Data-Structures/Go/hashing"
78
"github.com/bhavnavarshney/Algorithms-and-Data-Structures/Go/linkedlist"
89
"github.com/bhavnavarshney/Algorithms-and-Data-Structures/Go/searching"
9-
"github.com/bhavnavarshney/Algorithms-and-Data-Structures/Go/strings"
10+
"github.com/bhavnavarshney/Algorithms-and-Data-Structures/Go/sorting"
1011
"github.com/bhavnavarshney/Algorithms-and-Data-Structures/Go/trees"
1112
)
1213

1314
func main() {
1415
var ch int
1516
for {
16-
fmt.Println("\n0: Exit 1. SinglyLinkedList 2: DoublyLinkedList 3. HashMap 4. BinarySearchTree 5. KMP 6. Searching")
17+
fmt.Println("\n0: Exit 1. SinglyLinkedList 2: DoublyLinkedList 3. HashMap 4. BinarySearchTree 5. Searching 6. Sorting 7. Greedy")
1718
fmt.Scanf("%d", &ch)
1819
if ch == 0 {
1920
return
@@ -31,12 +32,15 @@ func main() {
3132
case 4:
3233
trees.TestBSTExecution()
3334
break
34-
case 5:
35-
strings.TestKMP()
36-
break
3735
case 6:
3836
searching.TestSearching()
3937
break
38+
case 7:
39+
sorting.TestSorting()
40+
break
41+
case 8:
42+
greedy.Greedy()
43+
break
4044
}
4145
}
4246

0 commit comments

Comments
 (0)