Skip to content

Commit e831e36

Browse files
authored
Merge pull request #15 from offamitkumar/11-add-problem-120
adds problem 120
2 parents 774061d + c323a6c commit e831e36

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

Diff for: README.md

+5
Original file line numberDiff line numberDiff line change
@@ -749,6 +749,11 @@ def __init__(self, val, left=None, right=None):
749749
#### Click [__*here*__](Solution/Day-119.cpp) for solution.
750750
#### Click [__*here*__](https://leetcode.com/problems/squares-of-a-sorted-array/) to visit [*LeetCode*](https://leetcode.com/) for this question.
751751
---
752+
## Problem 120
753+
##### This problem was asked by Microsoft.
754+
##### Implement the singleton pattern with a twist. First, instead of storing one instance, `store two instances`. And in every `even` call of `getInstance()`, return the `first instance` and in every `odd call` of getInstance(), return the `second instance`.
755+
#### Click [__*here*__](Solution/Day-120.cpp) for solution.
756+
---
752757
## Problem 122
753758
##### This question was asked by Zillow.
754759
##### You are given a 2-d matrix where each cell represents number of coins in that cell. Assuming we start at matrix[0][0], and can only move right or down, find the maximum number of coins you can collect by the bottom right corner.

Diff for: Solution/Day-120.cpp

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
//
2+
// Created by Amit Kumar on 12/07/23.
3+
//
4+
5+
#include "iostream"
6+
#include "string"
7+
8+
using namespace std;
9+
10+
enum State {
11+
NotInitialized, Odd, Even
12+
};
13+
14+
class ModifiedSingleton {
15+
16+
string instanceName;
17+
18+
ModifiedSingleton() = default;
19+
20+
explicit ModifiedSingleton(string name) : instanceName(std::move(name)) {}
21+
22+
public:
23+
ModifiedSingleton(ModifiedSingleton &ms) = delete;
24+
25+
static ModifiedSingleton &getInstance() {
26+
static ModifiedSingleton instanceOne;
27+
static ModifiedSingleton instanceTwo;
28+
29+
static State currentState = State::NotInitialized;
30+
31+
if (currentState == State::NotInitialized) {
32+
currentState = State::Odd;
33+
instanceOne = ModifiedSingleton("First Instance");
34+
instanceTwo = ModifiedSingleton("Second Instance");
35+
}
36+
37+
if (currentState == State::Odd) {
38+
currentState = State::Even;
39+
return instanceTwo;
40+
} else {
41+
currentState = State::Odd;
42+
return instanceOne;
43+
}
44+
}
45+
46+
friend ostream &operator<<(ostream &out, const ModifiedSingleton &ms) {
47+
out << ms.instanceName;
48+
return out;
49+
}
50+
51+
};
52+
53+
int main() {
54+
for (int i = 1; i < 10; ++i) {
55+
cout << ((i&1) ? "Odd Call: " : "Even Call: ");
56+
cout << ModifiedSingleton::getInstance() << endl;
57+
}
58+
return 0;
59+
}

0 commit comments

Comments
 (0)