├── .gitignore
├── CodeChef
└── Beginner
│ ├── Chef Watson uses Social Network.py
│ ├── Chef and Keyboard.py
│ └── Task for Alexey.py
├── CodeForces
├── 4_A_Watermelon.go
└── 71A_Way_too_long.go
├── Docs
└── README.md
├── GeeksForGeeks
├── Go
│ ├── HashMap
│ │ ├── printAllAnagrams.go
│ │ └── twoSums.go
│ ├── RESTAPI
│ │ ├── gin_auth.go
│ │ └── jsonUnmarshal.go
│ ├── Search_Sort
│ │ ├── binary-search.go
│ │ └── linear-search-using-multi-threading.go
│ ├── Tree
│ │ ├── binaryTree.go
│ │ └── dfs_binaryTree.go
│ ├── arrays
│ │ ├── check-for-balanced-parentheses-in-an-expression.go
│ │ ├── check-if-first-and-last-digit-same.go
│ │ ├── missing_number.go
│ │ ├── next-greater-element.go
│ │ └── print-a-given-matrix-in-spiral-form.go
│ ├── channels-and-goroutine
│ │ ├── ChannelExample.go
│ │ ├── ChannelWaitGroup.go
│ │ ├── bufferedChannels.go
│ │ ├── channelIsClosed.go
│ │ └── channelQuit.go
│ ├── linked-lists
│ │ └── linkedList.go
│ ├── other
│ │ ├── 2Darray.go
│ │ ├── callByReference.go
│ │ ├── find-the-element-that-appears-once.go
│ │ └── interfacesExample.go
│ ├── queue
│ │ └── queue.go
│ ├── stacks
│ │ └── stacks.go
│ └── strings
│ │ └── wordMatch.go
└── Python
│ ├── Array
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-34.pyc
│ │ ├── arr_insert.cpython-34.pyc
│ │ ├── arr_printer.cpython-34.pyc
│ │ ├── arr_remove.cpython-34.pyc
│ │ └── arr_search.cpython-34.pyc
│ ├── arr_init.py
│ ├── arr_insert.py
│ ├── arr_printer.py
│ ├── arr_remove.py
│ └── arr_search.py
│ ├── charRemoveTopalindrome.py
│ ├── hello.py
│ └── matrix_spiral.py
├── Go_Samples
├── gin_basic_auth_middleware
│ └── server.go
├── mux_basic_auth_middleware
│ └── server.go
├── net_http_login_with_body
│ └── server.go
└── samples
│ ├── simple_any.go
│ ├── simple_channel.go
│ ├── simple_defer.go
│ ├── simple_filereader_using_buffer.go
│ ├── simple_generics.go
│ ├── simple_http.go
│ ├── simple_interface.go
│ ├── simple_pointer.go
│ ├── simple_select.go
│ ├── simple_slices.go
│ ├── simple_string_concat.go
│ ├── simple_unmarshal.go
│ └── simple_wg_routines.go
├── HackerEarth
├── Akash and the Assignment.cpp
├── Assorted Arrangements.py
├── Counting Traingles.cs
├── Crazy Kangaroo.c
├── KGBD.py
├── Mind Palaces.cpp
├── Roy and Matrix Sum.cpp
├── Roys Chocolate.c
├── Roys Life Cycle.cpp
├── Vanya and Array.py
├── Will you be my Friend.java
├── ZrZr.py
├── algorithms
│ ├── PalindromeCount.go
│ ├── possibleSums.go
│ └── xorry.go
└── challenges
│ └── expand-it-1.go
├── HackerRank
├── 30_days_of_code
│ ├── 10_binary_numbers.py
│ ├── 11_2d_arrays.py
│ ├── 12_inheritance.py
│ ├── 15_linked_list.py
│ ├── 18_queues_and_stacks.py
│ ├── 20_sorting.py
│ ├── 29_bitwise_and.py
│ └── 9_recursion.py
├── DataStructure
│ └── Array
│ │ ├── 2D_Array.go
│ │ └── Arrays_DS.go
├── cracking_the_coding_interview
│ ├── arrays_left_rotation.py
│ ├── ctci-balanced-brackets.go
│ ├── ctci-ransom-note.go
│ └── ctci_making_anagrams.go
├── interview-preparation-kit
│ ├── GreedyAlgorithms
│ │ └── greedy-florist.go
│ ├── arrays
│ │ └── minimum-swap-2.go
│ ├── dictAndmaps
│ │ ├── count-triplets.go
│ │ └── sherlock-and-anagrams.go
│ ├── linkedLists
│ │ └── reverseDoublyLL.go
│ └── stack
│ │ ├── balancedBrackets.go
│ │ └── stack.go
└── other_programs
│ ├── HandShake.c
│ ├── Insertion_Sort_1.c
│ ├── Insertion_sort_2.c
│ ├── Lonely_Integer.c
│ ├── Maximum_Draws.c
│ ├── Pangrams.c
│ ├── alternating_character.java
│ ├── anagram.java
│ ├── angry_professor.c
│ ├── chocolate_feast.cpp
│ ├── compare_the_triplets.py
│ ├── funny_string.c
│ ├── gem_stones.java
│ ├── is_fibo.c
│ ├── kangaroo.py
│ ├── love_letter_mystery.java
│ ├── luck_balance.py
│ ├── make_it_anagram.cpp
│ ├── making_anagrams.java
│ ├── maximizing_xor.cpp
│ ├── palindrom_index.java
│ ├── sherlcok_and_squares.c
│ ├── staircase.cpp
│ ├── swap_case.py
│ └── utopian_tree.c
├── LeetCode
├── 30_day_challenge
│ └── 2020_aug
│ │ └── single_number.go
├── Card
│ └── Recursion
│ │ └── reverse_a_string.go
├── Easy
│ ├── Computation
│ │ ├── counting-words-with-a-given-prefix.go
│ │ ├── fibonacci-number.go
│ │ └── number-of-steps-to-reduce-a-number-to-zero.go
│ ├── LinkedList
│ │ ├── intersection-of-two-linked-lists.go
│ │ ├── linked-list-cycle.go
│ │ ├── linked_list_remove_duplicates.go
│ │ ├── linkedlist_reverse.go
│ │ ├── middle_of_ll.go
│ │ └── palindrome-linked-list.go
│ ├── Stack_Queue
│ │ └── valid-parentheses.go
│ ├── array
│ │ ├── best-time-to-buy-and-sell-stock.go
│ │ ├── contains_duplicate.go
│ │ ├── decompress_encoded_list.go
│ │ ├── divide-array-into-equal-pairs.go
│ │ ├── intersect_of_2_arrays.go
│ │ ├── kth-largest-element-in-a-stream.go
│ │ ├── last-stone-weight.go
│ │ ├── longest-common-prefix.go
│ │ ├── maximum-subarray.go
│ │ ├── maximum-units-on-a-truck.go
│ │ ├── merge-sorted-array.go
│ │ ├── missing_number.go
│ │ ├── move-zeroes.go
│ │ ├── plus_one.go
│ │ ├── remove_dup_from_sorted_array.go
│ │ ├── remove_duplicates_from_sorted_array.go
│ │ ├── remove_element.go
│ │ ├── remove_one_element_to_make_array_increasing.go
│ │ ├── reverse_integer.go
│ │ ├── running-sum-of-1d-array.go
│ │ ├── search-insert-position.go
│ │ ├── single_number.go
│ │ └── sort-array-by-parity.go
│ ├── hashmap
│ │ ├── hashmap_Two_Sum.go
│ │ └── hashmap_contains-duplicate.go
│ ├── strings
│ │ ├── count-asterisks.go
│ │ ├── find-words-formed-by-characters.go
│ │ ├── first_unique_char.go
│ │ ├── implement-strstr.go
│ │ ├── is_anagram.go
│ │ ├── length-of-last-word.go
│ │ ├── longest_common_prefix.go
│ │ ├── palindrome.go
│ │ ├── ransom-note.go
│ │ ├── reverse-words-in-a-string.go
│ │ ├── roman_to_number.go
│ │ ├── string_reverse_a_string.go
│ │ └── valid-palindrome-ii.go
│ └── trees
│ │ ├── binary-tree-inorder-traversal.go
│ │ ├── invert-binary-tree.go
│ │ ├── minimum-depth-of-binary-tree.go
│ │ ├── path-sum.go
│ │ ├── same-tree.go
│ │ ├── search-in-a-binary-search-tree.go
│ │ └── symmetric-tree.go
└── Medium
│ ├── Array
│ ├── array_rotate.go
│ ├── maximum-erasure-value.go
│ ├── minimum-deletions.go
│ └── two-sum-ii-input-array-is-sorted.go
│ ├── LinkedList
│ ├── linked_list_add_two_numbers.go
│ ├── linked_list_remove_duplicate.go
│ ├── linked_list_swap_nodes_in_pairs.go
│ └── swapping-nodes-in-a-linked-list.go
│ ├── Trees
│ ├── binary-tree-level-order-traversal.go
│ ├── binary-tree-right-side-view.go
│ └── populating-next-right-pointers-in-each-node.go
│ ├── hashmap
│ ├── hashmap_3Sum.go
│ └── hashmap_find_replace_pattern.go
│ ├── recursive_dp
│ └── recursive_subsets.go
│ └── strings
│ └── string_manp_longest_substring_without_repeating_chars.go
├── README.md
└── go_sample.go
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
2 |
--------------------------------------------------------------------------------
/CodeChef/Beginner/Chef Watson uses Social Network.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 |
4 | input_count = input().strip().split()
5 | frnd_count = int(input_count[1])
6 | special_frdns = input().strip().split()
7 | special_frdns = list(map(int, special_frdns))
8 | spl_posts = {}
9 | normal_posts = {}
10 | while (frnd_count):
11 | entry = input().strip().split()
12 | if (int(entry[0]) in special_frdns):
13 | spl_posts[int(entry[1])] = entry[2]
14 | else:
15 | normal_posts[int(entry[1])] = entry[2]
16 | frnd_count = frnd_count - 1
17 |
18 | for i in sorted(spl_posts, reverse=True):
19 | print(spl_posts[i])
20 |
21 | for i in sorted(normal_posts, reverse=True):
22 | print(normal_posts[i])
23 |
--------------------------------------------------------------------------------
/CodeChef/Beginner/Chef and Keyboard.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # TODO: TLE for 10^5
3 |
4 | input_count = int(input())
5 | while (input_count):
6 | input_data = input().strip().split()
7 | n = int(input_data[0])
8 | m = int(input_data[1])
9 | c = int(input_data[2])
10 | count = 0
11 | for i in range(1, m + 1):
12 | if (i <= c):
13 | for j in range(1, n + 1):
14 | if (j <= c):
15 | if (i * j == c):
16 | count = count + 1
17 | print(count)
18 | input_count = input_count - 1
19 |
--------------------------------------------------------------------------------
/CodeChef/Beginner/Task for Alexey.py:
--------------------------------------------------------------------------------
1 | # TODO: TLE for 10^8
2 | from fractions import gcd
3 |
4 | input_count = int(input().strip().split()[0])
5 |
6 | while (input_count):
7 | min_lcm = 100000000
8 | junk_numbers = input().strip().split()
9 | input_digit = input().strip().split()
10 | input_digit = sorted(list(map(int, input_digit)))
11 | for i in range(0, len(input_digit) - 1):
12 | for j in range(i + 1, len(input_digit)):
13 | temp_lcm = (input_digit[i] * input_digit[j]) / gcd(input_digit[i], input_digit[j])
14 | if (temp_lcm <= min_lcm):
15 | min_lcm = temp_lcm
16 | print(int(min_lcm))
17 | input_count = input_count - 1
18 |
--------------------------------------------------------------------------------
/CodeForces/4_A_Watermelon.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | /*
4 | URL: https://codeforces.com/problemset/problem/4/A
5 | Status: Accepted
6 | Runtime: 62 ms
7 | Memory Usage: 10400 KB
8 | */
9 | import (
10 | "fmt"
11 | )
12 |
13 | func main() {
14 | var kg int
15 | fmt.Scanf("%d", &kg)
16 | if kg != 2 && kg%2 == 0 {
17 | fmt.Println("YES")
18 | } else {
19 | fmt.Println("NO")
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/CodeForces/71A_Way_too_long.go:
--------------------------------------------------------------------------------
1 | /*
2 | URL: https://codeforces.com/problemset/problem/71/A
3 | Status: Accepted
4 | Runtime: 62 ms
5 | Memory Usage: 10400 KB
6 | */
7 | package main
8 |
9 | import (
10 | "fmt"
11 | )
12 |
13 | func main() {
14 | var wLen int
15 | fmt.Scanf("%d\n", &wLen) // \n is must for codeforces :)
16 | var wArray []string
17 | word := ""
18 | for i := 0; i < wLen; i++ {
19 | fmt.Scanf("%s\n", &word)
20 | wArray = append(wArray, word)
21 | }
22 | for i := range wArray {
23 | wLength := len(wArray[i])
24 | if wLength <= 10 {
25 | fmt.Println(wArray[i])
26 | continue
27 | }
28 | fmt.Printf("%s%d%s\n", string(wArray[i][0]), wLength-2, string(wArray[i][wLength-1]))
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/Docs/README.md:
--------------------------------------------------------------------------------
1 | # List of useful Docs links
2 |
3 | 1. [Guide to Go Profiling, Tracing and Observability](https://github.com/DataDog/go-profiler-notes/blob/main/guide/README.md)
4 |
5 |
6 | 2. [Traps, Gotchas, and Common Mistakes for New Golang Devs](http://devs.cloudimmunity.com/gotchas-and-common-mistakes-in-go-golang/)
7 |
8 |
9 | 3. [Good read on memory leak investigation](https://blog.detectify.com/2019/09/05/how-we-tracked-down-a-memory-leak-in-one-of-our-go-microservices/)
10 |
11 |
12 | 4. [Gotchas in the Go Network Packages Defaults (http.Client)](https://martin.baillie.id/wrote/gotchas-in-the-go-network-packages-defaults/)
13 |
14 |
15 | 5. [Go resiliency pattern (semaphore, timeout, circuit-breaker](https://github.com/eapache/go-resiliency)
16 |
Resiliency patterns are a type of service architecture that help to prevent cascading failures and to preserve functionality in the event of service failure.
17 |
18 |
19 | 6. [Array Interview Questions](https://igotanoffer.com/blogs/tech/array-interview-questions)
20 |
21 |
22 | 7. [VIDEO: Introduction to System Design](https://www.youtube.com/watch?v=MbjObHmDbZo)
23 |
24 |
25 | 8. [Go Proverbs](http://go-proverbs.github.io/)
26 |
27 |
28 | 9. [Go code review helper](https://github.com/golang/go/wiki/CodeReviewComments#go-code-review-comments)
29 |
30 |
31 | 10. [What's up with slice pointer by reference](https://medium.com/swlh/golang-tips-why-pointers-to-slices-are-useful-and-how-ignoring-them-can-lead-to-tricky-bugs-cac90f72e77b)
32 |
33 | 11. [Understanding golang data types](https://www.digitalocean.com/community/tutorials/understanding-data-types-in-go)
34 |
35 | 12. [High-performance JSON parsing in Go](https://www.cockroachlabs.com/blog/high-performance-json-parsing/)
36 |
37 | 13. [How to build a production ready microservice](https://www.oreilly.com/library/view/production-ready-microservices/9781491965962/ch01.html)
38 |
39 |
40 | 14. [How to scale from zero to millions](https://systeminterview.com/scale-from-zero-to-millions-of-users.php)
41 |
42 | 15. [Scaling a go application](https://github.com/zeromicro/go-zero)
43 |
44 | 16. [Problems with Integer. Good Read](https://jvns.ca/blog/2023/01/18/examples-of-problems-with-integers/)
45 |
46 | 17. [Golang quirks and tricks](https://eblog.fly.dev/quirks.html)
47 |
48 |
49 |
50 | SRE / Application metrics/ Go Trace:
51 |
52 | 1. [The Four Golden Signals](https://sre.google/sre-book/monitoring-distributed-systems/#xref_monitoring_golden-signals)
53 |
54 | 2. [Go tracer which supposed to be better that go-tracer](https://github.com/dominikh/gotraceui)
55 |
56 |
57 | Principles / Design patterns:
58 |
59 | 1. [Adapter pattern in Go](https://bitfieldconsulting.com/golang/adapter)
60 |
61 | 2. [How to ace System Design Interview?](https://helloacm.com/facebook-onsite-interview-preparation-part-3-how-to-ace-a-design-interview/)
62 |
63 |
64 |
65 |
66 | Interview Docs:
67 |
68 | 1. [Interview Best Practices](https://careers.google.com/interview-tips/?src=Online%2FSocial%2FKeyword_blog&utm_campaign=&utm_medium=Google%20Website&utm_source=Online)
69 |
70 | 2. [Mock Interview Videos](https://interviewing.io/recordings/)
71 |
72 | 3. [How to write a CV?](https://somehowimanage.blog/2019/01/28/somehow-i-recruit-cv-yeah-yeah-cv/)
73 |
74 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/HashMap/printAllAnagrams.go:
--------------------------------------------------------------------------------
1 | //https://www.geeksforgeeks.org/given-a-sequence-of-words-print-all-anagrams-together/
2 | package main
3 |
4 | import (
5 | "fmt"
6 | "sort"
7 | "strings"
8 | )
9 |
10 | func sortWord(str string) string{
11 | chars := strings.Split(str,"")
12 | sort.Strings(chars)
13 | return strings.Join(chars,"")
14 | }
15 |
16 | func printAllAnagrams(words []string) {
17 | wordMap := make(map[string][]int)
18 | countMap := make(map[int]string)
19 | for i, word := range words {
20 | sortedWord := sortWord(word)
21 | wordMap[sortedWord] =append(wordMap[sortedWord],i)
22 | }
23 | maxCount := 0
24 | for key := range wordMap{
25 | countMap[len(wordMap[key])] = key
26 | if maxCount < len(wordMap[key]){
27 | maxCount = len(wordMap[key])
28 | }
29 | }
30 | for i:= maxCount;i>=1;i--{
31 | key := countMap[i]
32 | wordIdxs := wordMap[key]
33 | for _,idx := range wordIdxs{
34 | fmt.Print(words[idx]," ")
35 | }
36 | }
37 | }
38 |
39 | func main() {
40 | strngs := []string{"cat", "tac", "dog", "god", "act"}
41 | printAllAnagrams(strngs)
42 | }
43 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/HashMap/twoSums.go:
--------------------------------------------------------------------------------
1 | //https://leetcode.com/problems/two-sum/solution/
2 | package main
3 |
4 | import (
5 | "fmt"
6 | )
7 |
8 | func twoSum(nums []int, target int) []int {
9 | sumMap := make(map[int]int)
10 | for i,val := range nums{
11 | if idx,ok := sumMap[target-val];ok{
12 | return []int{idx,i}
13 | }
14 | sumMap[val] = i
15 | }
16 | return nil
17 | }
18 |
19 | func main(){
20 | values := []int{2, 7, 11, 15}
21 | target := 9
22 | idxs :=twoSum(values,target)
23 | fmt.Println(idxs)
24 | values = []int{20, 70, 1, 15}
25 | target = 38
26 | idxs =twoSum(values,target)
27 | fmt.Println(idxs)
28 | }
29 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/RESTAPI/gin_auth.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | /*
4 | curl request
5 | curl --request GET \
6 | --url http://localhost:8085/rest/names \
7 | --header 'authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=' //the encoded string of usernam:password
8 | */
9 | import (
10 | "encoding/base64"
11 | "encoding/json"
12 | //"io/ioutil"
13 | "io"
14 | "net/http"
15 | "strings"
16 |
17 | "github.com/gin-gonic/gin"
18 | )
19 |
20 | var (
21 | Names = []string{"Bharath Kumar", "Jon Snow"}
22 | )
23 |
24 | type Name struct {
25 | Name string `json:"name",omitempty`
26 | }
27 |
28 | func authMiddleware() gin.HandlerFunc {
29 | //authenticate the creds here
30 | return func(c *gin.Context) {
31 |
32 | s := strings.SplitN(c.Request.Header.Get("Authorization"), " ", 2)
33 | if len(s) != 2 {
34 | c.JSON(http.StatusBadRequest, "Authorization header is not passed")
35 | c.Abort()
36 | return
37 | }
38 |
39 | b, err := base64.StdEncoding.DecodeString(s[1])
40 | if err != nil {
41 | c.JSON(http.StatusUnauthorized, "Auth Decode error")
42 | c.Abort()
43 | return
44 | }
45 |
46 | pair := strings.SplitN(string(b), ":", 2)
47 | if len(pair) != 2 {
48 | c.JSON(http.StatusUnauthorized, "Decoded string is not correct")
49 | c.Abort()
50 | return
51 | }
52 |
53 | if pair[0] != "username" || pair[1] != "password" {
54 | c.JSON(http.StatusUnauthorized, "Username/password is not correct")
55 | c.Abort()
56 | return
57 | }
58 |
59 | }
60 | }
61 |
62 | func getNames(c *gin.Context) {
63 | c.JSON(http.StatusOK, Names)
64 | }
65 |
66 | func putNames(c *gin.Context) {
67 | var name Name
68 | //c.BindJSON(&name) //this can be used instead of unmarshal
69 | //bodyByte, err := ioutil.ReadAll(c.Request.Body)
70 | bodyByte, err := io.ReadAll(c.Request.Body)
71 | if err != nil {
72 | c.JSON(http.StatusInternalServerError, "Check the body sent")
73 | return
74 | }
75 | err = json.Unmarshal(bodyByte, &name)
76 | if err != nil {
77 | c.JSON(http.StatusInternalServerError, "Check the body sent")
78 | return
79 | }
80 |
81 | Names = append(Names, name.Name)
82 | c.JSON(http.StatusAccepted, Names)
83 | }
84 |
85 | func main() {
86 | //create a new gin router
87 | router := gin.New()
88 | //create a new router group, this will create localhost:/rest/names
89 | names := router.Group("/rest/names")
90 | //All middlewares must be passed will come under USE
91 | names.Use(authMiddleware())
92 | names.GET("", getNames)
93 | names.POST("", putNames)
94 |
95 | //start the server at port 8085
96 | router.Run(":8085")
97 | }
98 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/RESTAPI/jsonUnmarshal.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | )
7 |
8 | type Items struct {
9 | Vegetables map[string]int `json:"vegetables"`
10 | Fruits Seasonal `json:"fruits"`
11 | }
12 |
13 | type Seasonal struct {
14 | Fruits map[string]int `json:"seasonal"`
15 | }
16 |
17 | func main() {
18 | var items *Items
19 | data := []byte("{\"vegetables\":{\"carrot\":5,\"beans\":4},\"fruits\":{\"seasonal\":{\"apple\":3,\"banana\":2}}}")
20 | json.Unmarshal(data, &items)
21 |
22 | for key, value := range items.Vegetables {
23 | fmt.Printf("%s: %d\n", key, value)
24 | }
25 |
26 | for key, value := range items.Fruits.Fruits {
27 | fmt.Printf("%s: %d\n", key, value)
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/Search_Sort/binary-search.go:
--------------------------------------------------------------------------------
1 | //https://www.geeksforgeeks.org/binary-search/
2 | package main
3 |
4 | import (
5 | "fmt"
6 | )
7 |
8 |
9 | func binarySearch(elements []int,low, high, key int) int {
10 | if high < low {
11 | return -1
12 | }
13 |
14 | mid := (low +high)/2
15 | if elements[mid] == key{
16 | return mid
17 | }
18 |
19 | if key > elements[mid] {
20 | return binarySearch(elements,mid+1,high,key)
21 | }
22 | return binarySearch(elements,low,mid-1,key)
23 | }
24 |
25 | func main() {
26 | elems := []int{1,2,3,4,5,6,7,10,20}
27 | key:= 20
28 | pos := binarySearch(elems,0,len(elems),key)
29 | if pos == -1 {
30 | fmt.Printf("Couldnt find the key %d in element list %+v\n",key,elems)
31 | }
32 | fmt.Printf("found the key %d in element list %+v, at position %d\n",key,elems,pos)
33 |
34 |
35 | elems = []int{10,30,50,80,80}
36 | key = 20
37 | pos = binarySearch(elems,0,len(elems),key)
38 | if pos == -1 {
39 | fmt.Printf("Couldnt find the key %d in element list %+v\n",key,elems)
40 | }
41 | fmt.Printf("found the key %d in element list %+v, at position %d\n",key,elems,pos)
42 | }
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/Search_Sort/linear-search-using-multi-threading.go:
--------------------------------------------------------------------------------
1 | //https://www.geeksforgeeks.org/linear-search-using-multi-threading/
2 | package main
3 |
4 | import (
5 | "fmt"
6 | )
7 |
8 | func linearSearch(element, key, pos int, chanEle chan int) chan int {
9 | fmt.Println("pos",pos)
10 | if element == key {
11 | chanEle <- pos
12 | }
13 | return chanEle
14 | }
15 |
16 | func main() {
17 |
18 | chanElem := make(chan int)
19 | elements := []int{1, 4, 13, 24, 55, 68}
20 |
21 | for pos, elem := range elements {
22 | go linearSearch(elem, 13, pos, chanElem)
23 | }
24 | fmt.Println("position is: ", <-chanElem)
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/Tree/binaryTree.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | // tree node structure
6 | type Node struct {
7 | data int
8 | leftChild *Node
9 | rightChild *Node
10 | }
11 |
12 | type queue struct {
13 | queue []*Node
14 | }
15 |
16 | // add the element to the end
17 | func (q *queue) enque(node *Node) {
18 | q.queue = append(q.queue, node)
19 | }
20 |
21 | // remove the first element and return it
22 | func (q *queue) deque() *Node {
23 | if len(q.queue) <= 0 {
24 | return nil
25 | }
26 | node := q.queue[0]
27 | q.queue = q.queue[1:]
28 | return node
29 | }
30 |
31 | func newNode(data int) *Node {
32 | newNode := new(Node)
33 | newNode.data = data
34 | return newNode
35 | }
36 |
37 | // find the parent value and create a new node. New node is placed on parent node based on the leftChild value
38 | // TODO: we can change the logic to insert to the next previous node too.
39 | /*
40 | if (temp->left != NULL){
41 | q.push(temp->left);
42 | else {
43 | temp->left = CreateNode(data);
44 | }}
45 | */
46 | func addNode(root *Node, parentVal, newNodeVal int, leftChild bool) {
47 | node := newNode(newNodeVal)
48 | q := &queue{}
49 | q.enque(root)
50 | for {
51 | // keep on going until the queue is empty
52 | if len(q.queue) <= 0 {
53 | break
54 | }
55 | queueNode := q.deque() // pop
56 | // if the parent node is the node we are searching for,stop the op
57 | if queueNode.data == parentVal {
58 | if leftChild {
59 | queueNode.leftChild = &Node{data: newNodeVal}
60 | return
61 | }
62 | queueNode.rightChild = node
63 | return
64 | }
65 |
66 | if queueNode.leftChild != nil {
67 | q.enque(queueNode.leftChild)
68 | }
69 | if queueNode.rightChild != nil {
70 | q.enque(queueNode.rightChild)
71 | }
72 | }
73 | }
74 |
75 | func inOrder(node *Node) {
76 | if node == nil {
77 | return
78 | }
79 | inOrder(node.leftChild)
80 | fmt.Printf("%d->", node.data)
81 | inOrder(node.rightChild)
82 | }
83 |
84 | // keep on checking children sum for left and right child, until we hit the leaf.
85 | // If one of the sum found to be not equal, return false
86 | // https://www.geeksforgeeks.org/check-for-children-sum-property-in-a-binary-tree/
87 | func checkForChildreSum(node *Node) bool {
88 | if node == nil {
89 | return false
90 | }
91 | var l, r int
92 | if node.leftChild != nil {
93 | l = node.leftChild.data
94 | }
95 | if node.rightChild != nil {
96 | r = node.rightChild.data
97 | }
98 | fmt.Printf("Node: %d, l:%d, r:%d\n", node.data, l, r)
99 |
100 | if node.data == l+r {
101 | return true
102 | }
103 |
104 | return checkForChildreSum(node.leftChild) || checkForChildreSum(node.rightChild)
105 | }
106 |
107 | func main() {
108 | // node structure
109 | // 60
110 | // 20 30
111 | // 10 40 10 90
112 | // root node
113 | root := newNode(60)
114 | addNode(root, 60, 20, true)
115 | addNode(root, 60, 30, false)
116 | addNode(root, 20, 10, true)
117 | addNode(root, 20, 40, false)
118 | addNode(root, 30, 10, true)
119 | addNode(root, 30, 90, false)
120 | // inOrder(root)
121 | fmt.Println(checkForChildreSum(root))
122 | }
123 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/Tree/dfs_binaryTree.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | type Node struct {
6 | data int
7 | leftChild *Node
8 | rightChild *Node
9 | }
10 |
11 | func newNode(data int) *Node {
12 | newNode := new(Node)
13 | newNode.data = data
14 | return newNode
15 | }
16 |
17 | // DFS
18 | func CreateTree() *Node {
19 | //initialize the root
20 | root := newNode(1)
21 |
22 | root.leftChild = newNode(2)
23 | root.rightChild = newNode(3)
24 |
25 | root.leftChild.leftChild = newNode(4)
26 | root.leftChild.rightChild = newNode(5)
27 |
28 | return root
29 | }
30 |
31 | func InOrder(node *Node) {
32 | if node == nil {
33 | return
34 | }
35 | InOrder(node.leftChild)
36 | fmt.Printf("%d->", node.data)
37 | InOrder(node.rightChild)
38 | }
39 |
40 | // using stack
41 | func preorderTraversal(root *TreeNode) []int {
42 | var ans []int
43 | if root == nil {
44 | return ans
45 | }
46 | stack := []*TreeNode{root}
47 | for len(stack) > 0 {
48 | top := stack[len(stack)-1]
49 | stack = stack[:len(stack)-1]
50 | ans = append(ans, top.Val)
51 | if top.Right != nil {
52 | stack = append(stack, top.Right)
53 | }
54 | if top.Left != nil {
55 | stack = append(stack, top.Left)
56 | }
57 | }
58 | return ans
59 | }
60 |
61 | func PreOrder(node *Node) {
62 | if node == nil {
63 | return
64 | }
65 | fmt.Printf("%d->", node.data)
66 | PreOrder(node.leftChild)
67 | PreOrder(node.rightChild)
68 | }
69 |
70 | func PostOrder(node *Node) {
71 | if node == nil {
72 | return
73 | }
74 | PostOrder(node.leftChild)
75 | PostOrder(node.rightChild)
76 | fmt.Printf("%d->", node.data)
77 | }
78 |
79 | func main() {
80 | root := CreateTree()
81 |
82 | //print preorder
83 | fmt.Println("\nPre Order:")
84 | PreOrder(root)
85 |
86 | //print inorder
87 | fmt.Println("\n\nIn Order:")
88 | InOrder(root)
89 |
90 | //print postorder
91 | fmt.Println("\n\nPost Order:")
92 | PostOrder(root)
93 | }
94 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/arrays/check-for-balanced-parentheses-in-an-expression.go:
--------------------------------------------------------------------------------
1 | //https://www.geeksforgeeks.org/check-for-balanced-parentheses-in-an-expression/
2 | package main
3 |
4 | import (
5 | "fmt"
6 | )
7 |
8 | var MatchingBraces = map[string]string{
9 | ")": "(",
10 | "]": "[",
11 | "}": "{",
12 | }
13 |
14 | func isBlanced(expression string) bool {
15 | fmt.Printf("Passed string is %s : ",expression)
16 | if len(expression)%2 != 0 {
17 | return false
18 | }
19 | m := len(expression) / 2
20 | for i := 0; i < m; i++ {
21 | if string(expression[m-1-i]) != MatchingBraces[string(expression[m+i])] {
22 | return false
23 | }
24 | }
25 | return true
26 | }
27 |
28 | func main() {
29 | fmt.Println(isBlanced("([])"))
30 | fmt.Println(isBlanced("([)"))
31 | fmt.Println(isBlanced("([[[[)"))
32 | return
33 | }
34 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/arrays/check-if-first-and-last-digit-same.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func isFirstLastDigitSame(arr []int) {
8 | for i, val := range arr {
9 | first := val % 10
10 | for {
11 | if val < 10 {
12 | break
13 | }
14 | val = val / 10
15 | }
16 | if first == val {
17 | fmt.Println(arr[i])
18 | }
19 | }
20 | }
21 |
22 | func main() {
23 | arr := []int{111, 123, 343}
24 | isFirstLastDigitSame(arr)
25 | }
26 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/arrays/missing_number.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | /*
4 | URL: https://www.geeksforgeeks.org/find-the-missing-number/
5 | */
6 | import (
7 | "fmt"
8 | )
9 |
10 | // we are dealing with n-1 elements. and we need to calculate summation for n * n+1 /2
11 | // array has to be continuos and the extra element should always be 1 to n+1
12 | // input 1,3,4. Here 2 is missing. Here 'n' is 4.
13 | func missingNumber(nums []int) int {
14 | len := len(nums)
15 | summation := ((len + 1) * ((len + 2) / 2))
16 | sum := 0
17 | for _, num := range nums {
18 | sum += num
19 | }
20 | return summation - sum
21 | }
22 |
23 | // for the given array [2,3], calculate xor for idx and numbers with given 'n'. i.e 1^2 ^2^3 ^3
24 | func missingNumberXor(nums []int) int {
25 | xor := len(nums) + 1
26 | for idx, num := range nums {
27 | xor = xor ^ num ^ idx + 1
28 | }
29 | return xor
30 | }
31 |
32 | func main() {
33 | fmt.Println("input: <>, output:", missingNumberXor([]int{2, 3}))
34 | }
35 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/arrays/next-greater-element.go:
--------------------------------------------------------------------------------
1 | //https://www.geeksforgeeks.org/next-greater-element/
2 |
3 | package main
4 |
5 | import (
6 | "fmt"
7 | )
8 |
9 | func nextGreaterElement(elements []int) {
10 | eleLen := len(elements)
11 | nextBiggerElements := make([]int, eleLen)
12 | for i := eleLen - 1; i >= 0; i-- {
13 | nextMinimum := -1
14 | for j := i + 1; j <= eleLen-1; j++ {
15 | if elements[j] > elements[i] {
16 | if nextMinimum == -1 || nextMinimum > elements[j] {
17 | nextMinimum = elements[j]
18 | }
19 | }
20 | }
21 | nextBiggerElements[i] = nextMinimum
22 | }
23 | fmt.Printf("Element is %v\n", nextBiggerElements)
24 | }
25 |
26 | func main() {
27 | ele := []int{4, 5, 2, 25}
28 | nextGreaterElement(ele)
29 |
30 | ele = []int{13, 7, 6, 12}
31 | nextGreaterElement(ele)
32 |
33 | ele = []int{11, 13, 21, 3}
34 | nextGreaterElement(ele)
35 |
36 | ele = []int{2,5,9,6,3,4,8,15,12}
37 | nextGreaterElement(ele)
38 | }
39 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/arrays/print-a-given-matrix-in-spiral-form.go:
--------------------------------------------------------------------------------
1 | //https://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/
2 | package main
3 |
4 | import (
5 | "fmt"
6 | )
7 |
8 | func printInSpiral(matrix [4][4]int, rowLen, columnLen int) {
9 |
10 | for i := 0; i < rowLen/2; i++ {
11 | //print LR top row
12 | for lr := i; lr < columnLen-i-1; lr++ {
13 | fmt.Printf("%d->", matrix[i][lr])
14 | }
15 |
16 | //print TB right column
17 | for tb := i; tb < rowLen-i-1; tb++ {
18 | fmt.Printf("%d->", matrix[tb][columnLen-i-1])
19 | }
20 |
21 | //print RL below row
22 | for rl := columnLen - 1 - i; rl > i; rl-- {
23 | fmt.Printf("%d->", matrix[rowLen-1-i][rl])
24 | }
25 |
26 | //print BT left column
27 | for bt := rowLen - 1 - i; bt > i; bt-- {
28 | fmt.Printf("%d->", matrix[bt][i])
29 | }
30 | }
31 |
32 | }
33 |
34 | func main() {
35 | var matrix [4][4]int
36 |
37 | for i := 0; i < 4; i++ {
38 | for j := 0; j < 4; j++ {
39 | matrix[i][j] = i*1 + j*2
40 | }
41 | }
42 | fmt.Println(matrix)
43 | printInSpiral(matrix, 4, 4)
44 | fmt.Println()
45 |
46 | //matrix2 := make([][]int, 6*6)
47 | //
48 | //for i := 0; i < 6; i++ {
49 | // for j := 0; j < 6; j++ {
50 | // matrix2[i][j] = i*2 + j + 3
51 | // }
52 | //}
53 | //fmt.Println(matrix2)
54 | //printInSpiral(matrix2, 6, 6)
55 | //fmt.Println()
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/channels-and-goroutine/ChannelExample.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func sumTwo(x, y int, sum chan int) {
8 | sum <- x + y
9 | //if x%2 != 0 {
10 | // time.Sleep(time.Second)
11 | //}
12 | }
13 |
14 | func main() {
15 | //single channel
16 | sum := make(chan int)
17 | go func() {
18 | sumTwo(5, 10, sum)
19 |
20 | }()
21 | fmt.Println(<-sum)
22 | go func() {
23 | sumTwo(10, 15, sum)
24 | }()
25 | fmt.Println(<-sum)
26 | }
27 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/channels-and-goroutine/ChannelWaitGroup.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "sync"
6 | )
7 |
8 | func sumIt(x, y int, sum chan int) {
9 | sum <- x + y
10 |
11 | //time.Sleep(time.Second)
12 | }
13 |
14 | func main() {
15 | var wg sync.WaitGroup
16 | wg.Add(2)
17 | //single channel
18 | sum := make(chan int)
19 | go func() {
20 | go sumIt(5, 10, sum)
21 | fmt.Println(<-sum)
22 | wg.Done()
23 | }()
24 |
25 | go func() {
26 | go sumIt(10, 15, sum)
27 | fmt.Println(<-sum)
28 | wg.Done()
29 | }()
30 | wg.Wait()
31 | }
32 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/channels-and-goroutine/bufferedChannels.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func twoNums(y int, nums chan int) {
6 | nums <- y + 1
7 | //close(nums)
8 | nums <- y - 1
9 | }
10 |
11 | func main() {
12 | //single channel
13 | nums := make(chan int, 2)
14 | twoNums(5, nums)
15 | fmt.Println(<-nums)
16 | fmt.Println(<-nums)
17 | }
18 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/channels-and-goroutine/channelIsClosed.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | // <- is used to make sure that,
6 | // this function is not writing to the channel
7 | func IsClosed(ch <-chan int) bool {
8 | select {
9 | case <-ch:
10 | return true
11 | default:
12 | }
13 |
14 | return false
15 | }
16 |
17 | func main() {
18 | c := make(chan int)
19 | fmt.Println(IsClosed(c)) // false
20 | close(c)
21 | fmt.Println(IsClosed(c)) // true
22 | }
23 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/channels-and-goroutine/channelQuit.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "math/rand"
6 |
7 | "time"
8 | )
9 |
10 | func quitChannel(quit chan bool) {
11 | time.Sleep(time.Second)
12 | // Do stuff
13 | s1 := rand.NewSource(time.Now().UnixNano())
14 | r1 := rand.New(s1)
15 | rand := r1.Int63n(100)
16 | if rand%2 == 0 {
17 | quit <- true
18 | quit <- true
19 | }
20 | fmt.Println("got odd, closing channel", rand)
21 | close(quit)
22 | }
23 |
24 | func main() {
25 | quit := make(chan bool)
26 | go quitChannel(quit)
27 | for {
28 | select {
29 | case <-quit:
30 | fmt.Println("Received quit")
31 | return
32 | default:
33 | println("Waiting to get data or close channel...")
34 | time.Sleep(time.Millisecond * 300)
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/linked-lists/linkedList.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | type Node struct {
8 | data int
9 | next *Node
10 | }
11 |
12 | func PrintLinkedList(head *Node) {
13 | if head == nil {
14 | fmt.Println("Linked List Head is nil")
15 | }
16 | node := head
17 | for {
18 | fmt.Print(node.data, "->")
19 | if node.next == nil {
20 | break
21 | }
22 | node = node.next
23 | }
24 | fmt.Println("nil")
25 | }
26 |
27 | func AddNode(head *Node, value int) *Node {
28 | newNode := new(Node)
29 | newNode.data = value
30 | if head == nil {
31 | head = newNode
32 | return head
33 | }
34 |
35 | node := head
36 | for {
37 | if node.next == nil {
38 | break
39 | }
40 | node = node.next
41 | }
42 | node.next = newNode
43 | return head
44 | }
45 |
46 | func DeleteNode(head *Node, position int) *Node {
47 | if head == nil {
48 | fmt.Println("The Linked list head is nil")
49 | return head
50 | }
51 | if position == 0 {
52 | head = nil
53 | return head
54 | }
55 |
56 | nodeRef := head
57 | i := 0
58 | for {
59 | lastNodeRef := nodeRef
60 | if nodeRef.next != nil {
61 | nodeRef = nodeRef.next
62 | i++
63 | } else {
64 | fmt.Println("Node Not found for position: ", position)
65 | return head
66 | }
67 |
68 | if i == position {
69 | fmt.Println("Deleted the Node at position: ", position)
70 | lastNodeRef.next = nodeRef.next
71 | return head
72 | }
73 | }
74 |
75 | return head
76 | }
77 |
78 | func main() {
79 | var head *Node
80 | head = AddNode(head, 20)
81 | AddNode(head, 30)
82 | AddNode(head, 40)
83 | AddNode(head, 50)
84 | // PrintLinkedList(head)
85 | // RemoveDuplicates(head)
86 | // head = DeleteNode(head, 1)
87 | // head = DeleteNode(head, 5)
88 | // PrintMiddleNode(head)
89 | // head = ReverseLinkedList(head)
90 | // head = ReverseWithGroup(head, 2)
91 | /* var head1 *Node;head1 = AddNode(head1, 22);AddNode(head1, 23);AddNode(head1, 24);ListAlternate(head, head1) */
92 | PrintLinkedList(head)
93 | }
94 |
95 | // solutions to the g4g questions
96 |
97 | // https://www.geeksforgeeks.org/write-a-c-function-to-print-the-middle-of-the-linked-list/
98 | func PrintMiddleNode(head *Node) {
99 | if head == nil {
100 | fmt.Println("No LL")
101 | return
102 | }
103 | ptr := head
104 | ptr2 := head
105 | for {
106 | if ptr2.next == nil {
107 | fmt.Println("Middle Node", ptr.data)
108 | break
109 | }
110 | if ptr2.next.next == nil {
111 | fmt.Println("Middle Node", ptr.next.data)
112 | break
113 | }
114 | ptr2 = ptr2.next.next
115 | ptr = ptr.next
116 | }
117 | }
118 |
119 | // https://www.geeksforgeeks.org/reverse-a-linked-list/
120 | func ReverseLinkedList(head *Node) *Node {
121 | var prev, next *Node
122 | currentNode := head
123 | for {
124 | if currentNode == nil {
125 | return prev
126 | }
127 | next = currentNode.next
128 | currentNode.next = prev
129 | prev = currentNode
130 | currentNode = next
131 | }
132 | }
133 |
134 | // https://practice.geeksforgeeks.org/problems/remove-duplicate-element-from-sorted-linked-list/1
135 | func RemoveDuplicates(head *Node) {
136 | currentNode := head
137 | for {
138 | if currentNode == nil || currentNode.next == nil {
139 | return
140 | }
141 | if currentNode.data == currentNode.next.data {
142 | currentNode.next = currentNode.next.next
143 | continue
144 | }
145 | currentNode = currentNode.next
146 | }
147 | }
148 |
149 | // https://practice.geeksforgeeks.org/problems/reverse-a-linked-list-in-groups-of-given-size/1
150 | func ReverseWithGroup(head *Node, group int) *Node {
151 | var prev, next *Node
152 | currentNode := head
153 | for {
154 | // same old reversal logic with group limit
155 | for i := 0; i < group; i++ {
156 | if currentNode == nil {
157 | break
158 | }
159 | next = currentNode.next
160 | currentNode.next = prev
161 | prev = currentNode
162 | currentNode = next
163 | }
164 | // If the next node exist, set the head.next (first node of current recursive list) with the next reversed group
165 | if next != nil {
166 | head.next = ReverseWithGroup(next, group)
167 | }
168 | // return the last node of the group, which is the first node after the reversing the current group
169 | return prev
170 | }
171 | }
172 |
173 | // https://www.geeksforgeeks.org/merge-a-linked-list-into-another-linked-list-at-alternate-positions/
174 | func ListAlternate(head, head2 *Node) {
175 | cur1 := head
176 | cur2 := head2
177 | for {
178 | if (cur1 == nil && cur2 == nil) || cur2 == nil {
179 | return
180 | }
181 | if cur1 != nil && cur1.next == nil {
182 | cur1.next = cur2
183 | cur2 = cur2.next
184 | cur1 = cur1.next
185 | }
186 | next2 := cur2.next
187 | next1 := cur1.next
188 | cur1.next = cur2
189 | cur1.next.next = next1
190 | cur2 = next2
191 | cur1 = cur1.next.next
192 | }
193 | }
194 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/other/2Darray.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func main(){
8 | value := [2][2]int{}
9 | value[0][0] = 6
10 | fmt.Println(value)
11 |
12 | }
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/other/callByReference.go:
--------------------------------------------------------------------------------
1 | // It is not possible to use the same address location in golang,
2 | // So Call by reference doesnot work
3 | package main
4 |
5 | import "fmt"
6 |
7 | func fn(m *int) {
8 | fmt.Printf("%v\n",m)
9 | *m = 1
10 | }
11 |
12 | func main() {
13 | var m int
14 | fn(&m)
15 | fmt.Printf("%v\n",&m)
16 | fmt.Println(m)
17 | }
18 |
19 | //output is:
20 | //0xc000006028
21 | //0xc000006028
22 | //1
23 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/other/find-the-element-that-appears-once.go:
--------------------------------------------------------------------------------
1 | // https://www.geeksforgeeks.org/find-element-appears-array-every-element-appears-twice
2 | // https://www.geeksforgeeks.org/find-the-element-that-appears-once
3 | package main
4 |
5 | import (
6 | "fmt"
7 | )
8 | func getSingleAppeared(elements []int) int {
9 | sum := elements[0]
10 | for i := 1; i < len(elements); i++ {
11 | sum = sum ^ elements[i]
12 | }
13 | return sum
14 | }
15 |
16 | func main() {
17 | fmt.Println("[]string{1,2,1,3,2} :", getSingleAppeared([]int{1, 2, 1, 3, 2}))
18 | fmt.Println("[]string{1,3,1,3,2} :", getSingleAppeared([]int{1, 3, 1, 3, 2}))
19 | }
20 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/other/interfacesExample.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | type Val struct {
6 | number int
7 | strings string
8 | }
9 |
10 | type MyInterface interface {
11 | PrintValues()
12 | }
13 |
14 | func (v *Val) PrintValues() {
15 | fmt.Printf("number: %d, string: %s\n", v.number, v.strings)
16 | }
17 |
18 | //func SomeFunction(v Val){
19 | // //do all Val related operations here
20 | // v.PrintValues()
21 | //}
22 |
23 | func newFunc(v MyInterface){
24 | v.PrintValues()
25 | }
26 |
27 | func main() {
28 | newVal := Val{10, "ten"}
29 | //SomeFunction(newVal)
30 | //you can pass the struct object as an interface,
31 | //writing UT for interface will be simpler
32 | newFunc(&newVal)
33 |
34 | val2 := Val{20, "twenty"}
35 | newFunc(&val2)
36 | }
37 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/queue/queue.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "sync"
6 | )
7 |
8 | type Queue struct {
9 | items []int
10 | lock sync.RWMutex
11 | }
12 |
13 | func (q *Queue) enqueue(item int){
14 | q.lock.Lock()
15 | q.items = append(q.items,item)
16 | q.lock.Unlock()
17 | }
18 |
19 | func (q *Queue) deque(){
20 | q.lock.Lock()
21 | q.items = q.items[1:len(q.items)]
22 | q.lock.Unlock()
23 | }
24 |
25 | func main(){
26 | queueElem := new(Queue)
27 | queueElem.enqueue(1)
28 | queueElem.enqueue(5)
29 | queueElem.enqueue(3)
30 | fmt.Println(queueElem.items)
31 | queueElem.deque()
32 | fmt.Println(queueElem.items)
33 | queueElem.enqueue(4)
34 | fmt.Println(queueElem.items)
35 | }
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/stacks/stacks.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "sync"
6 | )
7 |
8 | type Stack struct {
9 | items []int
10 | lock sync.RWMutex
11 | }
12 |
13 | func (s *Stack) push(item int){
14 | s.lock.Lock()
15 | s.items = append(s.items,item)
16 | s.lock.Unlock()
17 | }
18 |
19 | func (s *Stack) pop(){
20 | s.lock.Lock()
21 | s.items = s.items[0:len(s.items)-1]
22 | s.lock.Unlock()
23 | }
24 |
25 | func main(){
26 | stackElem := new(Stack)
27 | stackElem.push(1)
28 | stackElem.push(5)
29 | stackElem.push(3)
30 | fmt.Println(stackElem.items)
31 | stackElem.pop()
32 | fmt.Println(stackElem.items)
33 | stackElem.push(4)
34 | fmt.Println(stackElem.items)
35 | }
--------------------------------------------------------------------------------
/GeeksForGeeks/Go/strings/wordMatch.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func wordMatch(string1, string2 string) []string {
8 | var matchedString []string
9 | str2len := len(string2)
10 | str1len := len(string1)
11 |
12 | for i := 0; i < str1len; i++ {
13 | if string1[i] == string2[0] {
14 | if i+str2len > str1len {
15 | return matchedString
16 | }
17 | for j := 1; j < str2len && string1[i+j] == string2[j]; j++ {
18 | if j == str2len-1 {
19 | //all string2 are matched now, print till next word
20 | temp := string1[i : i+str2len]
21 | i = i + str2len
22 | for ; i < str1len; i++ {
23 | if []byte(" ")[0] == string1[i] || []byte(".")[0] == string1[i] {
24 | break
25 | }
26 | temp = temp + string(string1[i])
27 | }
28 | matchedString = append(matchedString, temp)
29 | }
30 | }
31 | }
32 | }
33 | return matchedString
34 | }
35 |
36 | func main() {
37 | str1 := "this is the best way to get the best knowledge out there."
38 | str2 := "th"
39 | fmt.Println(wordMatch(str1, str2))
40 | str2 = "kno"
41 | fmt.Println(wordMatch(str1, str2))
42 | fmt.Print("Closing the main function")
43 | }
44 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Python/Array/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bharathshetty4/Programming-Sites-Solved/9003658ca46b3bf7f85779371ae9274f15651f8e/GeeksForGeeks/Python/Array/__init__.py
--------------------------------------------------------------------------------
/GeeksForGeeks/Python/Array/__pycache__/__init__.cpython-34.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bharathshetty4/Programming-Sites-Solved/9003658ca46b3bf7f85779371ae9274f15651f8e/GeeksForGeeks/Python/Array/__pycache__/__init__.cpython-34.pyc
--------------------------------------------------------------------------------
/GeeksForGeeks/Python/Array/__pycache__/arr_insert.cpython-34.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bharathshetty4/Programming-Sites-Solved/9003658ca46b3bf7f85779371ae9274f15651f8e/GeeksForGeeks/Python/Array/__pycache__/arr_insert.cpython-34.pyc
--------------------------------------------------------------------------------
/GeeksForGeeks/Python/Array/__pycache__/arr_printer.cpython-34.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bharathshetty4/Programming-Sites-Solved/9003658ca46b3bf7f85779371ae9274f15651f8e/GeeksForGeeks/Python/Array/__pycache__/arr_printer.cpython-34.pyc
--------------------------------------------------------------------------------
/GeeksForGeeks/Python/Array/__pycache__/arr_remove.cpython-34.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bharathshetty4/Programming-Sites-Solved/9003658ca46b3bf7f85779371ae9274f15651f8e/GeeksForGeeks/Python/Array/__pycache__/arr_remove.cpython-34.pyc
--------------------------------------------------------------------------------
/GeeksForGeeks/Python/Array/__pycache__/arr_search.cpython-34.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/bharathshetty4/Programming-Sites-Solved/9003658ca46b3bf7f85779371ae9274f15651f8e/GeeksForGeeks/Python/Array/__pycache__/arr_search.cpython-34.pyc
--------------------------------------------------------------------------------
/GeeksForGeeks/Python/Array/arr_init.py:
--------------------------------------------------------------------------------
1 | from Array import arr_insert,arr_printer,arr_remove,arr_search
2 |
3 | #Initialize an array variable
4 | arr = []
5 |
6 | #Insert an element
7 | print("Insert some elements to the array")
8 | for i in range (15) :
9 | arr_insert.insert_one(arr,(5*i+9))
10 | arr_printer.print_arr(arr)
11 |
12 | #Remove the last element
13 | print("Remove the last element of an array")
14 | arr_remove.remove_last(arr)
15 | arr_printer.print_arr(arr)
16 |
17 | #1.http://www.geeksforgeeks.org/search-insert-and-delete-in-an-unsorted-array/
18 | #Remove a key from array
19 | print("Remove a key from an array")
20 | delete_element = 34
21 | arr_remove.remove_key(arr,delete_element)
22 | arr_printer.print_arr(arr)
23 |
24 | #Search an element
25 | print("search for a key in an array")
26 | search_element = 39
27 | if(arr_search.linear_search(arr,search_element)):
28 | print("Found the key %s in the array\n"% search_element)
29 | else:
30 | print("%s: Key not found\n" % search_element)
31 |
32 |
33 | #2.http://www.geeksforgeeks.org/search-insert-and-delete-in-a-sorted-array/
34 | #insert an element into sorted array
35 | print("Insert an element to a sorted array")
36 | insert_element = 43
37 | arr_insert.sort_insert(arr,insert_element)
38 | arr_printer.print_arr(arr)
39 |
40 |
41 | #serach an element from sorted array
42 | print("[Binary] search an element from a sorted array")
43 | search_element = 54
44 | n = len(arr) - 1
45 | pos = arr_search.binary_search(arr,0,int(n),search_element)
46 | if (pos == -1 ):
47 | print("%s: Key not found\n" % search_element)
48 | else:
49 | print("Found the key %s in the array in position \n"% search_element)
50 |
51 | #delete an element from sorted array
52 |
53 | print("Delete a given key from an array")
54 | delete_element = 59
55 | arr_remove.sort_remove(arr,delete_element)
56 | arr_printer.print_arr(arr)
--------------------------------------------------------------------------------
/GeeksForGeeks/Python/Array/arr_insert.py:
--------------------------------------------------------------------------------
1 | def insert_one(arr , val ):
2 | arr.append(val)
3 |
4 | def sort_insert(arr, val):
5 | #append a calue to the last, which will append the new value
6 | arr.append(val)
7 | for i in range(len(arr)-2,0,-1):
8 | if(arr[i] < val):
9 | break
10 | arr[i+1] = arr[i]
11 |
12 | arr[i+1] = val
13 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Python/Array/arr_printer.py:
--------------------------------------------------------------------------------
1 | def print_arr(arr):
2 | print("Array List is:",end="")
3 | for i in arr:
4 | print (i,end=",")
5 | print("\n")
--------------------------------------------------------------------------------
/GeeksForGeeks/Python/Array/arr_remove.py:
--------------------------------------------------------------------------------
1 | from Array import arr_search
2 |
3 | def remove_last(arr):
4 | try:
5 | elem = arr.pop()
6 | print("Successfully deleted the last element %s"% elem)
7 | except Exception as e:
8 | print("Error deleting the last element of an array")
9 |
10 | def remove_key(arr,key):
11 | try:
12 | arr.remove(key)
13 | print("Successfully deleted the key %s"% key)
14 | except Exception as e:
15 | print("Key %s not found in array to delete"% key)
16 |
17 | def sort_remove(arr,key):
18 | pos = arr_search.binary_search(arr,0,len(arr)-1,key)
19 | if (pos == -1 ):
20 | print("Key %s is not found to delete\n" % key)
21 | else:
22 | for i in range (pos,len(arr)-1):
23 | arr[i]=arr[i+1]
--------------------------------------------------------------------------------
/GeeksForGeeks/Python/Array/arr_search.py:
--------------------------------------------------------------------------------
1 | def linear_search(arr,element):
2 | for i in arr:
3 | if(i == element):
4 | return 1
5 | return 0
6 |
7 | def binary_search(arr, low, high, element):
8 | if(high 1]) #set defined here
36 | print("Sets example", duplicates)
37 |
38 | #array
39 | a= [1,"c"]
40 | for i in a:
41 | print("Array ex ", i)
42 |
43 |
44 |
45 |
46 | #dictionary
47 | d = {'x': 1}
48 | for key, value in d.items():
49 | print("dicttionary example ",key,value)
50 |
51 |
52 |
53 |
54 | #tuples
55 |
56 | t = ('a','b')
57 | print ("tuples ", t)
58 |
59 |
60 |
61 | #list
62 | l = [1,2]
63 | print("list exaample", l)
64 |
65 |
66 |
67 | #list comprehensions
68 | #used to construct lists in a very natural, easy way, like a mathematician is used to do.
69 | x = [x**2 for x in range(0,5)]
70 | print ("list comprehensions ",x,type(x))
71 |
72 | #prime using list comprehensions
73 | noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
74 | primes = [x for x in range(2, 50) if x not in noprimes]
75 | print("prime using list comprehensions ",primes)
76 |
77 |
78 | #lambda in map
79 | items = [1, 2, 3, 4, 5]
80 | squared = list(map(lambda x: x**2, items))
81 | print("lambda in map ",squared)
82 |
83 | #lambda in filter
84 | #creates a list of elements for which a function returns true
85 | number_list = range(-5, 5)
86 | less_than_zero = list(filter(lambda x: x < 0, number_list))
87 | print("lambda in filter ",less_than_zero)
88 |
89 |
90 | #lambda in reduce
91 | #performing some computation on a list and returning the result
92 | product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
93 | print("lambda in reduce ",product)
94 |
95 |
96 | #ternary operator
97 |
98 | is_fat = True
99 | state = "fat" if is_fat else "not fat"
100 | print ("Ternary example ", state)
101 |
102 |
103 |
104 | #repr() and str()
105 | #repr() is mainly used for debugging and development
106 | s = 'Hello, Geeks.'
107 | print ("str() ex ", str(s), str(2.0/11.0))
108 | print ("repr() ex ", repr(s), repr(2.0/11.0))
109 |
110 |
111 |
112 | #iterator, next, generator, yield
113 | def generator_function():
114 | for i in range(3):
115 | yield i
116 |
117 | gen = generator_function()
118 | print("generator next(0)",next(gen)) # Output: 0
119 | print("generator next(1)",next(gen)) # Output: 1
120 |
121 |
122 |
123 |
124 |
125 |
126 | # try, catch, exception, finally
127 |
128 | try:
129 | file = open('test.txt', 'rb')
130 | except IOError as e:
131 | print("Except example: An error occurred.")
132 | #raise e
133 | finally:
134 | print("Finally example: This would be printed whether or not an exception occurred!")
135 |
136 |
137 |
138 | #Control statements
139 |
140 | # has pass, continue, break options
141 |
142 | #for loop
143 | for i in range (0,1):
144 | print("for loop ex: ",i)
145 |
146 |
147 |
148 | #while loop
149 | count = 0
150 | while (count < 1):
151 | print ('While loop ex: ', count)
152 | count = count + 1
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 | #json encoding and decoding
161 | data = {'apple': 'cat', 'banana':'dog', 'pear':'fish'}
162 | dump_data = json.dumps(data)
163 | print("Dumped json data is ", dump_data)
164 | load_data = json.loads(dump_data)
165 | print("Loaded json data is ", load_data)
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 |
177 |
178 | #classes and multiple inheritance
179 |
180 | """
181 | class X: pass
182 | class Y: pass
183 | class Z: pass
184 |
185 | class A(X,Y): pass // multiple inheritance
186 | class B(Y,Z): pass
187 |
188 | class M(B,A,Z): pass // multilevel inheritance
189 |
190 | # Output:
191 | # [, ,
192 | # , ,
193 | # , ,
194 | # ]
195 |
196 | print(M.mro())
197 |
198 | """
199 |
200 |
201 |
202 |
203 |
204 |
205 | #default dict
206 |
207 |
208 | #multithreading
209 | """
210 | import thread
211 | def shout(n):
212 | print("Thread here", ('n',))
213 |
214 | thread.start_new_thread(shout,1)
215 | """
216 |
217 |
--------------------------------------------------------------------------------
/GeeksForGeeks/Python/matrix_spiral.py:
--------------------------------------------------------------------------------
1 | #https://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/
2 |
3 | #row_cloumn = input().strip().split(" ")
4 |
5 | #row = int(row_cloumn[0])
6 | #column = int(row_cloumn[1])
7 |
8 | #print(row, column)
9 |
10 | def print_one_spiral (matrix, count, size_row, size_col):
11 | print(count,matrix)
12 | #print top row
13 |
14 |
15 | #print right
16 |
17 | #print left
18 |
19 |
20 | def print_spiral (matrix, size_row, size_col):
21 | if size_row % 2 == 1 :
22 | spiral_needed = (size_row/2) +1
23 | else:
24 | spiral_needed = (size_row / 2)
25 |
26 | for i in range(int(spiral_needed)):
27 | print_one_spiral(matrix, i, size_row, size_col)
28 |
29 | matrix = [[1,2,3],
30 | [4,5,6],
31 | [1,2,3],
32 | [4,5,6]
33 | ]
34 | print_spiral(matrix,4,3)
35 |
36 |
--------------------------------------------------------------------------------
/Go_Samples/gin_basic_auth_middleware/server.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | /*
4 | curl request
5 |
6 | curl --request GET \
7 | --url http://localhost:8085/rest/names \
8 | --header 'authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ='
9 |
10 | */
11 | import (
12 | "encoding/base64"
13 | "net/http"
14 | "strings"
15 |
16 | "github.com/gin-gonic/gin"
17 | )
18 |
19 | func AuthMiddleware() gin.HandlerFunc {
20 | //authenticate the creds here
21 | return func(c *gin.Context) {
22 |
23 | s := strings.SplitN(c.Request.Header.Get("Authorization"), " ", 2)
24 | if len(s) != 2 {
25 | c.JSON(http.StatusUnauthorized, "Authorization header is not correct")
26 | c.Abort()
27 | return
28 | }
29 |
30 | b, err := base64.StdEncoding.DecodeString(s[1])
31 | if err != nil {
32 | c.JSON(http.StatusUnauthorized, "Decode error")
33 | c.Abort()
34 | return
35 | }
36 |
37 | pair := strings.SplitN(string(b), ":", 2)
38 | if len(pair) != 2 {
39 | c.JSON(http.StatusUnauthorized, "Decoded string is not correct")
40 | c.Abort()
41 | return
42 | }
43 |
44 | if pair[0] != "username" || pair[1] != "password" {
45 | c.JSON(http.StatusUnauthorized, "Username/password is not correct")
46 | c.Abort()
47 | return
48 | }
49 |
50 | }
51 | }
52 |
53 | func getNames(c *gin.Context) {
54 | var names []string
55 |
56 | names = []string{"bharath", "kumar"}
57 | c.JSON(http.StatusOK, names)
58 | }
59 |
60 | func main() {
61 | //create a new gin router
62 | router := gin.New()
63 | //create a new router group, this will create localhost:/rest
64 | rest := router.Group("/rest")
65 | //create a new group under /rest group, this will create localhost:/rest/names
66 | names := rest.Group("/names")
67 | //All middlewares must be passed will come under USE
68 | names.Use(AuthMiddleware())
69 |
70 | names.GET("", getNames)
71 |
72 | //start the server at port 8085
73 | router.Run(":8085")
74 | }
75 |
--------------------------------------------------------------------------------
/Go_Samples/mux_basic_auth_middleware/server.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | // mux router to authenticate basic auth [base64 encoded] using middleware
4 |
5 | /*
6 | curl request:
7 |
8 | curl --request GET \
9 | --url http://localhost:9900/form \
10 | --header 'authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ='
11 |
12 | */
13 | import (
14 | "encoding/base64"
15 | "net/http"
16 | "strings"
17 |
18 | "github.com/gorilla/mux"
19 | )
20 |
21 | func main() {
22 |
23 | r := mux.NewRouter()
24 | r.HandleFunc("/form", use(myHandler, basicAuth))
25 | http.Handle("/", r)
26 |
27 | http.ListenAndServe(":9900", nil)
28 | }
29 |
30 | // use provides a cleaner interface for chaining middleware for single routes.
31 | // Middleware functions are simple HTTP handlers (w http.ResponseWriter, r *http.Request)
32 | //
33 | // r.HandleFunc("/login", use(loginHandler, rateLimit, csrf))
34 | // r.HandleFunc("/form", use(formHandler, csrf))
35 | // r.HandleFunc("/about", aboutHandler)
36 | //
37 |
38 | func use(h http.HandlerFunc, middlewares ...func(http.HandlerFunc) http.HandlerFunc) http.HandlerFunc {
39 | for _, middleware := range middlewares {
40 | h = middleware(h)
41 | }
42 |
43 | return h
44 | }
45 |
46 | func myHandler(w http.ResponseWriter, r *http.Request) {
47 | w.Write([]byte("Authenticated!"))
48 | return
49 | }
50 |
51 | // Leverages nemo's answer in http://stackoverflow.com/a/21937924/556573
52 | func basicAuth(h http.HandlerFunc) http.HandlerFunc {
53 | return func(w http.ResponseWriter, r *http.Request) {
54 |
55 | w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
56 |
57 | s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
58 | if len(s) != 2 {
59 | http.Error(w, "Not authorized", 401)
60 | return
61 | }
62 |
63 | b, err := base64.StdEncoding.DecodeString(s[1])
64 | if err != nil {
65 | http.Error(w, err.Error(), 401)
66 | return
67 | }
68 |
69 | pair := strings.SplitN(string(b), ":", 2)
70 | if len(pair) != 2 {
71 | http.Error(w, "Not authorized", 401)
72 | return
73 | }
74 |
75 | if pair[0] != "username" || pair[1] != "password" {
76 | http.Error(w, "Not authorized", 401)
77 | return
78 | }
79 |
80 | h.ServeHTTP(w, r)
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/Go_Samples/net_http_login_with_body/server.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | // Simple net/http server which checks the body passed by the curl request for authentication
4 |
5 | /*
6 | curl request to check the code,
7 |
8 | curl --request POST \
9 | --url http://localhost:8085/login \
10 | --header 'content-type: application/json' \
11 | --data '{
12 | "username":"admin",
13 | "password":"pass"
14 | }'
15 |
16 | */
17 | import (
18 | "encoding/json"
19 | "fmt"
20 | "io/ioutil"
21 | "log"
22 | "net/http"
23 | )
24 |
25 | type loginStruct struct {
26 | Username string `json:username`
27 | Password string `json:password`
28 | }
29 |
30 | func LoginCheck(w http.ResponseWriter, r *http.Request) {
31 | userName := "admin"
32 | passWord := "pass"
33 |
34 | var creds loginStruct
35 | credsBody, err := ioutil.ReadAll(r.Body)
36 | if err != nil {
37 | log.Printf("Bad Request: Error while reading")
38 | w.WriteHeader(400)
39 | }
40 | err = json.Unmarshal(credsBody, &creds)
41 |
42 | if err != nil {
43 | log.Printf("Internal Error: Error while unmarshalling")
44 | w.WriteHeader(500)
45 | }
46 |
47 | if creds.Username == "" || creds.Password == "" {
48 | w.WriteHeader(400)
49 | w.Write([]byte("username or password is required"))
50 | }
51 | if creds.Username != userName || creds.Password != passWord {
52 |
53 | w.WriteHeader(401)
54 | } else {
55 |
56 | w.WriteHeader(200)
57 | }
58 |
59 | }
60 |
61 | func main() {
62 | fmt.Printf("Starting the server.. localhost:8085")
63 |
64 | mux := http.NewServeMux()
65 | mux.HandleFunc("/login", LoginCheck)
66 |
67 | log.Fatal(http.ListenAndServe(":8085", mux))
68 | }
69 |
--------------------------------------------------------------------------------
/Go_Samples/samples/simple_any.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | keys, vals := getKeys(map[any]any{1: "one", "two": 2})
7 | fmt.Printf("keys: %v, values: %v", keys, vals)
8 | }
9 |
10 | func getKeys(m map[any]any) ([]any, []any) {
11 | var keys []any
12 | var vals []any
13 | for k, v := range m {
14 | keys = append(keys, k)
15 | vals = append(vals, v)
16 | }
17 | return keys, vals
18 | }
19 |
--------------------------------------------------------------------------------
/Go_Samples/samples/simple_channel.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | // Blogs to read:
9 | // https://www.ardanlabs.com/blog/2018/11/goroutine-leaks-the-forgotten-sender.html
10 | // https://www.dolthub.com/blog/2023-03-13-golang-concurrency-examples/
11 |
12 | type chanStruct struct {
13 | intVal int
14 | strVal string
15 | }
16 |
17 | func main() {
18 | ch := make(chan chanStruct, 0) // unbuffered channel
19 | go updateChannel(ch)
20 | fmt.Println("Hello from channel:", <-ch) // waits until the data is written as it is unbuffered
21 |
22 | bufferedChannelSameThread()
23 | unbufferedWithDifferentThread()
24 | bufferedWithDifferentThread()
25 | }
26 |
27 | func updateChannel(ch chan chanStruct) {
28 | obj := chanStruct{intVal: 4, strVal: "bks"}
29 | ch <- obj
30 | }
31 |
32 | /*
33 | output:
34 | Hello from channel: {4 bks}
35 | */
36 |
37 | func bufferedChannelSameThread() {
38 | // create a buffered channel, which can write as many times as needed without worrying about the write.
39 | queue := make(chan string, 2) // this has to be 2 if we are reading and writing in the same thread
40 | queue <- "one"
41 | queue <- "two"
42 | close(queue) // make sure that you close the channel before ranging over it. Otherwise for loop will never break.
43 |
44 | for elem := range queue {
45 | fmt.Println(elem)
46 | }
47 | }
48 |
49 | /*
50 | output:
51 | one
52 | two
53 | */
54 |
55 | // range for unbuffered channel by using multiple thread
56 | func unbufferedWithDifferentThread() {
57 | done := make(chan string) // you can make this buffered to process faster, as 'range' will wait until the data is written on the channel after a 'read'
58 | go func() {
59 | for _, word := range []string{"foo", "bar", "baz"} {
60 | done <- word
61 | }
62 | close(done)
63 | //done <- "dd" NOT VALID. after closing the channel, you cannot send anything.
64 | }()
65 | for word := range done {
66 | fmt.Println(word)
67 | }
68 | fmt.Println("read after closing the channel:", <-done) // read after closing the channel. VALID.
69 | }
70 |
71 | /*
72 | output:
73 | foo
74 | bar
75 | baz
76 | read after closing the channel:
77 | */
78 |
79 | func bufferedWithDifferentThread() {
80 | ch := make(chan int, 1) // we can write multiple times if the channel is used in different thread even with the less size
81 | for i := 0; i < 4; i++ {
82 | go updateBufferedChannel(i, ch)
83 | }
84 |
85 | for i := 0; i < 2; i++ {
86 | time.Sleep(time.Second)
87 | recvdVal := <-ch
88 | fmt.Println("Reading data", recvdVal)
89 | }
90 | close(ch)
91 | }
92 |
93 | func updateBufferedChannel(val int, ch chan int) {
94 | fmt.Println("writing data", val)
95 | ch <- val
96 | }
97 |
98 | /*
99 | output:
100 | writing data 3
101 | writing data 2
102 | writing data 1
103 | writing data 0
104 | Reading data 3
105 | Reading data 2
106 | */
107 |
108 |
109 | // code for not panic'ing inside the go routine
110 |
111 | type caughtPanicError struct {
112 | val any
113 | stack []byte
114 | }
115 |
116 | func (e *caughtPanicError) Error() string {
117 | return fmt.Sprintf(
118 | "panic: %q\n%s",
119 | e.val,
120 | string(e.stack)
121 | )
122 | }
123 |
124 | func main() {
125 | done := make(chan error)
126 | go func() {
127 | defer func() {
128 | if v := recover(); v != nil {
129 | done <- caughtPanicError{
130 | val: v,
131 | stack: debug.Stack()
132 | }
133 | } else {
134 | done <- nil
135 | }
136 | }()
137 | doSomethingThatMightPanic()
138 | }()
139 | err := <-done
140 | if err != nil {
141 | panic(err)
142 | }
143 | }
144 |
--------------------------------------------------------------------------------
/Go_Samples/samples/simple_defer.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | )
7 |
8 | func deferExample() (err error) {
9 | defer fmt.Println("err1:", err) // nil , err will not get overwritten
10 | err = errors.New("new err")
11 | defer func() {
12 | fmt.Println("err2:", err) // err2: new global err, will get overwritten
13 | }()
14 | defer func(err error) {
15 | err = errors.New("local err")
16 | fmt.Println("err3:", err) // err3: local err
17 | }(err)
18 | err = errors.New("new global err")
19 | return
20 | }
21 |
22 | func main() {
23 | fmt.Println("Hello", deferExample()) // prints 'Hello new global err'
24 | }
25 |
26 | /*
27 | output:
28 | err3: local err
29 | err2: new global err
30 | err1:
31 | Hello new global err
32 | */
33 |
34 | // only the defer body will get run as part of defer. This doesnot work if we are passing a variable though as updating varaible updates
35 | // value inside defer aswell.
36 | func main() {
37 | defer func(tt time.Time) {
38 | fmt.Println("Hello defer", tt) // Hello 2023-03-22 15:22:56.278517 +0100 CET m=+0.000082018
39 | }(time.Now())
40 | fmt.Println("Hello", time.Now()) // Hello 2023-03-22 15:22:56.278517 +0100 CET m=+0.000082118
41 | time.Sleep(1 * time.Second)
42 | fmt.Println("Hello", time.Now()) // Hello 2023-03-22 15:22:57.279791 +0100 CET m=+1.001350562
43 | }
44 |
--------------------------------------------------------------------------------
/Go_Samples/samples/simple_filereader_using_buffer.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bufio"
5 | "fmt"
6 | "io"
7 | "log"
8 | "os"
9 | )
10 |
11 | func main() {
12 | f, err := os.Open("/Users/bharkum3/tmp/sam.config")
13 | if err != nil {
14 | log.Fatal(err)
15 | }
16 | defer f.Close()
17 | r := bufio.NewReader(f)
18 | b := make([]byte, 3)
19 | for {
20 | n, err := r.Read(b)
21 | if err != nil {
22 | if err != io.EOF {
23 | fmt.Println("Error reading file:", err)
24 | }
25 | break
26 | }
27 | fmt.Print(string(b[0:n]))
28 | }
29 | }
30 |
31 | func stdinReader() {
32 | reader := bufio.NewReader(os.Stdin)
33 | fmt.Println("Simple Shell")
34 | fmt.Println("---------------------")
35 |
36 | for {
37 | fmt.Print("-> ")
38 | text, _ := reader.ReadString('\n')
39 | // convert CRLF to LF
40 | text = strings.Replace(text, "\n", "", -1)
41 |
42 | if strings.Compare("hi", text) == 0 {
43 | fmt.Println("hello, Yourself")
44 | }
45 | }
46 |
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/Go_Samples/samples/simple_generics.go:
--------------------------------------------------------------------------------
1 |
2 | import "fmt"
3 |
4 | type allInterface interface {
5 | int | float64 | string
6 | }
7 |
8 | func main() {
9 | n, m, p := 2, 4.5, "stringToo"
10 | fmt.Println(printAll(n), printAll(m), printAll(p))
11 | }
12 |
13 | func printAll[V allInterface](allVar V) V {
14 | return allVar
15 | }
16 |
--------------------------------------------------------------------------------
/Go_Samples/samples/simple_http.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "bytes"
6 | "io/ioutil"
7 | "net/http"
8 | )
9 |
10 | func main() {
11 | url := "http://restapi3.apiary-mock.com/notes"
12 | fmt.Println("URL:>", url)
13 |
14 | var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`)
15 | req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
16 | req.Header.Set("X-Custom-Header", "myvalue")
17 | req.Header.Set("Content-Type", "application/json")
18 |
19 | client := &http.Client{}
20 | resp, err := client.Do(req)
21 | if err != nil {
22 | panic(err)
23 | }
24 | defer resp.Body.Close()
25 |
26 | fmt.Println("response Status:", resp.Status)
27 | fmt.Println("response Headers:", resp.Header)
28 | body, _ := ioutil.ReadAll(resp.Body)
29 | fmt.Println("response Body:", string(body))
30 | }
31 |
--------------------------------------------------------------------------------
/Go_Samples/samples/simple_interface.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "sync"
6 | "time"
7 | )
8 |
9 | // SafeCounter is safe to use concurrently.
10 | type SafeCounter struct {
11 | v map[string]int
12 | mux sync.Mutex
13 | }
14 |
15 | // Inc increments the counter for the given key.
16 | func (c *SafeCounter) Inc(key string) {
17 | c.mux.Lock()
18 | // Lock so only one goroutine at a time can access the map c.v.
19 | c.v[key]++
20 | c.mux.Unlock()
21 | }
22 |
23 | // Value returns the current value of the counter for the given key.
24 | func (c *SafeCounter) Value(key string) int {
25 | c.mux.Lock()
26 | // Lock so only one goroutine at a time can access the map c.v.
27 | defer c.mux.Unlock()
28 | return c.v[key]
29 | }
30 |
31 | func main() {
32 | //c := new(SafeCounter) // does not work, map will give nil pointer
33 | c := &SafeCounter{v: make(map[string]int)} // SafeCounter{v: make(map[string]int)} works too
34 | for i := 0; i < 1000; i++ {
35 | go c.Inc("somekey")
36 | }
37 |
38 | time.Sleep(time.Second)
39 | fmt.Println(c.Value("somekey"))
40 | }
41 |
--------------------------------------------------------------------------------
/Go_Samples/samples/simple_pointer.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | a := 2
7 | b := &a
8 | fmt.Println(a) // 2
9 | fmt.Println(*b) // 2
10 |
11 | *b = 3
12 | fmt.Println(a) // 3
13 | fmt.Println(*b) // 3
14 |
15 | a = 4
16 | fmt.Println(a) // 4
17 | fmt.Println(*b) // 4
18 | }
19 |
20 | /*
21 | Both a and *b refer to the same variable internally. Hence the changing the value of one reflects in another.
22 | Also, * and & can be used together as well. But they will cancel out each other.
23 | Hence these are all equivalent,
24 | a
25 | *&a
26 | b
27 | *&b
28 | &*b
29 |
30 | Note: *a is not a valid operation as a is not a pointer
31 |
32 | */
33 |
34 | // pass the pointer and use the pointer
35 | func incrInt(d *int) {
36 | *d++
37 | }
38 |
39 | func inorder(node *TreeNode, list * []int) {
40 | if node == nil {
41 | return
42 | }
43 | *list = append(*list,node.Val)
44 | }
45 |
46 | func more_examples() {
47 | c := new(Person) // returns pointer
48 | c.Name = "Catherine"
49 | fmt.Println(c.Name) // prints: Catherine
50 | d := c
51 | d.Name = "Daniel"
52 | fmt.Println(c.Name) // prints: Daniel
53 | // Adding an Asterix before a pointer dereferences the pointer. This does not work for data type variable such as 'a' above
54 | i := *d
55 | i.Name = "Ines"
56 | fmt.Println(c.Name) // prints: Daniel
57 | fmt.Println(d.Name) // prints: Daniel
58 | fmt.Println(i.Name) // prints: Ines
59 | }
60 |
--------------------------------------------------------------------------------
/Go_Samples/samples/simple_select.go:
--------------------------------------------------------------------------------
1 | // Go program to illustrate the
2 | // concept of select statement
3 | package main
4 |
5 | import (
6 | "fmt"
7 | "sync"
8 | "time"
9 | )
10 |
11 | func portal1(channel1 chan string, wg *sync.WaitGroup) {
12 | channel1 <- "Welcome to channel 1"
13 | wg.Done()
14 | }
15 |
16 | func portal2(channel2 chan string, wg *sync.WaitGroup) {
17 | channel2 <- "Welcome to channel 2"
18 | wg.Done()
19 | }
20 |
21 | // main function
22 | func main() {
23 | var wg sync.WaitGroup
24 | wg.Add(2)
25 | // Creating channels
26 | // NOTE: make it buffered channel, so that when we cant read this channel, it will not end up leaking go routine
27 | R1 := make(chan string, 1)
28 | R2 := make(chan string, 1)
29 |
30 | // calling function 1 and
31 | // function 2 in goroutine
32 | go portal1(R1, &wg)
33 | go portal2(R2, &wg)
34 |
35 | // Go’s select lets you wait on multiple channel operations.
36 | // can have 'default:' case or timer inside.
37 | // NOTE: If a select statement has non-blocking case like default or timer, it can choose any one of those and here
38 | // in this case we may never hit the timer at all
39 |
40 | select {
41 | // case 1 for portal 1
42 | case op1 := <-R1:
43 | fmt.Println(op1)
44 |
45 | // case 2 for portal 2
46 | case op2 := <-R2:
47 | fmt.Println(op2)
48 |
49 | case <-time.After(time.Second):
50 | fmt.Printf("\nTimeout\n")
51 | }
52 | wg.Wait()
53 | // make sure that both are closed
54 | close(R1)
55 | close(R2)
56 | }
57 |
--------------------------------------------------------------------------------
/Go_Samples/samples/simple_slices.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | /*
6 | Everything in Go is passed by value, slices too. But a slice value is a header,
7 | describing a contiguous section of a backing array, and a slice value only contains
8 | a pointer to the array where the elements are actually stored. The slice value does
9 | not include its elements (unlike arrays).
10 |
11 | So when you pass a slice to a function, a copy will be made from this header, including
12 | the pointer, which will point to the same backing array. Modifying the elements of the
13 | slice implies modifying the elements of the backing array, and so all slices which share
14 | the same backing array will "observe" the change.
15 |
16 | type SliceHeader struct {
17 | Data uintptr
18 | Len int
19 | Cap int
20 | }
21 |
22 | */
23 |
24 | /*
25 | The contents of a slice argument can be modified by a function, but its header cannot.
26 | The length stored in the slice variable is not modified by the call to the function,
27 | since the function is passed a copy of the slice header, not the original. Thus if we want
28 | to write a function that modifies the header, we must return it as a result parameter, just as we have done here.
29 | */
30 |
31 | func updateSlice(mySlice []string) {
32 | mySlice[0] = "oneupdated"
33 | mySlice = append(mySlice, "three") // append did not work
34 | // mySlice[3] = "oneupdated" //index out of range panic
35 | myLocalSlice := mySlice
36 | myLocalSlice[1] = "twoupdated" // will not update the original slice, works with ptr
37 | }
38 |
39 | func updateSliceWithPtr(mySlice *[]string) {
40 | (*mySlice)[0] = "oneptr"
41 | (*mySlice) = append((*mySlice), "threePtr") // append worked
42 | }
43 |
44 | func main() {
45 | var mySlice = []string{"one", "two"}
46 | fmt.Println(mySlice) //[one two]
47 | updateSlice(mySlice)
48 | fmt.Println(mySlice) // [oneupdated two]
49 | updateSliceWithPtr(&mySlice)
50 | fmt.Println(mySlice) // [oneptr two threePtr]
51 | myMainLocalSlice := mySlice
52 | myMainLocalSlice[1] = "twoupdated" // will update the original slice value too
53 | fmt.Println(mySlice) // [oneptr twoupdated threePtr]
54 | }
55 |
56 | /*
57 | op:
58 |
59 | [one two]
60 | [oneupdated two]
61 | [oneptr two threePtr]
62 | [oneptr twoupdated threePtr]
63 |
64 | */
65 |
--------------------------------------------------------------------------------
/Go_Samples/samples/simple_string_concat.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "strings"
5 | "fmt"
6 | )
7 |
8 | func stringsBuilder() {
9 | // ZERO-VALUE:
10 | //
11 | // It's ready to use from the get-go.
12 | // You don't need to initialize it.
13 | var sb strings.Builder
14 | for i := 0; i < 1000; i++ {
15 | sb.WriteString("a")
16 | }
17 | fmt.Println(sb.String())
18 | }
19 |
20 | func bytesBuffer(b *testing.B) {
21 | var buffer bytes.Buffer
22 | for n := 0; n < 1000; n++ {
23 | buffer.WriteString("x")
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Go_Samples/samples/simple_unmarshal.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | )
7 |
8 | func main() {
9 | //unmarshal into interface without defining the struct
10 | birdJson := `{"birds":{"pigeon":"likes to perch","eagle":"bird of prey"},"animals":"none"}`
11 | var result map[string]interface{}
12 | json.Unmarshal([]byte(birdJson), &result)
13 | birds := result["birds"].(map[string]interface{})
14 | for key, value := range birds {
15 | fmt.Println(key, value.(string))
16 | }
17 | unmarsahlEx()
18 | }
19 |
20 | type Bird struct {
21 | Species string `json:"birdType"`
22 | Description string `json:"what it does"`
23 | }
24 |
25 | // unmarshal with the struct
26 | func unmarsahlEx() {
27 | birdJson := `{"birdType": "pigeon","what it does": "likes to perch on rocks"}`
28 | var bird Bird
29 | json.Unmarshal([]byte(birdJson), &bird)
30 | fmt.Printf("%+v\n", bird)
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/Go_Samples/samples/simple_wg_routines.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "sync"
6 | )
7 | // good read: https://about.sourcegraph.com/blog/building-conc-better-structured-concurrency-for-go
8 | func runner1(wg *sync.WaitGroup) {
9 | defer wg.Done() // This decreases counter by 1
10 | fmt.Print("\nI am first runner")
11 |
12 | }
13 |
14 | func runner2(wg *sync.WaitGroup) {
15 | defer wg.Done()
16 | fmt.Print("\nI am second runner")
17 | }
18 |
19 | func main() {
20 | var wg sync.WaitGroup
21 | wg.Add(2)
22 | go runner1(&wg)
23 | go runner2(&wg)
24 | wg.Wait()
25 | }
26 |
--------------------------------------------------------------------------------
/HackerEarth/Akash and the Assignment.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 |
4 | int main()
5 | {
6 | int m,n,i;
7 | int f,s,d;
8 | cin>>m;
9 | cin>>n;
10 | char a[100000];
11 | for(i=0;i>a[i];
14 | }
15 |
16 | for(i=0;i>f;
18 | cin>>s;
19 | cin>>d;
20 | int num=f-2+d;
21 | cout<
2 |
3 | int main()
4 | {
5 | unsigned int count,i,a,b,c,n,j;
6 | scanf("%d",&n);
7 | for(j=0;jb)
23 | break;
24 | count++;
25 | }
26 | printf("%u\n",count);
27 | }
28 | }
--------------------------------------------------------------------------------
/HackerEarth/KGBD.py:
--------------------------------------------------------------------------------
1 | def kc_gcd(a, b):
2 | n1 = a
3 | n2 = b
4 | while (a > 0 and b > 0):
5 | a = a - b
6 | a, b = b, a
7 | while (n1 != n2):
8 | if (n1 > n2):
9 | n1 = n1 - n2
10 | else:
11 | n2 = n2 - n1
12 | return (n1 == a + b)
13 |
14 |
15 | n = int(input().strip())
16 | while (n >= 1):
17 | count = 0
18 | data = int(input().strip())
19 | for i in range(1, data + 1):
20 | for j in range(1, data + 1):
21 | if (kc_gcd(i, j)):
22 | count = count + 1
23 | n = n - 1
24 | print(count)
25 |
--------------------------------------------------------------------------------
/HackerEarth/Mind Palaces.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | using namespace std;
3 |
4 | int main()
5 | {
6 | int m,n,i,j;
7 | cin>>m;
8 | cin>>n;
9 | int mat[m][n];
10 | for(i=0;i>mat[i][j];
13 | }
14 | }
15 |
16 | int cas;
17 | cin>>cas;
18 | int k;
19 | for(k=0;k>ser;
23 | int flag=0;
24 | for(i=0;i
2 | using namespace std;
3 |
4 | int main()
5 | {
6 | int n,row,col;
7 | cin>>n;
8 | int i,j,k;
9 | int a[1000][1000];
10 |
11 | for(int i=0;i>row;
13 |
14 | int sum=0;
15 | //input to array
16 | for(j=0;j<=row-1;j++){
17 | for(k=0;k<=row-1;k++)
18 | {
19 |
20 | a[j][k]=abs(j-k);
21 |
22 | }
23 | }
24 | for(j=0;j
2 |
3 | int main()
4 | {
5 | long int m,n,dif;
6 | long int f,junk,s,i;
7 | scanf("%d",&m);
8 | scanf("%d",&n);
9 | scanf("%d%d",&f,&s);
10 | dif=s-f+1;
11 | for(i=0;i
2 | using namespace std;
3 |
4 | int main()
5 | {
6 | double n;
7 | double i=0;
8 | cin>>n;
9 | static double num1=0,num2=0;
10 | for(i=0;i>input;
13 | double j=0;
14 | double rowcount=0,count=0;
15 | while(input[j]!='\0'){
16 |
17 | if(input[j]=='C'){
18 | count=count+1;
19 |
20 | rowcount=rowcount+1;
21 | if(count>num1) num1=count;
22 | if(rowcount>num2) num2=rowcount;
23 | }
24 | else rowcount=0;
25 | j++;
26 | }
27 | }
28 | cout<= 10):
18 | newcount = newcount + 1
19 |
20 | print(newcount)
21 |
--------------------------------------------------------------------------------
/HackerEarth/Will you be my Friend.java:
--------------------------------------------------------------------------------
1 | import java.io.BufferedReader;
2 | import java.io.InputStreamReader;
3 |
4 |
5 | class TestClass {
6 | public static void main(String args[] ) throws Exception {
7 |
8 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
9 | String basef = br.readLine();
10 | int base1 = Integer.parseInt(basef);
11 | int totalf=0;
12 | int base2;
13 | String line = br.readLine();
14 | int N = Integer.parseInt(line);
15 | //String bases = br.readLine();
16 | String []bases=br.readLine().split(" ");
17 | for(int i=0;i= 0 and next % 10 == 0):
9 | count = count + 1
10 | next = next / 10
11 | print
12 | count
13 |
--------------------------------------------------------------------------------
/HackerEarth/algorithms/PalindromeCount.go:
--------------------------------------------------------------------------------
1 | //https://www.hackerearth.com/practice/algorithms/dynamic-programming/2-dimensional/practice-problems/algorithm/palindrome-count-1/
2 | package main
3 |
4 | import (
5 | "fmt"
6 | )
7 |
8 | func isPal(str string) bool {
9 | n := len(str)
10 | for i := 0; i < n/2; i++ {
11 | if string(str[i]) != string(str[n-1-i]){
12 | return false
13 | }
14 | }
15 | return true
16 | }
17 |
18 | func countPalindromes(str string, n int) int {
19 | count := 0
20 | for i := 0; i < n-1; i++ {
21 | for j := i + 1; j < n; j++ {
22 | if string(str[i]) == string(str[j]) {
23 | if isPal(str[i : j+1]) {
24 | count++
25 | }
26 | }
27 | }
28 | }
29 | return count
30 | }
31 | func main() {
32 | s := "dskjkd"
33 | n := len(s)
34 | c := countPalindromes(s, n)
35 | fmt.Print(n + c)
36 | }
37 |
--------------------------------------------------------------------------------
/HackerEarth/algorithms/possibleSums.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | func getPossSums(nums []int) int {
8 | count := 0
9 | uniqueNums := make(map[int]bool)
10 | uniqueNums[0] = true
11 | n := len(nums)
12 | for i := 0; i < n; i++ {
13 | if uniqueNums[nums[i]] == false {
14 | uniqueNums[nums[i]] = true
15 | count++
16 | }
17 | for j := i + 1; j < n; j++ {
18 | if uniqueNums[nums[i]+nums[j]] == false {
19 | uniqueNums[nums[i]+nums[j]] = true
20 | count++
21 | }
22 | }
23 | }
24 |
25 | fmt.Println(uniqueNums)
26 | return count + 1
27 | }
28 |
29 | func main() {
30 | nums := []int{1, 2, 3}
31 | sums := getPossSums(nums)
32 | fmt.Println(sums)
33 | }
34 |
--------------------------------------------------------------------------------
/HackerEarth/algorithms/xorry.go:
--------------------------------------------------------------------------------
1 | //https://www.hackerearth.com/problem/algorithm/xorray
2 | package main
3 |
4 | import (
5 | "fmt"
6 | )
7 |
8 | //donot call this function everytime, calculate at once for the maximum and use it every time
9 | func getXOR(digit int) int {
10 | var xor = make([]int,digit+1)
11 | xor[1] = 1
12 |
13 | for i := 2; i <= digit; i++ {
14 | var val = 1
15 | for j:= 2;j= 0; i-- {
13 | count = count + int(countString[i]-48)*dec
14 | dec = dec * 10
15 | }
16 | return count
17 | }
18 |
19 | func expandString(compStr string) map[string]int {
20 | var charCount = make(map[string]int)
21 | lastIdx := 0
22 | lastChar := string(compStr[0])
23 | for i := 1; i < len(compStr); i++ {
24 | cnt := 0
25 | if string(compStr[i]) >= "a" && string(compStr[i]) <= "z" {
26 | cnt = getCharCount(compStr[lastIdx+1 : i])
27 | charCount[lastChar] = charCount[lastChar] + cnt
28 |
29 | lastChar = string(compStr[i])
30 | lastIdx = i
31 | }
32 | if i == len(compStr)-1 {
33 | cnt = getCharCount(compStr[lastIdx+1:])
34 | charCount[lastChar] = charCount[lastChar] + cnt
35 |
36 | }
37 | }
38 | return charCount
39 | }
40 |
41 | func getChar(charCount [27]int, index []int) {
42 | tmpA := int('a')
43 | for _, idx := range index {
44 | //fmt.Printf("%d:",idx)
45 | flag := false
46 | for i := 1; i <= 26; i++ {
47 | if idx <= 0 {
48 | fmt.Println(string(tmpA + i - 2))
49 | flag = true
50 | break
51 | }
52 | idx = idx - charCount[i]
53 | }
54 | if !flag {
55 | if idx <= 0 {
56 | fmt.Println("z")
57 | } else {
58 | fmt.Println("-1")
59 | }
60 | }
61 | }
62 | }
63 |
64 | func main() {
65 | charCount := expandString("a1b5n7b3a8z3")
66 | var charIdx [27]int
67 | for i := 1; i <= 26; i++ {
68 | tmp := int('a')
69 | charIdx[i] = charCount[string(tmp+i-1)]
70 | }
71 |
72 | //fmt.Printf("a count is: %v\n", charCount)
73 | indexes := []int{2, 3, 4, 40, 800, 21}
74 | getChar(charIdx, indexes)
75 | }
76 |
--------------------------------------------------------------------------------
/HackerRank/30_days_of_code/10_binary_numbers.py:
--------------------------------------------------------------------------------
1 | #!/bin/python
2 |
3 | import sys
4 |
5 |
6 | n = int(raw_input().strip())
7 | count=0
8 | max=0
9 | while(n>0):
10 | digit=n%2
11 | if(digit==1):
12 | count = count + 1
13 | if(count > max):
14 | max=count
15 | else:
16 | count=0
17 | n=n/2
18 |
19 | print max
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/HackerRank/30_days_of_code/11_2d_arrays.py:
--------------------------------------------------------------------------------
1 | #!/bin/python
2 |
3 | import sys
4 |
5 |
6 | arr = []
7 | for arr_i in xrange(6):
8 | arr_temp = map(int,raw_input().strip().split(' '))
9 | arr.append(arr_temp)
10 | maxn=-60
11 | for i in range(0,4):
12 | for j in range(0,4):
13 | inp= (arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2])
14 | if (inp >= maxn):
15 | maxn=inp
16 |
17 | print maxn
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/HackerRank/30_days_of_code/12_inheritance.py:
--------------------------------------------------------------------------------
1 | class Student(Person):
2 | def __init__(self, firstName, lastName, idNumber, scores):
3 | self.firstName = firstName
4 | self.lastName = lastName
5 | self.idNumber = idNumber
6 | self.scores=scores
7 | def calculate(self):
8 | sum = 0
9 | count = 0
10 | for i in scores:
11 | sum =sum +i
12 | count = count +1
13 | avg=sum/count
14 | if(avg<40):
15 | return 'T'
16 | elif(avg<55):
17 | return 'D'
18 | elif(avg<70):
19 | return 'P'
20 | elif(avg<80):
21 | return 'A'
22 | elif(avg<90):
23 | return 'E'
24 | return 'O'
25 |
--------------------------------------------------------------------------------
/HackerRank/30_days_of_code/15_linked_list.py:
--------------------------------------------------------------------------------
1 | def insert(self,head,data):
2 | temp = Node(data)
3 | temp.next=None
4 | current = head
5 | if(head==None):
6 | current=temp
7 | else:
8 | while(head.next!=None):
9 | head=head.next
10 | head.next=temp
11 | return current
12 |
13 |
--------------------------------------------------------------------------------
/HackerRank/30_days_of_code/18_queues_and_stacks.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | # Write your code here
3 | stackstring = []
4 | queuestring = []
5 | def pushCharacter(self,ch):
6 | self.stackstring.extend(ch)
7 |
8 | def enqueueCharacter(self,ch):
9 | self.queuestring.extend(ch)
10 |
11 | def popCharacter(self):
12 | char = self.stackstring.pop()
13 | return char
14 | def dequeueCharacter(self):
15 | char = self.queuestring.pop(0)
16 | return char
17 |
--------------------------------------------------------------------------------
/HackerRank/30_days_of_code/20_sorting.py:
--------------------------------------------------------------------------------
1 | #!/bin/python
2 |
3 | import sys
4 |
5 | def passhere(a):
6 | alen=len(a)
7 | count=0
8 | for i in range(alen):
9 | for j in range(alen-1):
10 | if(a[j]>a[j+1]):
11 | count = count + 1
12 | temp=a[j]
13 | a[j]=a[j+1]
14 | a[j+1]=temp
15 | print "Array is sorted in",count, "swaps."
16 | print "First Element:", a[0]
17 | print "Last Element:", a[len(a)-1]
18 |
19 | n = int(raw_input().strip())
20 | a = map(int,raw_input().strip().split(' '))
21 | passhere(a)
22 |
--------------------------------------------------------------------------------
/HackerRank/30_days_of_code/29_bitwise_and.py:
--------------------------------------------------------------------------------
1 | #!/bin/python3
2 |
3 | import sys
4 |
5 |
6 | t = int(input().strip())
7 | for a0 in range(t):
8 | maxnum=0
9 | n,k = input().strip().split(' ')
10 | n,k = [int(n),int(k)]
11 | print(k-1 if ((k-1) | k) <= n else k-2)
12 |
13 |
14 |
--------------------------------------------------------------------------------
/HackerRank/30_days_of_code/9_recursion.py:
--------------------------------------------------------------------------------
1 | # Enter your code here. Read input from STDIN. Print output to STDOUT
2 |
3 | def factorial(n):
4 | if(n<=1):
5 | return 1
6 | else:
7 | num=n*factorial(n-1)
8 | return num
9 |
10 | n=int(raw_input())
11 | factn=factorial(n)
12 | print factn
13 |
14 |
--------------------------------------------------------------------------------
/HackerRank/DataStructure/Array/2D_Array.go:
--------------------------------------------------------------------------------
1 | package main
2 | import "fmt"
3 | //code link: https://www.hackerrank.com/challenges/2d-array
4 | func main() {
5 | arr := [6][6]int{}
6 | var maxval int
7 | for i:=0;i<6;i++{
8 | for j:=0;j<6;j++{
9 | fmt.Scanf("%d",&arr[i][j])
10 | }
11 | }
12 | maxval = -10000
13 | for i:=0;i<4;i++{
14 | for j:=0;j<4;j++{
15 | total := (arr[i][j])+(arr[i][j+1])+(arr[i][j+2])+(arr[i+1][j+1])+(arr[i+2][j])+(arr[i+2][j+1])+(arr[i+2][j+2])
16 | if (total > maxval){
17 | maxval = total
18 | }
19 | }
20 | }
21 | fmt.Println(maxval)
22 | }
23 |
--------------------------------------------------------------------------------
/HackerRank/DataStructure/Array/Arrays_DS.go:
--------------------------------------------------------------------------------
1 | package main
2 | //code link: https://www.hackerrank.com/challenges/arrays-ds
3 | import (
4 | "fmt"
5 | )
6 | func main() {
7 | //Enter your code here. Read input from STDIN. Print output to STDOUT
8 | var size int
9 | fmt.Scanf("%d", &size)
10 | vals := make([]string,size)
11 | for j:= 0 ; j= k {
18 | sum := int32(0)
19 | for i := flwLen - 1; i >= flwLen-k; i-- {
20 | sum = sum + c[i]
21 | }
22 | cost = cost + (iterNum+1)*sum
23 | }
24 | iterNum++
25 | flwLen = flwLen - k
26 | if flwLen < k {
27 | break
28 | }
29 | }
30 | for i := flwLen - 1; i >= 0; i-- {
31 | cost = cost + (iterNum+1)*c[i]
32 | }
33 |
34 | return cost
35 | }
36 |
37 | func main() {
38 | k := int32(2)
39 | c := []int32{2, 5, 6}
40 | res := getMinimumCost(k, c)
41 | fmt.Println(res)
42 | }
43 |
--------------------------------------------------------------------------------
/HackerRank/interview-preparation-kit/arrays/minimum-swap-2.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | //not working
4 | import (
5 | "fmt"
6 | )
7 |
8 | func minimumSwaps(arr []int32) int32 {
9 | fmt.Println(arr)
10 | if len(arr) <= 1 {
11 | return 0
12 | }
13 | var swap int32
14 |
15 | for i:=0;i arr[i+1] {
17 | for j:=i+1;j 3 {
39 | res = 2 * (count - 3)
40 | }
41 | return res
42 | }
43 |
44 | func main() {
45 | nums := []int64{1, 2, 2, 4}
46 | r := int64(2)
47 | res := countTriplets(nums, r)
48 | fmt.Println(res)
49 | }
50 |
--------------------------------------------------------------------------------
/HackerRank/interview-preparation-kit/dictAndmaps/sherlock-and-anagrams.go:
--------------------------------------------------------------------------------
1 | //https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=dictionaries-hashmaps
2 |
3 | //not working
4 | package main
5 |
6 | import (
7 | "fmt"
8 | )
9 |
10 | // Complete the sherlockAndAnagrams function below.
11 | func sherlockAndAnagrams(s string) int32 {
12 | var ana int32
13 | var count int
14 | strMap := make(map[string]int)
15 |
16 | for i := range s {
17 | strMap[string(s[i])] = strMap[string(s[i])] + 1
18 | if strMap[string(s[i])] == 2 {
19 | strMap[string(s[i])] = 0
20 | count++
21 | }
22 | }
23 |
24 | return ana
25 | }
26 |
27 | func main() {
28 |
29 | s := "abba"
30 | result := sherlockAndAnagrams(s)
31 |
32 | fmt.Printf("%d\n", result)
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/HackerRank/interview-preparation-kit/linkedLists/reverseDoublyLL.go:
--------------------------------------------------------------------------------
1 | //https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=linked-lists
2 | package main
3 |
4 | import (
5 | "fmt"
6 | )
7 |
8 | type DoublyLinkedListNode struct {
9 | data int32
10 | next *DoublyLinkedListNode
11 | prev *DoublyLinkedListNode
12 | }
13 |
14 | type DoublyLinkedList struct {
15 | head *DoublyLinkedListNode
16 | tail *DoublyLinkedListNode
17 | }
18 |
19 | func (doublyLinkedList *DoublyLinkedList) insertNodeIntoDoublyLinkedList(nodeData int32) {
20 | node := &DoublyLinkedListNode{
21 | next: nil,
22 | prev: nil,
23 | data: nodeData,
24 | }
25 |
26 | if doublyLinkedList.head == nil {
27 | doublyLinkedList.head = node
28 | } else {
29 | doublyLinkedList.tail.next = node
30 | node.prev = doublyLinkedList.tail
31 | }
32 |
33 | doublyLinkedList.tail = node
34 | }
35 |
36 | func printLinkedList(head *DoublyLinkedListNode) {
37 | node := head
38 | for {
39 | if node == nil {
40 | fmt.Println()
41 | return
42 | }
43 | fmt.Printf("%d->", node.data)
44 | node = node.next
45 | }
46 | }
47 |
48 | // Complete the reverse function below.
49 |
50 | /*
51 | * For your reference:
52 | *
53 | * DoublyLinkedListNode {
54 | * data int32
55 | * next *DoublyLinkedListNode
56 | * prev *DoublyLinkedListNode
57 | * }
58 | *
59 | */
60 | func reverse(head *DoublyLinkedListNode) *DoublyLinkedListNode {
61 | var next *DoublyLinkedListNode
62 | cur := head
63 | for {
64 | if cur == nil {
65 | return cur
66 | }
67 | next = cur.next
68 |
69 | cur.next = cur.prev
70 | cur.prev = next
71 |
72 | if next == nil {
73 | return cur
74 | }
75 | cur = next
76 | }
77 |
78 | return cur
79 | }
80 |
81 | func main() {
82 | llist := DoublyLinkedList{}
83 | llist.insertNodeIntoDoublyLinkedList(1)
84 | llist.insertNodeIntoDoublyLinkedList(4)
85 | llist.insertNodeIntoDoublyLinkedList(5)
86 | printLinkedList(llist.head)
87 | llist1 := reverse(llist.head)
88 | printLinkedList(llist1)
89 | }
90 |
--------------------------------------------------------------------------------
/HackerRank/interview-preparation-kit/stack/balancedBrackets.go:
--------------------------------------------------------------------------------
1 | // https://www.hackerrank.com/challenges/balanced-brackets/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=stacks-queues
2 | // 3/18 is failing
3 | package main
4 |
5 | import "fmt"
6 |
7 | type Stack []string
8 |
9 | func (s Stack) ISEmpty() bool { return len(s) == 0 }
10 |
11 | func (s *Stack) Push(v string) {
12 | (*s) = append((*s), v)
13 | }
14 |
15 | func (s *Stack) Pop() string {
16 | v := (*s)[len(*s)-1]
17 | (*s) = (*s)[:len(*s)-1]
18 | return v
19 | }
20 |
21 | // Complete the isBalanced function below.
22 | func isBalanced(s string) string {
23 | stack := Stack{}
24 | for _,val := range (s){
25 | v := string(val)
26 | switch v {
27 | case "(","{","[":
28 | stack.Push(v)
29 | case "}":
30 | if stack.ISEmpty() { return "NO"}
31 | poppedVal := stack.Pop()
32 | if poppedVal != "{" {
33 | return "NO"
34 | }
35 | case "]":
36 | if stack.ISEmpty() { return "NO"}
37 | poppedVal := stack.Pop()
38 | if poppedVal != "[" {
39 | return "NO"
40 | }
41 | case ")":
42 | if stack.ISEmpty() { return "NO"}
43 | poppedVal := stack.Pop()
44 | if poppedVal != "(" {
45 | return "NO"
46 | }
47 | }
48 | }
49 | return "YES"
50 | }
51 |
52 | func main() {
53 | s := "}][}}(}][))]"
54 | fmt.Println(isBalanced(s))
55 | }
56 |
--------------------------------------------------------------------------------
/HackerRank/interview-preparation-kit/stack/stack.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | )
6 |
7 | type StackOld []int
8 |
9 | func (s StackOld) ISEmpty() bool { return len(s) == 0 }
10 |
11 | func (s *StackOld) Push(v int) {
12 | (*s) = append((*s), v)
13 | }
14 |
15 | func (s *StackOld) Pop() int {
16 | v := (*s)[len(*s)-1]
17 | (*s) = (*s)[:len(*s)-1]
18 | return v
19 | }
20 |
21 | func main() {
22 | s := StackOld{}
23 | fmt.Println(s.ISEmpty())
24 | s.Push(4)
25 | s.Push(5)
26 | s.Push(6)
27 | fmt.Println("Before Stack", s)
28 | s.Pop()
29 | fmt.Println("After Stack", s)
30 | }
31 |
--------------------------------------------------------------------------------
/HackerRank/other_programs/HandShake.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 |
6 | int main() {
7 | unsigned int a,b,i,shake;
8 | scanf("%d",&a);
9 | for(i=0;i
2 | #include
3 | #include
4 | #include
5 | #include
6 | void insertionSort(int ar_size, int * ar) {
7 | int n=ar_size,i,j;
8 | int temp=ar[n-1];
9 | for(i=n-1;i>=0;i--){
10 | if(temp>ar[i-1]){
11 | ar[i]=temp;
12 | break;
13 | }else ar[i]=ar[i-1];
14 |
15 | for(j=0;j
2 | #include
3 | #include
4 | #include
5 | #include
6 | int main(void) {
7 |
8 | int ar_size;
9 | scanf("%d", &ar_size);
10 | int ar[ar_size], _ar_i;
11 | for(_ar_i = 0; _ar_i < ar_size; _ar_i++) {
12 | ar[_ar_i]=0;
13 | }
14 | for(_ar_i = 0; _ar_i < ar_size; _ar_i++) {
15 | scanf("%d", &ar[_ar_i]);
16 | }
17 |
18 | int n=ar_size,i,j;
19 | int temp=0,temp1;
20 | for(i=1;i
2 | #include
3 | #include
4 | #include
5 | #include
6 | int lonelyinteger(int a_size, int* a) {
7 | int i,j,k,flag;
8 | for(i=0;i
2 | #include
3 | #include
4 | #include
5 |
6 | int main() {
7 | int a,b,i;
8 | scanf("%d",&a);
9 | for(i=0;i
2 | #include
3 | #include
4 | #include
5 |
6 | int main() {
7 | char in_string[4000];
8 | int present[27],i;
9 | int cur_str;
10 | char cur_string;
11 | for(i=1;i<=26;i++) present[i]=0;
12 | gets(in_string);
13 | int in_len=strlen(in_string);
14 | for(i=0;ia[j]){
50 | chang=chang+b[j]-a[j];
51 |
52 | }
53 | }
54 |
55 | System.out.print(chang+"\n");
56 |
57 | }
58 |
59 |
60 |
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/HackerRank/other_programs/angry_professor.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | using namespace std;
7 |
8 |
9 | int main() {
10 | int n;
11 | cin>>n;
12 | int m,c;
13 | int t;
14 | while(n--){
15 | cin>>m;
16 | cin>>c;
17 | while(m--){
18 | cin>>t;
19 | if(t<=0) c--;
20 | }
21 | if(c<=0){
22 | cout<<"NO"<<"\n";
23 | }else cout<<"YES\n";
24 |
25 |
26 | }
27 | return 0;
28 | }
29 |
30 |
--------------------------------------------------------------------------------
/HackerRank/other_programs/chocolate_feast.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | using namespace std;
7 |
8 |
9 | int main() {
10 | int t,n,c,m,extra;
11 | cin>>t;
12 | while(t--){
13 | cin>>n>>c>>m;
14 | int answer=0;
15 | int mid;
16 | mid=n/c;
17 | answer=answer+mid;
18 |
19 | while(mid>=m)
20 | {
21 |
22 | answer=answer+(mid/m);
23 |
24 | extra=mid%m;
25 | mid=mid/m;
26 |
27 | mid=mid+extra;
28 |
29 | }
30 |
31 |
32 | cout<int(two[len1-1])):
13 | count = count + 1
14 | elif(int(one[len1-1])
2 | #include
3 | #include
4 | #include
5 |
6 | int main() {
7 | int n,c,d,i;
8 | char str[10000];
9 | char str1[10000]="";
10 | int size;
11 | scanf("%d",&size);
12 | while(size--){
13 | scanf("%s",str);
14 | n = strlen(str);
15 | // copy string
16 | for (c = n - 1, d = 0; c >= 0; c--, d++)
17 | str1[d] = str[c];
18 | str1[d] = '\0';
19 | int flag=1;
20 | for(i=1;i
2 | #include
3 | #include
4 | #include
5 | #include
6 | using namespace std;
7 |
8 |
9 | int main() {
10 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */
11 | int n,i,flag;
12 | long double dig1,dig2,fibn,sum;
13 | cin>>n;
14 | for(i=0;i>fibn;
20 | while(sum<=fibn){
21 | if(sum==fibn) {
22 | flag=1;
23 | }
24 | sum=dig1+dig2;
25 | dig1=dig2;
26 | dig2=sum;
27 | }
28 |
29 | if(flag==1) cout<<"IsFibo\n";
30 | else cout<<"IsNotFibo\n";
31 | }
32 |
33 |
34 | return 0;
35 | }
36 |
37 |
--------------------------------------------------------------------------------
/HackerRank/other_programs/kangaroo.py:
--------------------------------------------------------------------------------
1 | #!/bin/python
2 |
3 | import sys
4 |
5 |
6 | x1,v1,x2,v2 = raw_input().strip().split(' ')
7 | x1,v1,x2,v2 = [int(x1),int(v1),int(x2),int(v2)]
8 | #print x1,v1,x2,v2
9 | if(x10):
27 | totalluck = totalluck - int(implist[0])
28 | implist.pop(0)
29 | casecanfail = casecanfail-1
30 | for i in implist:
31 | totalluck = totalluck + int(i)
32 | print totalluck
33 |
34 |
--------------------------------------------------------------------------------
/HackerRank/other_programs/make_it_anagram.cpp:
--------------------------------------------------------------------------------
1 |
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | using namespace std;
8 |
9 |
10 | int main() {
11 | char s1[10010],s2[10010];
12 | cin>>s1>>s2;
13 | int a[26]={0};
14 | for(int i=0;ib[j]) sum+=a[j]-b[j];
39 | else sum+=b[j]-a[j];
40 | }
41 |
42 | }
43 |
44 | System.out.println(sum);
45 |
46 | }
47 |
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/HackerRank/other_programs/maximizing_xor.cpp:
--------------------------------------------------------------------------------
1 | #include