question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
maximum-number-of-tasks-you-can-assign
C++ greedy + binary search
c-greedy-binary-search-by-robbinb1993-xzef
\nclass Solution {\npublic:\n bool pos(const int M, vector<int>& tasks, vector<int>& workers, int pills, int strength) { \n multiset<int> W;\n
robbinb1993
NORMAL
2022-02-20T12:51:15.510738+00:00
2022-02-20T12:51:15.510768+00:00
341
false
```\nclass Solution {\npublic:\n bool pos(const int M, vector<int>& tasks, vector<int>& workers, int pills, int strength) { \n multiset<int> W;\n for (int i = int(workers.size()) - 1; i >= int(workers.size()) - M; i--)\n W.insert(workers[i]);\n \n for (int i = M - 1; i >= 0; i--) {\n auto it = W.lower_bound(tasks[i]);\n if (it == W.end()) {\n if (pills == 0)\n return false;\n it = W.lower_bound(tasks[i] - strength);\n if (it == W.end())\n return false;\n pills--;\n }\n W.erase(it);\n }\n return true; \n }\n \n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n sort(tasks.begin(), tasks.end());\n sort(workers.begin(), workers.end());\n int L = 0;\n int R = min(int(tasks.size()), int(workers.size()));\n int ans;\n while (L <= R) {\n int M = (L + R) / 2;\n if (pos(M, tasks, workers, pills, strength)) {\n ans = M;\n L = M + 1; \n }\n else\n R = M - 1;\n }\n return ans;\n }\n};\n```
0
0
[]
0
maximum-number-of-tasks-you-can-assign
c++ solution using binary search
c-solution-using-binary-search-by-dilips-nmsb
\nclass Solution {\npublic:\n bool find(vector<int>&t,vector<int>&w,int mid,int pill,int s)\n {\n multiset<int>st(w.begin(),w.end());\n for(
dilipsuthar17
NORMAL
2022-01-28T15:23:00.390105+00:00
2022-01-28T15:23:00.390143+00:00
521
false
```\nclass Solution {\npublic:\n bool find(vector<int>&t,vector<int>&w,int mid,int pill,int s)\n {\n multiset<int>st(w.begin(),w.end());\n for(int i=mid-1;i>=0;i--)\n {\n auto it=st.lower_bound(t[i]);\n if(it==st.end())\n {\n it=st.lower_bound(t[i]-s);\n pill--;\n if(it==st.end()||pill<0)\n {\n return false;\n }\n }\n st.erase(it);\n }\n return true;\n }\n int maxTaskAssign(vector<int>& t, vector<int>& w, int pill,int s) \n {\n sort(t.begin(),t.end());\n sort(w.begin(),w.end());\n int n=t.size();\n int m=w.size();\n int l=0;\n int ans=l;\n int r=min(n,m);\n while(l<=r)\n {\n int mid=(l+r)/2;\n if(find(t,w,mid,pill,s))\n {\n ans=mid;\n l=mid+1;\n }\n else\n {\n r=mid-1;\n }\n }\n return ans;\n }\n};\n```
0
0
['C', 'Binary Tree', 'C++']
0
maximum-number-of-tasks-you-can-assign
C++ | Multiset | Binary Search
c-multiset-binary-search-by-tanishbothra-q279
\nclass Solution {\npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n \n sort(begin(tasks),end(tas
tanishbothra22
NORMAL
2021-12-27T16:04:42.770372+00:00
2021-12-27T16:07:55.273127+00:00
390
false
```\nclass Solution {\npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n \n sort(begin(tasks),end(tasks));\n sort(begin(workers),end(workers),greater<int>());\n \n \n int n=tasks.size();\n int m=workers.size();\n \n int low=0;\n int high=n;\n int ans=0;\n \n while(low<=high){\n int mid= low+(high-low)/2;\n int c=0;\n int j=0;\n int k=m-1;\n int p=pills;\n multiset<int,greater<int>>st(begin(workers),begin(workers)+min(mid,m));\n for(int i=mid-1;i>=0;i--){\n if(st.empty())break;\n auto it=st.begin();\n if(*it>=tasks[i]){\n c++;\n st.erase(it);\n }else{\n auto it =st.end();\n it--;\n bool flag=false;\n while(p>0){\n if(*it+strength>=tasks[i]){\n p--;\n flag=true;\n st.erase(it);\n c++;\n break;\n }else{\n if(it==st.begin())break;\n it--;\n }\n }\n \n if(!flag)break;\n }\n }\n\t\tif(c==mid){\n\t\t\tans=mid;\n\t\t\tlow=mid+1;\n\t\t}else{\n\t\t\thigh=mid-1;\n\t\t} \n \n}\n \nreturn ans;\n \n }\n \n};\n```
0
0
['C']
0
maximum-number-of-tasks-you-can-assign
Why does example 3 return '2' instead of '3'
why-does-example-3-return-2-instead-of-3-f4we
For the 3rd example in the problem description, why does the output expect 2 instead of 3? (0-indexed) Worker 1 can be assigned to task 0, worker 2 can be assig
springathing
NORMAL
2021-12-16T05:12:08.659775+00:00
2021-12-16T05:24:36.100191+00:00
102
false
For the 3rd example in the problem description, why does the output expect 2 instead of 3? (0-indexed) Worker 1 can be assigned to task 0, worker 2 can be assigned to task 1 with 1 pill boost, and worker 3 can be assigned to task 2 with 2 pill boosts.\n```\nInput: tasks = [10,15,30], workers = [0,10,10,10,10], pills = 3, strength = 10\nOutput: 2\n```\n\nHere is my wrong answer code that I believe should give me AC without using Binary Search\n```\npublic class Solution {\n public int MaxTaskAssign(int[] t, int[] w, int p, int s) {\n // Sort both arrays so strongest worker and hardest task are at array.len - 1 position\n Array.Sort(t);\n Array.Sort(w);\n \n int r = 0;\n \n // Find the 1st task that the last worker is able to handle, else iterate down to -1 in the tasks array\n int checkTask = t.Length - 1, checkWorker = w.Length - 1;\n while (checkTask >= 0) {\n if (w[checkWorker] >= t[checkTask]) { // found first task that can be handled without pills\n break;\n }\n checkTask--;\n }\n \n // handle all tasks by workers that don\'t require any pills\n int handleTask = checkTask, handleWorker = checkWorker;\n while (handleTask >= 0 && handleWorker >= 0 && w[handleWorker] >= t[handleTask]) {\n r++;\n handleTask--;\n handleWorker--;\n }\n \n // Starting from the first worker unable to handle any tasks without pills\n int startTask = 0, startWorker = handleWorker; \n while (startTask < t.Length && startWorker >= 0) { \n // Skip the tasks already handled by previous workers\n if (startTask > handleTask && startTask <= checkTask) {\n startTask++;\n continue;\n }\n\n // Apply magic pills until either the worker is strong enough to handle task, \n // or the number of available pills reaches 0\n if (w[startWorker] < t[startTask] && p > 0) { \n while (p > 0 && w[startWorker] < t[startTask]) { \n w[startWorker] += s;\n p--;\n } \n }\n \n // Check to see if the worker is capable of handling the task after any consumption of magic pills\n if (w[startWorker] >= t[startTask]) {\n startTask++;\n r++;\n } \n \n startWorker--;\n }\n \n return r;\n }\n}\n```
0
0
[]
1
maximum-number-of-tasks-you-can-assign
C# Solution
c-solution-by-springathing-o9b0
Binary Search\n\npublic class Solution {\n public int MaxTaskAssign(int[] t, int[] w, int p, int s) {\n Array.Sort(t);\n Array.Sort(w);\n
springathing
NORMAL
2021-12-16T05:08:25.355572+00:00
2021-12-16T05:08:25.355612+00:00
129
false
Binary Search\n```\npublic class Solution {\n public int MaxTaskAssign(int[] t, int[] w, int p, int s) {\n Array.Sort(t);\n Array.Sort(w);\n \n int l = 0, r = Math.Min(t.Length, w.Length);\n while (l + 1 < r) {\n int m = l + (r - l) / 2;\n if (CanAssign(t, w, p, s, m)) {\n l = m;\n } else {\n r = m;\n }\n }\n \n if (CanAssign(t, w, p, s, r)) return r;\n else return l;\n }\n \n public bool CanAssign(int[] t, int[] w, int p, int s, int cnt) {\n List<int> dq = new List<int>();\n int end = w.Length - 1;\n for (int i = cnt - 1; i >= 0; --i) {\n while (end >= w.Length - cnt && w[end] + s >= t[i]) {\n dq.Add(w[end]);\n end--;\n }\n \n if (dq.Count == 0) return false;\n \n if (dq[0] >= t[i]) {\n dq.RemoveAt(0);\n } else {\n dq.RemoveAt(dq.Count - 1);\n p--;\n if (p < 0) return false;\n }\n }\n \n return true;\n }\n}\n```
0
0
[]
0
maximum-number-of-tasks-you-can-assign
Python 3 solution
python-3-solution-by-dhananjay79-6hao
After watching striver\'s live coding, I understood the intution behind solving this problem.\nI am dumb :|\n\nclass Solution:\n def maxTaskAssign(self, T:
dhananjay79
NORMAL
2021-12-09T20:42:15.053039+00:00
2021-12-09T20:42:15.053082+00:00
220
false
After watching striver\'s live coding, I understood the intution behind solving this problem.\nI am dumb :|\n```\nclass Solution:\n def maxTaskAssign(self, T: List[int], W: List[int], pills: int, strength: int) -> int:\n \n \n def isPossible(T,W,pills,strength):\n\n harderTask, strongestMan = len(T) - 1, -1\n \n for _ in range(len(T)):\n if W[strongestMan] >= T[harderTask]:\n W.pop()\n else:\n if not pills: return False\n power_needed = T[harderTask] - strength\n index = bisect.bisect_left(W,power_needed)\n if index >= len(W): return False\n pills -= 1\n W.pop(index)\n harderTask -= 1\n \n return True\n \n \n \n T.sort()\n W.sort()\n \n l,h, = 0, min(len(T),len(W))\n \n while l <= h:\n mid = (l+h) // 2\n\n res = isPossible(T[:mid], W[len(W)-mid:], pills, strength) \n \n if res: l = mid + 1\n else: h = mid - 1\n \n return h\n \n```
0
0
[]
0
maximum-number-of-tasks-you-can-assign
Same multiset solution but a bit different approach gets WA
same-multiset-solution-but-a-bit-differe-cswf
My solution a bit different but do not know why it doesn\'t work. \n\n1) Start from hardest task. \n2) Find weakest worker that can do the task without pill\n3)
tahlil
NORMAL
2021-11-20T03:42:27.495453+00:00
2021-11-20T03:53:24.448332+00:00
239
false
My solution a bit different but do not know why it doesn\'t work. \n\n1) Start from hardest task. \n2) Find weakest worker that can do the task without pill\n3) If step 2 fails then find the weakest worker with pill can do it.\n4) If succeeds then remove the worker. Otherwise try the next task.\n\n```\nclass Solution {\npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) \n {\n sort(tasks.rbegin(),tasks.rend());//Sorting tasks hardest to easiest\n \n multiset<int>w(workers.begin(),workers.end());\n \n int ans = 0;\n for(int i=0);i<tasks.size() && w.size()>0;i++)\n {\n int task = tasks[i];\n int pillUsed = 0;\n \n auto pos = w.lower_bound(task); // Finding the weakest worker that can do it.\n if(pos == w.end() && pills)\n pos = w.lower_bound(task-strength),pillUsed=1; // Finding the weakest workder with pill that can do it.\n \n if(pos != w.end()) // Means found one worker that can do the task\n {\n ans++;\n w.erase(pos); // removing the worker\n pills-=pillUsed; // Decreasing pill count\n }\n \n }\n return ans;\n }\n};```\n \n WA on the following case which is too large to debug. \n [7908,9988,9571,5279,4047,9760,3274,7098,6367,4774,9975,5544,8811,2564,3835,6634,5648,9052,8143,5502,1285,7300,5630,7578,6522,2243,7284,6534,3766,1835,4153,4333,6338,6373,7517,6930,8190,2834,2218,2945,6929,4170,9254,9312,9789,1324,3851,4038,9497,6486,7949,5781,7787,5185,2726,8538,3698,6929,2613,6860,6981,7506,5294,6213,9848,4539,1234,8108,3832,5068,2712,6301,8340,7950,1320,9111,5411,8075,9752,6882,9679,9463,6580,9986,5114,4483,7816,1878,2204,4364,1603,3131,3492,8579,3026,2521,5679,8630,8667,3827,1555,3296,1118,4644,4866,1312,7632,9550,6914,9195,1009,2145,5184,4996,2913,6914,3584,4866,8505,7708,1309,2780,1794,6103,6161,9576,9885,1843,2180,9261,6516,7411,8606,4633,5653,8562,9533,8516,2503,3270,5264,1737,1603,1376,1834,6990,8234,8975,4194,2276,7633,3401,3521,6003,7685,2139,9061,2786,8637,7517,1411,3732,9200,9772,8017,4008,9189,4728,5141,8600,5512,4239,5236,6909,9942,4712,7017,9755,2365,3130,4668,9101,1414,7787,4533,7845,3755,2534,7896,4710,7581,2301,5079,4236,7276,8656,4777,1857]\n[4612,4669,4273,1929,1925,1342,4565,2152,1909,4897,2697,1419,1998,4789,2940,3388,4619,1427,1798,917,2270,1639,1633,4669,2674,2348,3714,3909,4359,3151,1639,4533,3444,3531,887,528,2346,1481,831,2345,3610,4507,2890,4740,3959,648,1468,3063,2416,4091,1151,2196,999,2708,578,978,4113,4229,2052,2154,2149,583,1029,2020,4498,4638,4932,2986,2749,1047,2434,971,1645,570,1395,3603,4581,3607,3158,2758,1046,1171,2204,1421,3708,4769,3399,981,3396,4837,3633,4067,4141,2037,1622,2257,1529,1371,4090,3273,4767,3543,1098,503,3905,4427,3875,2594,4878,2252,912,4838,509,2989,3304,4268,1520,4027,3691,993,600,3529,3762,1854,592,1579,2191,3051,1897,4050,1345,3416,1108,4862,4587,3065,3486,2138,1272,4237,4235,4107,1951,3747,2774,4944,3815,2560,3688,1838,2821,3098,1361,1439,2486,4599,2215,1908,2432,1862,1780,1143,4117,3175,3839,3019,4576,4343,4186,1643,3472,1637,693,4128,4709,4500,2639,4022,2886,1708,2721,4686,4870,772,557,1845,2788,821,3752]\n35\n2208\nOutput:\n113\nExpected:\n118\n
0
0
[]
1
maximum-number-of-tasks-you-can-assign
[Golang] Can somebody help me to point out why my solution fails at test cases 33?
golang-can-somebody-help-me-to-point-out-yebz
My logic: Do binary search to choose the potential answer k. \n\n1) choose the smallest k tasks and strongest k workers. try to assign it without pill first (fi
shentianjie466357304
NORMAL
2021-11-20T03:42:00.055901+00:00
2021-11-20T03:45:35.829179+00:00
103
false
My logic: Do binary search to choose the potential answer k. \n\n1) choose the smallest k tasks and strongest k workers. try to assign it without pill first (find the weakest worker possible greedy strategy)\n2) If not try to find the weakest worker with a pill \n3) Otherwise it is impossible to assign k tasks, return false. \n\n\nIt fails at test cases 33: \n```\n[1943,2068,4077,7832,8061,6939,6263,8917,8008,5348,8837,4753,4607,7638,9000,7222,4552,1123,9225,6896,4154,6303,3186,2325,9994,5855,8851,7377,1930,1187,5094,2689,8852,1507,1567,9575,1193,1557,8840,9075,5032,3642,6917,7968,5310,2315,7516,4776,3091,7027,1788,2007,2651,6112,4264,5644,3585,9408,7410,9605,8151,1538,6905,6759,4518,3444,5036,1589,3902,3037,1468,9179,3000,5339,6805,7394,9418,9262,2888,4708,3402,5554,8714,7393,2848,5946,9808,4301,6675,8564,6300,4359,9506,1946,9673,7412,1164,2986,2198,5144,3763,4782,8835,6994,8035,3332,2342,5243,3150,9084,6519,9798,7682,9919,7473,7686,9978,8092,9897,3985,9874,5842,9740,2145,2426,7069,8963,9250,4142,9434,1895,6559,3233,8431,6278,6748,7305,4359,2144,8009,4890,6486,7464,8645,1704,5915,9586,1394,7504,2124,3150,2051,5026,7612,3715,5757,4355,6394,3202,2777,3949,2349,7398,3029,3081,5116,5078,8048,9934,4348,8518,5201,1203,7935,5006,6388,8680,3427,6048,1957,4026,4618,4080]\n[875,2347,939,3664,3926,4555,1947,4406,4601,3502,4964,1307,4232,2968,4572,3139,2788,1847,1208,2019,4184,1664,1747,3690,4333,891,686,1959,2218,4972,806,741,1490,4529,2909,925,2040,1234,1264,1135,3640,1455,2933,3699,2856,3074,4579,2458,2090,833,4140,4534,2336,4363,1948,4546,4155,3735,3577,2780,4874,1747,4844,3482,3053,3534,549,4500,2237,2128,1554,3210,4161,2211,950,3732,2182,1148,4368,4050,1452,1015,3192,4318,3908,2590,1103,2811,2821,690,2718,3360,2659,3315,579,3108,2979,3903,4367,1906,4964,889,4803,825,2270,4794,4825,4485,4461,1639,3857,1330,3169,2425,3694,1980,2268,3002,2177,3225,2499,2517,1916,2844,760,2167,1786,3179,3222,1432,3775,4747,1764,690,3223,4684,890,2701,1045,3034,1381,1011,2150,4798,2247,1334,3058,934,2895,1484,2784,3341,4412,1748,625,2610,3488,4810,669,4275,4929,1014,2104,3111]\n122\n3131\n```\n\nExpected Output 143 and my output 145\n\n\n\tfunc maxTaskAssign(tasks []int, workers []int, pills int, strength int) int {\n\t\tsort.Ints(tasks)\n\t\tsort.Ints(workers)\n\n\t\th := int(math.Min(float64(len(tasks)), float64(len(workers))))\n\t\tl := 0\n\t\tans := 0\n\t\tfor l <= h {\n\t\t\tm := l + (h - l) / 2\n\t\t\tif canDo(tasks[0:m], workers[len(workers)-m:], pills, strength) {\n\t\t\t\tans = m\n\t\t\t\tl = m + 1\n\t\t\t} else {\n\t\t\t\th = m - 1\n\t\t\t}\n\t\t}\n\t\treturn ans\n\t}\n\n\tfunc canDo(tasks, workers []int, pills, strength int) bool {\n\t\tfor j := len(tasks) - 1; j >= 0; j-- {\n\t\t\t// biggest task\n\t\t\ttask := tasks[j]\n\t\t\tidx := findPlace(workers, task)\n\t\t\tflag := false\n\t\t\tif idx >= 0 {\n\t\t\t\tworkers = append(workers[0:idx], workers[idx+1:]...)\n\t\t\t\tflag = true\n\t\t\t} else if idx = findPlace(workers, task - strength); idx >= 0 && pills > 0 {\n\t\t\t\tpills--\n\t\t\t\tworkers = append(workers[0:idx], workers[idx+1:]...)\n\t\t\t\tflag = true\n\t\t\t}\n\n\t\t\tif !flag {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn len(workers) == 0\n\t}\n\n\tfunc findPlace(workers []int, task int) int {\n\t\t// find the leftmost worker that can accomplish the task\n\t\tl := 0\n\t\tr := len(workers) - 1\n\t\tans := -1\n\t\tfor l <= r {\n\t\t\tm := l + (r - l) / 2\n\t\t\tif workers[m] >= task {\n\t\t\t\tans = m\n\t\t\t\tr = m - 1\n\t\t\t} else {\n\t\t\t\tl = m + 1\n\t\t\t}\n\t\t}\n\t\treturn ans\n\t}
0
0
[]
0
maximum-number-of-tasks-you-can-assign
Scala, use a TreeMap for greedy algorithm when validating on the binary search
scala-use-a-treemap-for-greedy-algorithm-1pdv
scala\n\n def maxTaskAssign(tasks: Array[Int], workers: Array[Int], pills: Int, strength: Int): Int = {\n type int = Int\n var res = 0\n tasks.sortInP
qiuqiushasha
NORMAL
2021-11-18T19:10:35.769002+00:00
2021-11-18T19:10:35.769029+00:00
65
false
```scala\n\n def maxTaskAssign(tasks: Array[Int], workers: Array[Int], pills: Int, strength: Int): Int = {\n type int = Int\n var res = 0\n tasks.sortInPlaceWith((a, b) => a <= b)\n workers.sortInPlaceWith((a, b) => a <= b)\n\n import scala.collection.mutable.TreeMap\n\n val tl = tasks.length\n val wl = workers.length\n\n def f(target: int): Boolean = {\n\n var taken = 0\n var j = wl - 1\n val tm = new TreeMap[int, int]()((a, b) => Integer.compare(a, b))\n\n (target - 1 to 0 by -1).foreach(i => {\n\n val ct = tasks(i)\n while (j >= 0 && workers(j) >= ct) {\n tm.put(workers(j), tm.getOrElse(workers(j), 0) + 1)\n j -= 1\n }\n val weakest = tm.minAfter(ct)\n if (weakest.isDefined) {\n val key = weakest.get._1\n tm.put(key, tm(key) - 1)\n if (tm(key) == 0) tm -= key\n } else {\n if (taken < pills) {\n while (j >= 0 && workers(j) + strength >= ct) {\n tm.put(workers(j), tm.getOrElse(workers(j), 0) + 1)\n j -= 1\n }\n val weakestPill = tm.minAfter(ct - strength)\n if (weakestPill.isDefined) {\n val key = weakestPill.get._1\n tm.put(key, tm(key) - 1)\n if (tm(key) == 0) tm -= key\n taken += 1\n\n } else {\n return false\n }\n\n } else {\n return false\n }\n\n }\n\n })\n\n true\n }\n\n var s = 0\n var e = Math.min(tl, wl)\n while (s <= e) {\n var mid = s + (e - s) / 2\n if (f(mid)) {\n res = Math.max(res, mid)\n s = mid + 1\n } else {\n e = mid - 1\n }\n\n }\n\n res\n\n }\n```
0
0
[]
0
maximum-number-of-tasks-you-can-assign
Rust binary search + BTreeMap
rust-binary-search-btreemap-by-robetking-6cnd
Would be nice to have a multiset in rust but can use BTreeMap with counts.\n\nIdea to check if it\'s possible in a binary search iteration: take the K smallest
robetkingnz
NORMAL
2021-11-14T16:36:39.463116+00:00
2021-11-14T16:39:13.856870+00:00
315
false
Would be nice to have a multiset in rust but can use BTreeMap with counts.\n\nIdea to check if it\'s possible in a binary search iteration: take the K smallest tasks and the K strongest workers. Go through the workers left to right assigning the weakest worker to the easiest task. If the worker can\'t do the easiest task, give the worker a pill and take the hardest task the worker can do. If we ever get a worker that can\'t take a task (out of pills or pills not strong enough), it\'s not possible.\n\n```\n// @robertkingnz\nfn possible(tasks: &[i32], workers: &[i32], mut pills: i32, strength: i32) -> bool {\n let mut m: BTreeMap<i32, i32> = BTreeMap::new();\n for &t in tasks {\n let e = m.entry(t).or_insert(0);\n *e += 1;\n }\n for &w in workers {\n let (&first, &first_count) = m.iter().next().unwrap();\n if w >= first {\n if first_count == 1 {\n m.remove(&first);\n } else {\n m.insert(first, first_count - 1);\n }\n } else if pills == 0 {\n return false;\n } else if let Some((&x, &x_count)) = m.range(..=(w+strength)).next_back() {\n pills -= 1;\n if x_count == 1 {\n m.remove(&x);\n } else {\n m.insert(x, x_count - 1);\n }\n } else {\n return false;\n }\n }\n true\n}\n\nimpl Solution {\n pub fn max_task_assign(mut tasks: Vec<i32>, mut workers: Vec<i32>, pills: i32, strength: i32) -> i32 {\n tasks.sort();\n workers.sort();\n let n = tasks.len().min(workers.len());\n tasks.drain(n..tasks.len());\n workers.drain(..(workers.len()-n));\n let mut a = 0;\n let mut b = n+1;\n while a < b {\n let i = a + (b-a)/2;\n let ok = possible(\n &tasks[..i],\n &workers[n-i..],\n pills,\n strength);\n if ok {\n a = i+1;\n } else {\n b = i;\n }\n }\n if a > 0 {\n return (a-1) as i32;\n }\n 0\n }\n}\n```
0
0
[]
0
maximum-number-of-tasks-you-can-assign
Easy C++ Solution| Binary Search | MultiSet
easy-c-solution-binary-search-multiset-b-uldz
{Based on solution by @astroash}\nWe first do binary search on the solution space, i.e, 0 to minimum of tasks.size or workers.size().\n\nThe condition we check
harit_1
NORMAL
2021-11-14T08:18:19.162272+00:00
2021-11-14T08:19:48.434542+00:00
217
false
*{Based on solution by @astroash}*\nWe first do binary search on the solution space, i.e, 0 to minimum of tasks.size or workers.size().\n\nThe condition we check in iteration is it possible to assign the first k smallest tasks to the workers?\n\nFor each task, there can be three cases:\n- A worker without the pill can complete it.\n- A worker with the pill can complete it.\n- No available worker, with or without the pill can complete it.\n\nThis is further explained as comments in the code.\n\nPlease upvote. :)\n\n\n\n```\nclass Solution {\n \n bool possible(vector<int>& tasks, vector<int>& workers, int t, int strength, int mid){\n multiset<int> myset(workers.begin(), workers.end());\n multiset<int>::iterator it;\n \n for(int i=mid-1;i>=0;i--){\n it = myset.end();\n it--;\n if(*it>=tasks[i]){ // we check if a worker without the pill can complete it. Here, we should check for the strongest worker for this task.\n myset.erase(it);\n }\n else { // If worker without the pill can\'t complete it, we check for the weakest worker if he/she can complete the task with the help of pill. I also track the number of pills available and reduce the count if used.\n it = myset.lower_bound(tasks[i]-strength);\n if(t>0 && it!=myset.end()){\n t--;\n myset.erase(it);\n }\n else{ // If above two conditions aren\'t fulfilled, then these mid samllest no. of tasks can\'t be assigned.\n return false;\n } \n }\n }\n \n return true;\n }\n \npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& workers, int pills, int strength) {\n int n = tasks.size();\n int m = workers.size();\n sort(tasks.begin(), tasks.end());\n sort(workers.begin(), workers.end());\n \n int l=0, r=min(n,m);\n int ans=0;\n while(l<=r){\n int mid = l+(r-l)/2;\n if(possible(tasks, workers, pills, strength, mid)){\n ans=mid;\n l=mid+1;\n }\n else{\n r=mid-1;\n }\n }\n \n return ans;\n }\n};\n```
0
0
['Binary Search', 'C']
0
maximum-number-of-tasks-you-can-assign
c++ nlg^2n
c-nlg2n-by-colinyoyo26-39cs
\nclass Solution {\npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& ws, int ps, int st) {\n sort(tasks.begin(), tasks.end());\n so
colinyoyo26
NORMAL
2021-11-14T01:10:48.240610+00:00
2021-11-14T01:10:48.240659+00:00
157
false
```\nclass Solution {\npublic:\n int maxTaskAssign(vector<int>& tasks, vector<int>& ws, int ps, int st) {\n sort(tasks.begin(), tasks.end());\n sort(ws.begin(), ws.end(), greater<int>());\n int m = tasks.size(), n = ws.size();\n auto isvalid = [&] (int k) {\n if (k > min(m, n)) return false;\n int p = ps;\n multiset<int> ms(ws.begin(), ws.begin() + k);\n for (int j = k - 1; j >= 0; j--) {\n auto it = prev(ms.end());\n if (*it < tasks[j]) {\n it = ms.lower_bound(tasks[j] - st);\n if (it == ms.end() || !p--) return false;\n }\n ms.erase(it);\n }\n return true;\n };\n int l = 1 << 20, ans = 0;\n for (; l; l >>= 1)\n if (isvalid(l | ans)) ans |= l;\n return ans;\n }\n};\n```
0
1
[]
0
fizz-buzz-multithreaded
Java, using synchronized with short explanation.
java-using-synchronized-with-short-expla-dyp1
[Code is at the end]\n\nSo I just keep a shared currentNumber showing where we\'re up to. Each thread has to then check whether or not it should take its turn.
hai_dee
NORMAL
2019-09-19T04:08:01.108833+00:00
2019-09-19T04:08:01.108871+00:00
19,022
false
[Code is at the end]\n\nSo I just keep a shared ```currentNumber``` showing where we\'re up to. Each thread has to then check whether or not it should take its turn. If it\'s not the current thread\'s turn, it calls ```wait()```, thus suspending and giving up the monitor. After each increment of ```currentNumber```, we need to call ```notifyAll()``` so that the other threads are woken and can re-check the condition. They will all be given a chance to run \n\nThe implicit locks, (aka monitors) provided by synchronized can be a bit confusing at first to understand, so I recommend reading up on them if you are confused. I personally found these sites useful:\n+ https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html\n+ https://howtodoinjava.com/java/multi-threading/java-synchronized/\n\nYou might notice something slightly unusual in my wait code, i.e.\n\n```\nif (currentNumber % 3 != 0 || currentNumber % 5 == 0) {\n wait();\n continue;\n}\n```\n\nWhen perhaps you would have expected the more traditional form of:\n```\nwhile (currentNumber % 3 != 0 || currentNumber % 5 == 0) {\n wait();\n}\n```\n\nSeeing as we are always told that waiting conditions must be a loop, right? (Because sometimes it will have to wait more than once for its turn). The reason I have done this though is because otherwise there\'d have to be an additional check in the waiting loop for if the currentNumber value is still below n.\n```\nwhile (currentNumber % 3 != 0 || currentNumber % 5 == 0) {\n wait();\n\t if (currentNumber > n) return;\n}\n```\n\nWhile this does work, I felt it was probably the more convoluted option. But it\'s definitely an option, and I\'d be interested to hear thoughts on this "design" decision. In effect, it is a wait in a loop, it\'s just that it utilises the outer loop\'s condition (by using continue).\n\nI probably could pull some of the repetition into a seperate method. One challenge was that 3 of the methods took a Runnable, and one took an IntConsumer.\n\n```\nclass FizzBuzz {\n \n private int n;\n private int currentNumber = 1;\n \n public FizzBuzz(int n) {\n this.n = n;\n }\n\n // printFizz.run() outputs "fizz".\n public synchronized void fizz(Runnable printFizz) throws InterruptedException {\n while (currentNumber <= n) {\n if (currentNumber % 3 != 0 || currentNumber % 5 == 0) {\n wait();\n continue;\n }\n printFizz.run();\n currentNumber += 1;\n notifyAll();\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public synchronized void buzz(Runnable printBuzz) throws InterruptedException {\n while (currentNumber <= n) {\n if (currentNumber % 5 != 0 || currentNumber % 3 == 0) {\n wait();\n continue;\n }\n printBuzz.run();\n currentNumber += 1;\n notifyAll();\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public synchronized void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n while (currentNumber <= n) {\n if (currentNumber % 15 != 0) {\n wait();\n continue;\n }\n printFizzBuzz.run();\n currentNumber += 1;\n notifyAll();\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public synchronized void number(IntConsumer printNumber) throws InterruptedException {\n while (currentNumber <= n) {\n if (currentNumber % 3 == 0 || currentNumber % 5 == 0) {\n wait();\n continue;\n }\n printNumber.accept(currentNumber);\n currentNumber += 1;\n notifyAll();\n }\n }\n```
126
2
[]
12
fizz-buzz-multithreaded
python, >99.28%, a standard Lock() based solution, with detailed explanation
python-9928-a-standard-lock-based-soluti-0ph0
\nimport threading\n\nclass FizzBuzz:\n def __init__(self, n: int): \n self.n = n\n self.f = threading.Lock()\n self.b = threading.
rmoskalenko
NORMAL
2020-03-18T01:27:11.901818+00:00
2020-08-28T03:40:10.206829+00:00
8,136
false
```\nimport threading\n\nclass FizzBuzz:\n def __init__(self, n: int): \n self.n = n\n self.f = threading.Lock()\n self.b = threading.Lock()\n self.fb = threading.Lock()\n self.f.acquire()\n self.b.acquire()\n self.fb.acquire()\n self.main = threading.Lock()\n\n # printFizz() outputs "fizz"\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n while True:\n self.f.acquire()\n if self.n == 0 :\n return\n printFizz()\n self.main.release()\n\n # printBuzz() outputs "buzz"\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n while True:\n self.b.acquire()\n if self.n == 0:\n return\n printBuzz()\n self.main.release()\n\n # printFizzBuzz() outputs "fizzbuzz"\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n while True:\n self.fb.acquire()\n if self.n == 0:\n return\n printFizzBuzz()\n self.main.release()\n\n # printNumber(x) outputs "x", where x is an integer.\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n for i in range(1, self.n+1):\n #print("number:",i)\n self.main.acquire()\n if i % 15 == 0:\n self.fb.release()\n elif i % 3 == 0:\n self.f.release()\n elif i % 5 == 0:\n self.b.release()\n else:\n printNumber(i)\n self.main.release()\n\n self.main.acquire() \n self.n = 0\n self.f.release()\n self.b.release()\n self.fb.release()\n return\n\n```\n\nSome background first. Python gives us a tool called Lock(). It\'s basically a flag and it can be either acquired or released. So an acquire() call will wait until Lock is released. Originally locks are created as released. So all we need here is Lock() to create a lock and two methods: acquire() and release().\n\nThis is very similar to Semaphore(), but semaphores are deprecated and going to be removed, so let\'s stick with Locks.\n\nOk, now we are familiar with the special tools, let\'s think about the app logic.\n\nWe have 4 threads. 3 of them (Fizz, Buzz and FizzBuzz) are more specialized and they print only very specific numbers, the fourth one (number) is used more frequently, so we can use it as an orchestrator or "main" thread.\n\nSo on a high level, the number thread is going to acquier its own lock, then it will check the current number, if it\'s %15, %3 or %5 - it\'s going to release a corresponding lock, otherwise it\'s going to print the number itself and release its own lock.\n\nThe other 3 threads will be spinning in loops waiting for their lock to be acquired, then they print the current number (during that time the number thread is locked), then they release the main lock.\n\nOkey, good, we\'ve got the main framework figured out, now we need to add the details.\n\nFirst of all, when the class is initialized, we want only the main thread to be released, the other three threads should stay locked. We are going to do it by:\n```\n self.f.acquire()\n self.b.acquire()\n self.fb.acquire()\n```\n\nAt this point we can get our program started. Now we need to think how to stop it nicely.\n\nThe number thread has a `for` loop, so it will spin exactly as many cycles as needed and it will finish. But how can we terminate the other 3?\n\nThere could be a few ways.\n\n1. Use some global variable to tell all threads to stop or continue. For example, we can set self.n to 0 once we are done and in all three threads check if `self.n != 0`. Another way would be to use a dedicated flag ( in this example it is `self.done`).\n2. Let every thread count how many cycles it needs to execute. Basically instead of having `while True ... if flag is set then break` we can say `for c in range(self.n // 15)` . An example of such code is below:\n\n```\nimport threading\n\nclass FizzBuzz:\n def __init__(self, n):\n self.n = n\n self.f = threading.Lock()\n self.b = threading.Lock()\n self.fb = threading.Lock()\n self.main = threading.Lock() \n self.f.acquire()\n self.b.acquire()\n self.fb.acquire()\n\n # printFizz() outputs "fizz"\n def fizz(self, printFizz):\n for i in range (self.n // 3 - self.n // 15):\n self.f.acquire()\n printFizz()\n self.main.release()\n \n # printBuzz() outputs "buzz"\n def buzz(self, printBuzz):\n for i in range (self.n // 5 - self.n // 15):\n self.b.acquire()\n printBuzz()\n self.main.release()\n\n # printFizzBuzz() outputs "fizzbuzz"\n def fizzbuzz(self, printFizzBuzz):\n for i in range (self.n // 15):\n self.fb.acquire()\n printFizzBuzz()\n self.main.release() \n\n # printNumber(x) outputs "x", where x is an integer.\n def number(self, printNumber):\n for i in range(1, self.n + 1): \n self.main.acquire() \n if i % 15 == 0:\n self.fb.release()\n elif i % 3 == 0:\n self.f.release()\n elif i % 5 == 0:\n self.b.release()\n else:\n printNumber(i)\n self.main.release() \n```\n\nSo what is the difference between 2 approaches?\n\nPerformance wise, they are very comparable, both showing results in high 90% range. \nThe second approach produces a noticably shorter code. \n\nBut there is a more philosophical difference.\n\nThe global flag approach keeps one thread as a master where all logic is implemented while the other three threads are dumb workers. They repeat exactly same step until they are told to stop. The other approach has logic spread between all 4 threads. So while workers are becoming more sophisticated, they are also more independent and they require fewer communication channels.\n\nGenerally speaking, on a very large scale the second approach has advantages. Every communication between the threads can become a bottleneck, so the more independent threads the better (just imagine that you\'re running it on some super broad cluster. Syncing the state of every shared resource comes with a price, so Lock vs Lock+GlobaFlag can make a difference).\n\nBut on a small scale, keeping most of the logic in one place has some advantages too. \n
70
1
[]
10
fizz-buzz-multithreaded
Java implementation using Semaphore as token 4ms
java-implementation-using-semaphore-as-t-t6xs
\n\nclass FizzBuzz {\n private int n;\n\tprivate Semaphore fizz = new Semaphore(0);\n\tprivate Semaphore buzz = new Semaphore(0);\n\tprivate Semaphore fizzbu
franklee9527
NORMAL
2019-10-08T06:45:44.867795+00:00
2019-10-08T06:45:44.867831+00:00
6,127
false
\n```\nclass FizzBuzz {\n private int n;\n\tprivate Semaphore fizz = new Semaphore(0);\n\tprivate Semaphore buzz = new Semaphore(0);\n\tprivate Semaphore fizzbuzz = new Semaphore(0);\n\tprivate Semaphore num = new Semaphore(1);\n\n\tpublic FizzBuzz(int n) {\n this.n = n;\n }\n\n\t// printFizz.run() outputs "fizz".\n\tpublic void fizz(Runnable printFizz) throws InterruptedException {\n\t\tfor (int k = 1; k <= n; k++) {\n\t\t\tif (k % 3 == 0 && k % 5 != 0) {\n\t\t\t\tfizz.acquire();\n\t\t\t\tprintFizz.run();\n\t\t\t\treleaseLock(k + 1);\n\t\t\t}\n\t\t}\n\t}\n\n\t// printBuzz.run() outputs "buzz".\n\tpublic void buzz(Runnable printBuzz) throws InterruptedException {\n\t\tfor (int k = 1; k <= n; k++) {\n\t\t\tif (k % 5 == 0 && k % 3 != 0) {\n\t\t\t\tbuzz.acquire();\n\t\t\t\tprintBuzz.run();\n\t\t\t\treleaseLock(k + 1);\n\t\t\t}\n\t\t}\n\t}\n\n\t// printFizzBuzz.run() outputs "fizzbuzz".\n\tpublic void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n\t\tfor (int k = 1; k <= n; k++) {\n\t\t\tif (k % 15 == 0) {\n\t\t\t\tfizzbuzz.acquire();\n\t\t\t\tprintFizzBuzz.run();\n\t\t\t\treleaseLock(k + 1);\n\t\t\t}\n\t\t}\n\t}\n\n\t// printNumber.accept(x) outputs "x", where x is an integer.\n\tpublic void number(IntConsumer printNumber) throws InterruptedException {\n\t\tfor (int k = 1; k <= n; k++) {\n\t\t\tif (k % 3 != 0 && k % 5 != 0) {\n\t\t\t\tnum.acquire();\n\t\t\t\tprintNumber.accept(k);\n\t\t\t\treleaseLock(k + 1);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void releaseLock(int n) {\n\t\tif (n % 3 == 0 && n % 5 != 0) {\n\t\t\tfizz.release();\n\t\t} else if (n % 5 == 0 && n % 3 != 0) {\n\t\t\tbuzz.release();\n\t\t} else if (n % 15 == 0) {\n\t\t\tfizzbuzz.release();\n\t\t} else {\n\t\t\tnum.release();\n\t\t}\n\t}\n}\n```
69
0
[]
10
fizz-buzz-multithreaded
C++ mutex / condition_variable, please suggest improvements
c-mutex-condition_variable-please-sugges-w5p0
```\nprivate:\n int n;\n int count;\n mutex m;\n condition_variable cv;\n\npublic:\n FizzBuzz(int n) {\n this->n = n;\n this->count
grokus
NORMAL
2019-09-22T16:10:36.308025+00:00
2019-09-22T16:10:36.308063+00:00
8,977
false
```\nprivate:\n int n;\n int count;\n mutex m;\n condition_variable cv;\n\npublic:\n FizzBuzz(int n) {\n this->n = n;\n this->count = 1;\n }\n\n void fizz(function<void()> printFizz) {\n while (true) {\n unique_lock<mutex> lock(m);\n while (count <= n && (count % 3 != 0 || count % 5 == 0))\n cv.wait(lock);\n if (count > n) return;\n printFizz();\n ++count;\n cv.notify_all();\n }\n }\n\n void buzz(function<void()> printBuzz) {\n while (true) {\n unique_lock<mutex> lock(m);\n while (count <= n && (count % 5 != 0 || count % 3 == 0))\n cv.wait(lock);\n if (count > n) return;\n printBuzz();\n ++count;\n cv.notify_all();\n }\n }\n\n\tvoid fizzbuzz(function<void()> printFizzBuzz) {\n while (true) {\n unique_lock<mutex> lock(m);\n while (count <= n && (count % 5 != 0 || count % 3 != 0))\n cv.wait(lock);\n if (count > n) return;\n printFizzBuzz();\n ++count;\n cv.notify_all();\n }\n }\n\n void number(function<void(int)> printNumber) {\n while (true) {\n unique_lock<mutex> lock(m);\n while (count <= n && (count % 5 == 0 || count % 3 == 0))\n cv.wait(lock);\n if (count > n) return;\n printNumber(count++);\n cv.notify_all();\n }\n }
48
1
[]
15
fizz-buzz-multithreaded
Python 3 non-cheesy solution with semaphores
python-3-non-cheesy-solution-with-semaph-p138
My solution is similar to other Semaphore solutions, but it doesn\'t need math formulas to calculate how many times we should print fizz or buzz.\nI feel that i
ilgor
NORMAL
2020-01-08T02:32:03.195872+00:00
2020-01-08T02:32:03.195921+00:00
6,126
false
My solution is similar to other Semaphore solutions, but it doesn\'t need math formulas to calculate how many times we should print fizz or buzz.\nI feel that it\'s a code smell and not true to the spirit of multi-threading.\nInstead I used **done** flag which is set by controlling thread and allows slave threads to peacefully finish on time without some extra inherent knowledge about the task.\n\nHope you\'ll like it.\n\n```\n# IDEA: use four semaphores with only number one starting unlocked, number-thread will loop numbers and distribute work\n# to other threads with releases, number-thread will set done flag when its loop finishes and other threads will break on this flag\n#\nclass FizzBuzz:\n def __init__(self, n: int):\n self.done = False \n self.n = n\n self.fSem = threading.Semaphore(0)\n self.bSem = threading.Semaphore(0)\n self.fbSem = threading.Semaphore(0)\n self.nSem = threading.Semaphore(1)\n\n # printFizz() outputs "fizz"\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n while True:\n self.fSem.acquire()\n if self.done: break\n printFizz()\n self.nSem.release()\n\n # printBuzz() outputs "buzz"\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n while True:\n self.bSem.acquire()\n if self.done: break\n printBuzz()\n self.nSem.release()\n\n # printFizzBuzz() outputs "fizzbuzz"\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n while True:\n self.fbSem.acquire()\n if self.done: break\n printFizzBuzz()\n self.nSem.release()\n\n # printNumber(x) outputs "x", where x is an integer.\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n for i in range(1, self.n+1):\n self.nSem.acquire()\n if i % 15 == 0:\n self.fbSem.release()\n elif i % 3 == 0:\n self.fSem.release()\n elif i % 5 == 0:\n self.bSem.release()\n else:\n printNumber(i)\n self.nSem.release()\n self.nSem.acquire() # needed so this thread waits to set done flag only when other threads are done with printing\n self.done = True\n self.fSem.release() # let all other threads to break and finish\n self.bSem.release() #\n self.fbSem.release() #\n```
37
0
['Python', 'Python3']
7
fizz-buzz-multithreaded
C++ condition_variable waiting on predicate
c-condition_variable-waiting-on-predicat-sm1t
\nclass\xA0FizzBuzz\xA0{\n\xA0\xA0\xA0\xA0private:\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0int\xA0n;\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0atomic<int>\xA0current;\n\xA0\xA0
igorb
NORMAL
2020-01-20T00:09:24.602439+00:00
2020-01-20T00:09:24.602494+00:00
3,139
false
```\nclass\xA0FizzBuzz\xA0{\n\xA0\xA0\xA0\xA0private:\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0int\xA0n;\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0atomic<int>\xA0current;\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0mutex\xA0mx;\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0condition_variable\xA0cv;\n\xA0\xA0\xA0\xA0public:\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0FizzBuzz(int\xA0n)\xA0{\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0this->n\xA0=\xA0n;\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0current\xA0=\xA01;\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0}\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0//\xA0printFizz()\xA0outputs\xA0"fizz".\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0void\xA0fizz(function<void()>\xA0printFizz)\xA0\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0{\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0do_work([&](int\xA0i){printFizz();},\xA0[&]{return\xA0(current\xA0%\xA03\xA0==\xA00\xA0&&\xA0current\xA0%\xA05\xA0!=\xA00);});\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0}\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0//\xA0printBuzz()\xA0outputs\xA0"buzz".\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0void\xA0buzz(function<void()>\xA0printBuzz)\xA0\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0{\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0do_work([&](int\xA0i){printBuzz();},\xA0[&]{return\xA0(current\xA0%\xA05\xA0==\xA00\xA0&&\xA0current\xA0%\xA03\xA0!=\xA00);});\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0}\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0//\xA0printFizzBuzz()\xA0outputs\xA0"fizzbuzz".\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0void\xA0fizzbuzz(function<void()>\xA0printFizzBuzz)\xA0\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0{\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0do_work([&](int\xA0i){printFizzBuzz();},\xA0[&]{return\xA0(current\xA0%\xA05\xA0==\xA00\xA0&&\xA0current\xA0%\xA03\xA0==\xA00);});\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0}\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0//\xA0printNumber(x)\xA0outputs\xA0"x",\xA0where\xA0x\xA0is\xA0an\xA0integer.\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0void\xA0number(function<void(int)>\xA0printNumber)\xA0\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0{\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0do_work(printNumber,\xA0[&]{return\xA0(current\xA0%\xA05\xA0!=\xA00\xA0&&\xA0current\xA0%\xA03\xA0!=\xA00);});\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0}\n\xA0\xA0\xA0\xA0protected:\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0void\xA0do_work(function<void(int)>\xA0printFunc,\xA0function<bool()>\xA0evalFunc)\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0{\xA0\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0while(current\xA0<=\xA0n)\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0{\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0unique_lock<mutex>\xA0ul(mx);\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0cv.wait(ul,\xA0[&]{return\xA0(evalFunc()\xA0||\xA0current\xA0>\xA0n);});\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0if(current\xA0>\xA0n)\xA0break;\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0printFunc(current);\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0++current;\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0cv.notify_all();\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0}\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0}\n};\n\n```\n
19
0
['C']
4
fizz-buzz-multithreaded
Java Solutions with Explanation (Approach 1 - object lock, Approach 2- Semaphore)
java-solutions-with-explanation-approach-c9sk
Intuition\nFour separate threads is supposed to operate on thie FizzBuzz class. We need to guard the block of code that has the logic to decide if the number is
mitesh_pv
NORMAL
2023-01-22T04:15:06.173971+00:00
2023-01-22T11:47:44.685466+00:00
3,933
false
# Intuition\nFour separate threads is supposed to operate on thie FizzBuzz class. We need to guard the block of code that has the logic to decide if the number is multiple of 3&5, 3|5 or none.\n\n# Approach 1 - Using Object Lock\nUsing two instance variables, `n` which is the the last number, `i` which is the currrent number to be printed.\nEach time `i` is incremented, check if it is divisible by 3, 5 according to the functions requireemnts. <br>\nAwait the thread if condition does not satisfy, else increment and notify.\n\n# Code\n```java\nclass FizzBuzz {\n private int n;\n private int i;\n\n public FizzBuzz(int n) {\n this.n = n;\n this.i = 1;\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n synchronized (this) {\n while (i<=n) {\n if (i%3==0 && i%5!=0) {\n printFizz.run();\n i+=1;\n notifyAll(); \n } else {\n wait();\n }\n }\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n synchronized (this) {\n while (i<=n) {\n if (i%3!=0 && i%5==0) {\n printBuzz.run();\n i+=1;\n notifyAll(); \n } else {\n wait();\n }\n }\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n synchronized (this) {\n while (i<=n) {\n if (i%15==0) {\n printFizzBuzz.run();\n i+=1;\n notifyAll(); \n } else {\n wait();\n }\n }\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n synchronized (this) {\n while (i<=n) {\n if (i%3!=0 && i%5!=0) {\n printNumber.accept(i);\n i+=1;\n notifyAll(); \n } else {\n wait();\n }\n }\n }\n }\n}\n```\n\n# Approach 2 - Using Semaphore\nThe main logic remains same as above. <br>\nIn place of object lock, here we make use of `Semaphore`.\nWe take 3 semaphores, `fizzSem`, `buzzSem`, `fizzBuzzSem` and `numSem`. <br>\nBased on what is the next value of `currentNum` we release the required semaphore to continue. <br>\nLastly we need to make sure that the program doesn\'t goes on bounded wait, for that we need to release all the semaphores if any acquired. <br>\n\nThis is achieved in `else` part of `release()` function.\n\n# Code\n\n```java\nclass FizzBuzz {\n private int num;\n private int currentNum;\n private Semaphore fizzSem;\n private Semaphore buzzSem;\n private Semaphore fizzBuzzSem;\n private Semaphore numberSem;\n\n public FizzBuzz(int num) {\n this.num = num;\n this.currentNum = 1;\n this.fizzSem = new Semaphore(0);\n this.buzzSem = new Semaphore(0);\n this.fizzBuzzSem = new Semaphore(0);\n this.numberSem = new Semaphore(1);\n }\n\n private void release() {\n currentNum++;\n if (currentNum <= num) {\n if (currentNum % 3 == 0 && currentNum % 5 != 0) {\n fizzSem.release();\n } else if (currentNum % 3 != 0 && currentNum % 5 == 0) {\n buzzSem.release();\n } else if (currentNum % 15 == 0) {\n fizzBuzzSem.release();\n } else {\n numberSem.release();\n }\n } else {\n fizzSem.release();\n buzzSem.release();\n fizzBuzzSem.release();\n numberSem.release();\n }\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n while (currentNum <= num) {\n fizzSem.acquire();\n if (currentNum <= num) {\n printFizz.run();\n }\n release();\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n while (currentNum <= num) {\n buzzSem.acquire();\n if (currentNum <= num) {\n printBuzz.run();\n }\n release();\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n while (currentNum <= num) {\n fizzBuzzSem.acquire();\n if (currentNum <= num) {\n printFizzBuzz.run();\n }\n release();\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n while (currentNum <= num) {\n numberSem.acquire();\n if (currentNum <= num) {\n printNumber.accept(currentNum);\n }\n release();\n } \n }\n}\n```
18
0
['Concurrency', 'Java']
6
fizz-buzz-multithreaded
Java non-blocking solution using AtomicInteger
java-non-blocking-solution-using-atomici-cent
java\nimport java.util.ConcurrentModificationException;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.IntConsumer;\n\nclass Fizz
dimkagorhover
NORMAL
2019-09-19T19:16:35.155375+00:00
2019-09-19T19:16:35.155423+00:00
4,929
false
```java\nimport java.util.ConcurrentModificationException;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.IntConsumer;\n\nclass FizzBuzz {\n\n private final AtomicInteger counter;\n\n private final int n;\n\n public FizzBuzz(int n) {\n this.n = n;\n counter = new AtomicInteger(1);\n }\n\n private void updateToNext(int count) {\n if (!counter.compareAndSet(count, count + 1))\n throw new ConcurrentModificationException();\n }\n\n public void fizz(Runnable printFizz) throws InterruptedException {\n int count;\n while ((count = counter.get()) <= n) {\n if (count % 3 == 0 && count % 5 != 0) {\n printFizz.run();\n updateToNext(count);\n }\n }\n }\n\n public void buzz(Runnable printBuzz) throws InterruptedException {\n int count;\n while ((count = counter.get()) <= n) {\n if (count % 3 != 0 && count % 5 == 0) {\n printBuzz.run();\n updateToNext(count);\n }\n }\n }\n\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n int count;\n while ((count = counter.get()) <= n) {\n if (count % 3 == 0 && count % 5 == 0) {\n printFizzBuzz.run();\n updateToNext(count);\n }\n }\n }\n\n public void number(IntConsumer printNumber) throws InterruptedException {\n int count;\n while ((count = counter.get()) <= n) {\n if (count % 3 != 0 && count % 5 != 0) {\n printNumber.accept(count);\n updateToNext(count);\n }\n }\n }\n}\n```
17
1
['Java']
8
fizz-buzz-multithreaded
Java: Fun and simple CyclicBarrier solution
java-fun-and-simple-cyclicbarrier-soluti-5oan
In this solution we use a CyclicBarrier to hold each iteration of the while loop until each thread has an opportunity to execute. Once all four threads have exe
Reves
NORMAL
2020-03-15T16:06:36.052020+00:00
2020-03-15T16:11:48.963624+00:00
943
false
In this solution we use a CyclicBarrier to hold each iteration of the while loop until each thread has an opportunity to execute. Once all four threads have executed, the Barrier is tripped, the counter increased, and all threads advance to the next iteration.\n\n\n```\nclass FizzBuzz {\n private int n;\n private CyclicBarrier cyclicBarrier;\n private int i;\n\n public FizzBuzz(int n) {\n this.n = n;\n cyclicBarrier = new CyclicBarrier(4, () -> i++); //Barrier tripped when all four threads call await(), which increases the counter\n i = 1;\n }\n\n public void fizz(Runnable printFizz) throws InterruptedException {\n while(i <= n){\n if(i % 3 == 0 && i % 5 != 0)\n printFizz.run();\n \n try{\n cyclicBarrier.await();\n }catch(BrokenBarrierException e){}\n }\n }\n\n public void buzz(Runnable printBuzz) throws InterruptedException {\n while(i <= n){\n if(i % 3 != 0 && i % 5 == 0)\n printBuzz.run();\n \n try{\n cyclicBarrier.await();\n }catch(BrokenBarrierException e){}\n }\n }\n\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n while(i <= n){\n if(i % 3 == 0 && i % 5 == 0)\n printFizzBuzz.run();\n \n try{\n cyclicBarrier.await();\n }catch(BrokenBarrierException e){}\n }\n }\n\n public void number(IntConsumer printNumber) throws InterruptedException {\n while(i <= n){\n if(i % 3 != 0 && i % 5 != 0)\n printNumber.accept(i);\n \n try{\n cyclicBarrier.await();\n }catch(BrokenBarrierException e){}\n }\n }\n}\n\n```
14
0
[]
4
fizz-buzz-multithreaded
Java Using Lock (Mutex Simulation)
java-using-lock-mutex-simulation-by-mjay-1nxy
Logic is pretty simple, just lock the mutex before starting any operation, check the condition, if true do the desired task, if not unlock the mutex so it can b
mjay4
NORMAL
2020-08-04T05:54:30.699444+00:00
2020-08-04T05:56:20.116390+00:00
2,656
false
Logic is pretty simple, just lock the mutex before starting any operation, check the condition, if true do the desired task, if not unlock the mutex so it can be used by some other thread. For every mutex repeat the same operation.\nOne thing to note, if our count is more than n we need to unlock the mutex before it return else it will keep shifting control from one thread to another and won\'t do anything ie, We will get TLE. \nHope this helps. Let me know if u don\'t understand something and do upvote if it helps. Thank u . \n\n\n```\nclass FizzBuzz {\n private int n;\n private int count;\n private final Lock mutex = new ReentrantLock(true);\n public FizzBuzz(int n) {\n this.n = n;\n count = 1;\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n while(1>0){\n mutex.lock();\n if(count>n){\n mutex.unlock();\n return;\n }\n if(count%3==0 && count%5!=0){ \n printFizz.run();\n count++;\n }\n mutex.unlock();\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n while(1>0){\n mutex.lock();\n if(count>n){\n mutex.unlock();\n return;\n }\n if(count%3!=0 && count%5==0){ \n printBuzz.run();\n count++;\n }\n mutex.unlock();\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n while(1>0){\n mutex.lock();\n if(count>n){\n mutex.unlock();\n return;\n }\n if(count%3==0 && count%5==0){ \n printFizzBuzz.run();\n count++;\n }\n mutex.unlock();\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n while(1>0){\n mutex.lock();\n if(count>n){\n mutex.unlock();\n return;\n }\n if(count%3!=0 && count%5!=0){ \n printNumber.accept(count);\n count++;\n }\n mutex.unlock();\n }\n }\n}
13
1
['Java']
1
fizz-buzz-multithreaded
Python 3 | 5 Approaches (Lock/Semaphore/Event/Condition) | Explanation
python-3-5-approaches-locksemaphoreevent-leqp
Explanation\n- Semaphore(1) can be used to replace Lock(), therefore 5 approaches\n- Very similar to 1116. Print Zero Even Odd\n- Make sure we have control over
idontknoooo
NORMAL
2022-12-27T06:55:37.025076+00:00
2022-12-27T07:17:23.560418+00:00
1,876
false
## Explanation\n- `Semaphore(1)` can be used to replace `Lock()`, therefore 5 approaches\n- Very similar to [1116. Print Zero Even Odd](https://leetcode.com/problems/print-zero-even-odd/description/)\n- Make sure we have control over the executing order by using `Lock/Semaphore/Condition/Lock`.\n- The `Barrier` solution is slightly different, as it doens\'t really care about the executing order, but keep 4 threads in sync for each iteration. The performance might compromise a little bit as it\'s running more iterations than other solutions.\n\n## Approaches \\#1 & 2. Lock/Semaphore\n```python\nfrom threading import Lock\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.fifteen = self.n // 15\n self.three = self.n // 3 - self.fifteen\n self.five = self.n // 5 - self.fifteen\n self.rest = self.n - self.three - self.fifteen - self.five\n self.fl = Lock() # Semaphore(1)\n self.bl = Lock() # Semaphore(1)\n self.fbl = Lock() # Semaphore(1)\n self.nl = Lock() # Semaphore(1)\n self.fl.acquire()\n self.bl.acquire()\n self.fbl.acquire()\n self.cur = 1\n\n def release_lock(self, is_number_thread=False):\n if self.cur % 15 == 0:\n self.fbl.release()\n elif self.cur % 3 == 0:\n self.fl.release()\n elif self.cur % 5 == 0:\n self.bl.release()\n else:\n if not is_number_thread:\n self.nl.release()\n return True\n return False\n\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n for _ in range(self.three):\n with self.fl:\n printFizz()\n self.cur += 1\n self.release_lock()\n self.fl.acquire() \n\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n for _ in range(self.five):\n with self.bl:\n printBuzz()\n self.cur += 1\n self.release_lock()\n self.bl.acquire() \n\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n for _ in range(self.fifteen):\n with self.fbl:\n printFizzBuzz()\n self.cur += 1\n self.release_lock()\n self.fbl.acquire() \n \n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n for _ in range(self.rest):\n again = True \n with self.nl:\n printNumber(self.cur)\n self.cur += 1\n again = self.release_lock(is_number_thread=True)\n if not again:\n self.nl.acquire() \n```\n\n## Approaches \\#3. Condition\n```python\nfrom threading import Condition\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.c = Condition()\n self.cur = 1\n self.fb_cnt = n // 15\n self.fizz_cnt = n // 3 - self.fb_cnt\n self.buzz_cnt = n // 5 - self.fb_cnt\n self.other = n - self.fb_cnt - self.fizz_cnt - self.buzz_cnt\n\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n for _ in range(self.fizz_cnt):\n with self.c:\n self.c.wait_for(lambda: self.cur % 3 == 0 and self.cur % 5 != 0)\n printFizz()\n self.cur += 1\n self.c.notify_all()\n\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n for _ in range(self.buzz_cnt):\n with self.c:\n self.c.wait_for(lambda: self.cur % 3 != 0 and self.cur % 5 == 0)\n printBuzz()\n self.cur += 1\n self.c.notify_all()\n\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n for _ in range(self.fb_cnt):\n with self.c:\n self.c.wait_for(lambda: self.cur % 15 == 0)\n printFizzBuzz()\n self.cur += 1\n self.c.notify_all()\n \n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n for _ in range(self.other):\n with self.c:\n self.c.wait_for(lambda: self.cur % 15 and self.cur % 3 and self.cur % 5)\n printNumber(self.cur)\n self.cur += 1\n self.c.notify_all()\n```\n## Approaches \\#4. Event\n```python\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.ef = Event()\n self.eb = Event()\n self.efb = Event()\n self.en = Event()\n self.cur = 1\n self.fb_cnt = n // 15\n self.fizz_cnt = n // 3 - self.fb_cnt\n self.buzz_cnt = n // 5 - self.fb_cnt\n self.other = n - self.fb_cnt - self.fizz_cnt - self.buzz_cnt\n\n def set_flag(self):\n if self.cur % 15 == 0:\n self.efb.set()\n elif self.cur % 5 == 0:\n self.eb.set()\n elif self.cur % 3 == 0:\n self.ef.set()\n else:\n self.en.set()\n\n\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n for _ in range(self.fizz_cnt):\n while not (self.cur % 3 == 0 and self.cur % 5 != 0):\n self.ef.wait()\n printFizz()\n self.cur += 1\n self.ef.clear()\n self.set_flag()\n\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n for _ in range(self.buzz_cnt):\n while not (self.cur % 3 != 0 and self.cur % 5 == 0):\n self.eb.wait()\n printBuzz()\n self.cur += 1\n self.eb.clear()\n self.set_flag()\n\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n for _ in range(self.fb_cnt):\n while not (self.cur % 15 == 0):\n self.efb.wait()\n printFizzBuzz()\n self.cur += 1\n self.efb.clear()\n self.set_flag()\n \n\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n for _ in range(self.other):\n while not (self.cur % 15 and self.cur % 3 and self.cur % 5):\n self.en.wait()\n printNumber(self.cur)\n self.cur += 1\n self.en.clear()\n self.set_flag()\n```\n\n## Approaches \\#5. Barrier\n```python\nfrom threading import Barrier\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n + 1\n self.br = Barrier(4)\n\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n for cur in range(1, self.n):\n if cur % 3 == 0 and cur % 5 != 0:\n printFizz()\n self.br.wait()\n\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n for cur in range(1, self.n):\n if cur % 3 != 0 and cur % 5 == 0:\n printBuzz()\n self.br.wait()\n\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n for cur in range(1, self.n):\n if cur % 3 == 0 and cur % 5 == 0:\n printFizzBuzz()\n self.br.wait()\n\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n for cur in range(1, self.n):\n if cur % 3 != 0 and cur % 5 != 0:\n printNumber(cur)\n self.br.wait()\n```
11
0
['Concurrency', 'Python3']
2
fizz-buzz-multithreaded
Python beats 100% using Semaphore
python-beats-100-using-semaphore-by-utad-npcm
When we know N, we know how many times 3\'s multiple appears, which is N/3. We also know N/5 is the number of 5\'s multiple, N/15 is the number of 15\'s multipl
utada
NORMAL
2019-09-19T03:30:21.238094+00:00
2019-09-19T03:52:13.910123+00:00
2,891
false
When we know N, we know how many times 3\'s multiple appears, which is N/3. We also know N/5 is the number of 5\'s multiple, N/15 is the number of 15\'s multiple. \nTotally, we print fuzzbuzz N/15 times, print fuzz N/3-N-15 times, and print buzz N/5-N/15 times.\nWe firstly execute thread function number(),and according to x we are meeting now, we choose which kind of thread to execute and then back to thread number() until x>N.\n```\nimport threading\nclass FizzBuzz(object):\n def __init__(self, n):\n self.n = n\n self.fz = threading.Semaphore(0)\n self.bz = threading.Semaphore(0)\n self.fzbz = threading.Semaphore(0)\n self.num = threading.Semaphore(1)\n\n def fizz(self, printFizz):\n for i in range(self.n/3-self.n/15):\n self.fz.acquire()\n printFizz()\n self.num.release()\n\n def buzz(self, printBuzz):\n for i in range(self.n/5-self.n/15):\n self.bz.acquire()\n printBuzz()\n self.num.release()\n\n def fizzbuzz(self, printFizzBuzz):\n for i in range(self.n/15):\n self.fzbz.acquire()\n printFizzBuzz()\n self.num.release()\n \n def number(self, printNumber):\n for i in range(1, self.n+1):\n self.num.acquire()\n if i%3==0 and i%5 ==0:\n self.fzbz.release()\n elif i%3==0:\n self.fz.release()\n elif i%5==0:\n self.bz.release()\n else:\n printNumber(i)\n self.num.release()\n \n```\n![image](https://assets.leetcode.com/users/utada/image_1568863311.png)\n
11
3
['Python']
2
fizz-buzz-multithreaded
Multi-threaded FizzBuzz using Mutex and Condition Variable [O(n)]
multi-threaded-fizzbuzz-using-mutex-and-kfphb
Intuition\n Describe your first thoughts on how to solve this problem. \nThe code uses a mutex and condition variable to synchronize the output of the different
freddyt18
NORMAL
2023-04-29T14:04:49.810372+00:00
2023-04-29T14:04:49.810416+00:00
1,965
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code uses a mutex and condition variable to synchronize the output of the different methods (fizz, buzz, fizzbuzz, and number) and ensure that they are executed in the correct order. \n\nThe wait conditions for each method are defined using lambda functions. \n\nThe private member variable "i" keeps track of the current number being printed and is incremented in each method after the corresponding output has been printed. \n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach used in this code is known as multi-threaded programming, which involves creating multiple threads of execution that can run concurrently to perform different tasks or parts of a task. \n\nThe use of a mutex and condition variable is a common technique for synchronizing the access to shared resources or coordinating the execution of different threads. This approach is widely used in systems programming, parallel computing, and distributed computing, among other areas.\n> This approach simplifies the logic of the wait conditions and avoids duplicating code in each method, resulting in a concise and efficient implementation of the FizzBuzz problem.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this code is O(n), where n is the maximum number to be printed. This is because each number from 1 to n is printed exactly once. \n\nThe time complexity of each of the four methods (fizz, buzz, fizzbuzz, and number) is also O(n), as each method is called exactly n/3, n/5, n/15, and (n - n/3 - n/5 + n/15) times respectively, which simplifies to O(n) for each method. The use of multi-threading does not affect the time complexity of the code, as each thread executes the same amount of work and the threads are synchronized to ensure that the output is printed in the correct order.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity of this code is O(1), which is constant space complexity. \n\nThis is because the code does not use any data structures that grow in size with the input size n. \n\nThe only memory usage is for the private member variables "n" and "i", which are integers and therefore have a constant size, as well as the mutex and condition variable, which are also constant in size. The code does not allocate any dynamic memory or use any other data structures that grow with n. Therefore, the space complexity of the code is constant and does not depend on the input size.\n\n# Code\n```\nclass FizzBuzz {\nprivate:\n int n;\n int i;\n\npublic:\n FizzBuzz(int n) {\n this->n = n;\n this->i = 1;\n }\n\n // printFizz() outputs "fizz".\n void fizz(function<void()> printFizz) {\n while (true) {\n unique_lock<mutex> lock(m);\n cv.wait(lock, [&]{return (i % 3 == 0 && i % 5 != 0) || i > n;});\n if (i > n) return;\n printFizz();\n ++i;\n cv.notify_all();\n }\n }\n\n // printBuzz() outputs "buzz".\n void buzz(function<void()> printBuzz) {\n while (true) {\n unique_lock<mutex> lock(m);\n cv.wait(lock, [&]{return (i % 5 == 0 && i % 3 != 0) || i > n;});\n if (i > n) return;\n printBuzz();\n ++i;\n cv.notify_all();\n }\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n void fizzbuzz(function<void()> printFizzBuzz) {\n while (true) {\n unique_lock<mutex> lock(m);\n cv.wait(lock, [&]{return i % 15 == 0 || i > n;});\n if (i > n) return;\n printFizzBuzz();\n ++i;\n cv.notify_all();\n }\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n void number(function<void(int)> printNumber) {\n while (true) {\n unique_lock<mutex> lock(m);\n cv.wait(lock, [&]{return (i % 3 != 0 && i % 5 != 0) || i > n;});\n if (i > n) return;\n printNumber(i);\n ++i;\n cv.notify_all();\n }\n }\n\nprivate:\n mutex m;\n condition_variable cv;\n};\n\n```
9
0
['C++']
1
fizz-buzz-multithreaded
Python, Condition, wait_for()
python-condition-wait_for-by-marboni-qy7j
\nimport threading\nfrom functools import partial\n\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.cur = 1\n self.co
marboni
NORMAL
2020-12-20T20:13:22.718978+00:00
2020-12-20T20:13:22.719011+00:00
903
false
```\nimport threading\nfrom functools import partial\n\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.cur = 1\n self.condition = threading.Condition()\n\n # printFizz() outputs "fizz"\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n \tself._execute(lambda cur: printFizz(), lambda cur: cur % 3 == 0 and cur % 5 != 0)\n\n # printBuzz() outputs "buzz"\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n \tself._execute(lambda cur: printBuzz(), lambda cur: cur % 3 != 0 and cur % 5 == 0)\n\n # printFizzBuzz() outputs "fizzbuzz"\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n self._execute(lambda cur: printFizzBuzz(), lambda cur: cur % 3 == 0 and cur % 5 == 0)\n\n # printNumber(x) outputs "x", where x is an integer.\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n self._execute(lambda cur: printNumber(cur), lambda cur: cur % 3 != 0 and cur % 5 != 0)\n \n def _execute(self, func, condition_func):\n with self.condition:\n while True:\n self.condition.wait_for(lambda: condition_func(self.cur) or self.cur > self.n)\n \n try:\n if self.cur > self.n:\n return\n else:\n func(self.cur)\n self.cur += 1\n finally: \n self.condition.notify_all()\n```\t\t\t\t\t
9
1
[]
0
fizz-buzz-multithreaded
C++ Very Simple Solution Using 3 Semaphores
c-very-simple-solution-using-3-semaphore-ci6d
\n#include <semaphore.h>\nclass FizzBuzz {\nprivate:\n int n;\n sem_t fizz_sem;\n sem_t buzz_sem;\n sem_t fizzbuzz_sem;\n\npublic:\n FizzBuzz(int
yehudisk
NORMAL
2020-11-19T18:29:25.800975+00:00
2020-11-19T18:29:25.801015+00:00
1,235
false
```\n#include <semaphore.h>\nclass FizzBuzz {\nprivate:\n int n;\n sem_t fizz_sem;\n sem_t buzz_sem;\n sem_t fizzbuzz_sem;\n\npublic:\n FizzBuzz(int n) {\n this->n = n;\n sem_init(&fizz_sem, 0, 0);\n sem_init(&buzz_sem, 0, 0);\n sem_init(&fizzbuzz_sem, 0, 0);\n }\n \n ~FizzBuzz() {\n sem_destroy(&fizz_sem);\n sem_destroy(&buzz_sem);\n sem_destroy(&fizzbuzz_sem);\n }\n\n // printFizz() outputs "fizz".\n void fizz(function<void()> printFizz) {\n for (int i = 3; i <= n; i += 3) {\n // divides by 3 but not by 5\n if (i % 5) { \n sem_wait(&fizz_sem);\n printFizz();\n }\n }\n }\n\n // printBuzz() outputs "buzz".\n void buzz(function<void()> printBuzz) {\n for (int i = 5; i <= n; i += 5) {\n // divides by 5 but not by 3\n if (i % 3) {\n sem_wait(&buzz_sem);\n printBuzz();\n }\n }\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n\tvoid fizzbuzz(function<void()> printFizzBuzz) {\n for (int i = 15; i <= n; i += 15) {\n sem_wait(&fizzbuzz_sem);\n printFizzBuzz();\n }\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n void number(function<void(int)> printNumber) {\n for (int i = 1; i <= n; i++) {\n if (i % 3 == 0) {\n if (i % 5 == 0)\n sem_post(&fizzbuzz_sem);\n else\n sem_post(&fizz_sem);\n }\n else if (i % 5 == 0)\n sem_post(&buzz_sem);\n else\n printNumber(i);\n }\n }\n};\n```\n**Like it? please upvote\nHave any comments? I\'d love to hear!**
9
6
['C']
4
fizz-buzz-multithreaded
JAVA using Synchronized
java-using-synchronized-by-shivbaba-5w89
\nTaking a shared variable - count. Protecting it using synchronized. If condition is not correct, wait(). Else print, increase the count and notify other waiti
shivbaba
NORMAL
2021-07-18T17:37:21.296062+00:00
2021-07-18T17:37:43.041001+00:00
1,592
false
\nTaking a shared variable - count. Protecting it using synchronized. If condition is not correct, wait(). Else print, increase the count and notify other waiting threads so that they can resume running. \n\nclass FizzBuzz {\n private int n;\n private int count;\n\n public FizzBuzz(int n) {\n this.n = n;\n this.count = 1;\n }\n\n // printFizz.run() outputs "fizz".\n synchronized public void fizz(Runnable printFizz) throws InterruptedException {\n while (count <= n) {\n if (count % 3 == 0 && count % 5 != 0) {\n count++;\n printFizz.run();\n notifyAll();\n } else {\n wait();\n }\n }\n }\n\n // printBuzz.run() outputs "buzz".\n synchronized public void buzz(Runnable printBuzz) throws InterruptedException {\n while (count <= n) {\n if (count % 5 == 0 && count % 3 != 0) {\n printBuzz.run();\n count++;\n notifyAll();\n } else {\n wait();\n }\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n synchronized public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n while (count <= n) {\n if (count % 15 == 0) {\n printFizzBuzz.run();\n count++;\n notifyAll();\n } else {\n wait();\n }\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n synchronized public void number(IntConsumer printNumber) throws InterruptedException {\n while (count <= n) {\n if (count % 3 == 0 || count % 5 == 0) {\n wait();\n } else {\n printNumber.accept(count);\n count++;\n notifyAll();\n }\n }\n }\n}
8
0
['Java']
2
fizz-buzz-multithreaded
Easy Mutex Solution || Love Babbar Approach || Best Way 🔥🔥
easy-mutex-solution-love-babbar-approach-q2k6
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
abhi_pandit_18
NORMAL
2023-07-13T06:09:11.805113+00:00
2023-07-13T06:09:11.805158+00:00
1,339
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass FizzBuzz {\nprivate:\n int n;\n mutex m;\n condition_variable c;\n int i;\n\npublic:\n FizzBuzz(int n) {\n this->n = n;\n this->i = 1;\n }\n\n // printFizz() outputs "fizz".\n void fizz(function<void()> printFizz) {\n while(i<=n)\n {\n unique_lock<mutex> lock(m);\n while(i<=n && (((i%3) == 0) && ((i%5) != 0)) == 0)\n {\n c.wait(lock);\n }\n if(i<=n)\n {\n printFizz();\n i++;\n }\n c.notify_all();\n }\n }\n\n // printBuzz() outputs "buzz".\n void buzz(function<void()> printBuzz) {\n while(i<=n)\n {\n unique_lock<mutex> lock(m);\n while(i<=n && (((i%3) != 0) && ((i%5) == 0)) == 0)\n {\n c.wait(lock);\n }\n if(i<=n)\n {\n printBuzz();\n i++;\n }\n c.notify_all();\n }\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n\tvoid fizzbuzz(function<void()> printFizzBuzz) {\n while(i<=n)\n {\n unique_lock<mutex> lock(m);\n while(i<=n && (((i%3) == 0) && ((i%5) == 0)) == 0)\n {\n c.wait(lock);\n }\n if(i<=n)\n {\n printFizzBuzz();\n i++;\n }\n c.notify_all();\n }\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n void number(function<void(int)> printNumber) {\n while(i<=n)\n {\n unique_lock<mutex> lock(m);\n while(i<=n && (((i%3) != 0) && ((i%5) != 0)) == 0)\n {\n c.wait(lock);\n }\n if(i<=n)\n {\n printNumber(i++);\n }\n c.notify_all();\n }\n }\n};\n```
7
0
['C++']
3
fizz-buzz-multithreaded
Java wait/notifyAll
java-waitnotifyall-by-softarium-lsuu
\nclass FizzBuzz {\n private final int max;\n private int counter = 1;\n public FizzBuzz(int n) { this.max = n; }\n\n private synchronized void sync
softarium
NORMAL
2021-12-03T21:02:49.845025+00:00
2021-12-03T21:02:49.845051+00:00
578
false
```\nclass FizzBuzz {\n private final int max;\n private int counter = 1;\n public FizzBuzz(int n) { this.max = n; }\n\n private synchronized void synchronizedPrint(final Runnable print, final IntPredicate predicate) throws InterruptedException {\n while (counter <= max) {\n if (predicate.test(counter)) {\n print.run();\n counter++;\n this.notifyAll();\n } else {\n this.wait();\n }\n }\n }\n\n public void fizz(final Runnable printFizz) throws InterruptedException {\n synchronizedPrint(printFizz, n -> n % 3 == 0 && n % 5 != 0);\n }\n\n public void buzz(final Runnable printBuzz) throws InterruptedException {\n synchronizedPrint(printBuzz, n -> n % 5 == 0 && n % 3 != 0);\n }\n\n public void fizzbuzz(final Runnable printFizzBuzz) throws InterruptedException {\n synchronizedPrint(printFizzBuzz, n -> n % 15 == 0);\n }\n\n public void number(final IntConsumer printNumber) throws InterruptedException {\n synchronizedPrint(() -> printNumber.accept(counter), n -> n % 3 != 0 && n % 5 != 0);\n }\n}\n```
7
0
[]
2
fizz-buzz-multithreaded
Java - 8 ms - Use a semaphore with one permit
java-8-ms-use-a-semaphore-with-one-permi-grjy
\nclass FizzBuzz {\n private static int NUMBER_OF_PRINT_LICENSES = 1;\n \n private int n;\n private int printIndex;\n private Semaphore printLice
ed-karabinus
NORMAL
2021-04-18T07:06:43.201147+00:00
2021-04-18T07:06:43.201190+00:00
928
false
```\nclass FizzBuzz {\n private static int NUMBER_OF_PRINT_LICENSES = 1;\n \n private int n;\n private int printIndex;\n private Semaphore printLicense;\n\n public FizzBuzz(int n) {\n this.n = n;\n this.printIndex = 1;\n this.printLicense = new Semaphore(NUMBER_OF_PRINT_LICENSES);\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n runRunnableBasedOnPredicate(\n printFizz, \n (printIndex) -> printIndex % 3 == 0 && printIndex % 15 != 0\n );\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n runRunnableBasedOnPredicate(\n printBuzz, \n (printIndex) -> printIndex % 5 == 0 && printIndex % 15 != 0\n );\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n runRunnableBasedOnPredicate(\n printFizzBuzz, \n (printIndex) -> printIndex % 15 == 0\n );\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n while (shouldLoopContinue()) {\n printLicense.acquire();\n if (shouldLoopContinue() &&\n printIndex % 3 != 0 && \n printIndex % 5 != 0\n ) {\n printNumber.accept(printIndex);\n printIndex++;\n }\n printLicense.release();\n }\n }\n \n private void runRunnableBasedOnPredicate(\n Runnable runnable, \n Predicate<Integer> predicate\n ) throws InterruptedException {\n while (shouldLoopContinue()) {\n printLicense.acquire();\n if (shouldLoopContinue() && \n predicate.test(printIndex)\n ) {\n runnable.run();\n printIndex++;\n }\n printLicense.release();\n }\n }\n \n private Boolean shouldLoopContinue() {\n return printIndex <= n;\n }\n}\n```
7
0
['Java']
4
fizz-buzz-multithreaded
Beats 100% Other Solutions
beats-100-other-solutions-by-day_tripper-8b69
\nimport threading\n\nclass FizzBuzz:\n def __init__(self, n: int): \n self.n = n\n self.f = threading.Lock()\n self.b = threading.
Day_Tripper
NORMAL
2022-07-21T03:41:39.874544+00:00
2022-07-21T03:41:39.874588+00:00
1,314
false
```\nimport threading\n\nclass FizzBuzz:\n def __init__(self, n: int): \n self.n = n\n self.f = threading.Lock()\n self.b = threading.Lock()\n self.fb = threading.Lock()\n self.f.acquire()\n self.b.acquire()\n self.fb.acquire()\n self.main = threading.Lock()\n\n # printFizz() outputs "fizz"\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n while True:\n self.f.acquire()\n if self.n == 0 :\n return\n printFizz()\n self.main.release()\n\n # printBuzz() outputs "buzz"\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n while True:\n self.b.acquire()\n if self.n == 0:\n return\n printBuzz()\n self.main.release()\n\n # printFizzBuzz() outputs "fizzbuzz"\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n while True:\n self.fb.acquire()\n if self.n == 0:\n return\n printFizzBuzz()\n self.main.release()\n\n # printNumber(x) outputs "x", where x is an integer.\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n for i in range(1, self.n+1):\n #print("number:",i)\n self.main.acquire()\n if i % 15 == 0:\n self.fb.release()\n elif i % 3 == 0:\n self.f.release()\n elif i % 5 == 0:\n self.b.release()\n else:\n printNumber(i)\n self.main.release()\n\n self.main.acquire() \n self.n = 0\n self.f.release()\n self.b.release()\n self.fb.release()\n return\n```
6
0
[]
0
fizz-buzz-multithreaded
C++, single mutex, but not spinlock or roundrobin
c-single-mutex-but-not-spinlock-or-round-x8vz
Each thread checks for its unique condition, so it\'s safe but slower\n\nclass FizzBuzz {\nprivate:\n int n;\n int current_number;\n mutex number_mutex
nalivai
NORMAL
2020-09-09T20:18:25.881308+00:00
2020-09-09T20:21:39.877324+00:00
1,328
false
Each thread checks for its unique condition, so it\'s safe but slower\n```\nclass FizzBuzz {\nprivate:\n int n;\n int current_number;\n mutex number_mutex;\n const int number_of_threads = 4;\n bool done = true;\n \npublic:\n FizzBuzz(int n) {\n this->n = n;\n if (n > 0){\n done = false;\n }\n current_number = 1;\n }\n\nprivate: \n void nextNumber(){\n if (current_number < n){\n scoped_lock lock(number_mutex);\n current_number++;\n } else{\n done = true;\n }\n }\n\npublic: \n // printFizz() outputs "fizz".\n void fizz(function<void()> printFizz) { \n while (!done){\n if (!(current_number % 3 ) && (current_number % 5)){\n printFizz();\n nextNumber(); \n }\n }\n }\n\n // printBuzz() outputs "buzz".\n void buzz(function<void()> printBuzz) { \n while (!done){\n if ((current_number % 3 ) && !(current_number % 5)){\n printBuzz();\n nextNumber(); \n }\n }\n }\n \n // printFizzBuzz() outputs "fizzbuzz".\n\tvoid fizzbuzz(function<void()> printFizzBuzz) {\n while (!done){\n if (!(current_number % 3 ) && !(current_number % 5)){\n printFizzBuzz();\n nextNumber(); \n }\n }\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n void number(function<void(int)> printNumber) {\n \n while (!done){\n if ((current_number % 3 ) && (current_number % 5)){\n printNumber(current_number);\n nextNumber(); \n }\n }\n }\n};\n```
6
0
['C', 'C++']
2
fizz-buzz-multithreaded
C# SemaphoreSlim Array
c-semaphoreslim-array-by-olegbelousov77-ci49
csharp\nusing System.Threading;\n\npublic class FizzBuzz {\n \n private enum FizzBuzzEnum {\n Fizz = 0,\n Buzz = 1,\n FizzBuzz = 2,\n
olegbelousov77
NORMAL
2021-11-21T21:13:27.148870+00:00
2021-11-21T21:13:27.148922+00:00
658
false
```csharp\nusing System.Threading;\n\npublic class FizzBuzz {\n \n private enum FizzBuzzEnum {\n Fizz = 0,\n Buzz = 1,\n FizzBuzz = 2,\n Number = 3\n }\n \n private int _n;\n private int _k;\n private SemaphoreSlim[] _semaphores;\n private CancellationTokenSource _cts;\n\n public FizzBuzz(int n) {\n _n = n;\n _k = 0;\n _semaphores = Enum\n .GetValues<FizzBuzzEnum>()\n .Select(v => new SemaphoreSlim(0,1))\n .ToArray();\n _cts = new CancellationTokenSource();\n _semaphores[(int)GetFizzBuzz(++_k)].Release();\n }\n\n public void Fizz(Action printFizz) => \n Execute(FizzBuzzEnum.Fizz, printFizz);\n\n public void Buzz(Action printBuzz) => \n Execute(FizzBuzzEnum.Buzz, printBuzz);\n\n public void Fizzbuzz(Action printFizzBuzz) => \n Execute(FizzBuzzEnum.FizzBuzz, printFizzBuzz);\n\n public void Number(Action<int> printNumber) => \n Execute(FizzBuzzEnum.Number, () => printNumber(_k));\n \n private void Execute(FizzBuzzEnum fizzbuzz, Action action) {\n try {\n while (_k <= _n) {\n _semaphores[(int)fizzbuzz].Wait(_cts.Token);\n if (_k <= _n) {\n action();\n _semaphores[(int)GetFizzBuzz(++_k)].Release();\n }\n }\n _cts.Cancel();\n } catch (OperationCanceledException) {\n \n }\n }\n \n private FizzBuzzEnum GetFizzBuzz(int i) {\n if (i % 3 == 0 && i % 5 == 0)\n return FizzBuzzEnum.FizzBuzz;\n if (i % 3 == 0 && i % 5 != 0)\n return FizzBuzzEnum.Fizz;\n if (i % 3 != 0 && i % 5 == 0)\n return FizzBuzzEnum.Buzz;\n return FizzBuzzEnum.Number;\n }\n}\n```
5
0
['C#']
1
fizz-buzz-multithreaded
Python3 four locks
python3-four-locks-by-mxmb-vp6p
python\nimport threading as t\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.count = 1\n self.num_lock, self.fizz_lo
mxmb
NORMAL
2021-08-21T18:57:49.406449+00:00
2021-08-21T19:01:07.556241+00:00
937
false
```python\nimport threading as t\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.count = 1\n self.num_lock, self.fizz_lock, self.buzz_lock, self.fizzbuzz_lock = t.Lock(), t.Lock(), t.Lock(), t.Lock()\n self.fizz_lock.acquire()\n self.buzz_lock.acquire()\n self.fizzbuzz_lock.acquire()\n\n # printFizz() outputs "fizz"\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n for _ in range(self.n//3-self.n//15):\n self.fizz_lock.acquire()\n printFizz()\n self.num_lock.release()\n\n # printBuzz() outputs "buzz"\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n for _ in range(self.n//5-self.n//15):\n self.buzz_lock.acquire()\n printBuzz()\n self.num_lock.release()\n\n # printFizzBuzz() outputs "fizzbuzz"\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n for _ in range(self.n//15):\n self.fizzbuzz_lock.acquire()\n printFizzBuzz()\n self.num_lock.release()\n\n # printNumber(x) outputs "x", where x is an integer.\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n for i in range(1,self.n+1):\n self.num_lock.acquire()\n if not i%15:\n self.fizzbuzz_lock.release()\n elif not i%3:\n self.fizz_lock.release()\n elif not i%5:\n self.buzz_lock.release()\n else:\n printNumber(i)\n self.num_lock.release()\n```
5
0
['Python', 'Python3']
1
fizz-buzz-multithreaded
Java Solution with Locks
java-solution-with-locks-by-anjana9-o0it
\nclass FizzBuzz {\n private int n;\n private int count;\n private Object lock;\n\n public FizzBuzz(int n) {\n this.n = n;\n this.coun
anjana9
NORMAL
2020-10-12T05:49:06.750774+00:00
2020-10-12T05:56:42.269903+00:00
1,289
false
```\nclass FizzBuzz {\n private int n;\n private int count;\n private Object lock;\n\n public FizzBuzz(int n) {\n this.n = n;\n this.count = 1;\n this.lock = new Object();\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n while(count<=n) {\n synchronized (lock) {\n if (count<=n && count % 3 == 0 && count % 5 != 0) {\n printFizz.run();\n count++;\n }\n }\n\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n while(count<=n) {\n synchronized (lock) {\n if (count<=n && count % 5 == 0 && count % 3 != 0) {\n printBuzz.run();\n count++;\n }\n }\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n while(count<=n) {\n synchronized (lock) {\n if (count<=n && count % 5 == 0 && count % 3 == 0) {\n printFizzBuzz.run();\n count++;\n }\n }\n }\n\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n while(count<=n) {\n synchronized (lock) {\n if (count<=n && count % 3 != 0 && count % 5 != 0) {\n printNumber.accept(count);\n count++;\n }\n }\n }\n }\n}\n```
5
1
['Java']
6
fizz-buzz-multithreaded
Easy C !! One mutex and One Condition variable.
easy-c-one-mutex-and-one-condition-varia-5gzi
Use the mutex for locking the current number.\n- Fizz() thread sleeps on the condition variable if either the current number is divisible by 5 or not divisible
csd2592
NORMAL
2019-10-13T00:50:11.498111+00:00
2019-10-13T00:50:11.498147+00:00
1,048
false
Use the mutex for locking the current number.\n- Fizz() thread sleeps on the condition variable if either the current number is divisible by 5 or not divisible by 3.\n- Buzz() thread sleeps on the condition variable if either the current number is divisible by 3 or not divisible by 5.\n- FizzBuzz() thread sleeps on the condition variable if either the current number is not divisible by 3 or not divisible by 5.\n- Number() thread sleeps on the condition variable if either the current number is divisible by 3 or divisible by 5. \n\n```\n#include <stdlib.h>\n#include <stdio.h>\n#include <pthread.h>\n\n\ntypedef struct {\n int n;\n int curr;\n pthread_mutex_t m;\n pthread_cond_t cv;\n} FizzBuzz;\n\nFizzBuzz* fizzBuzzCreate(int n) {\n FizzBuzz* obj = (FizzBuzz*) malloc(sizeof(FizzBuzz));\n obj->n = n;\n obj->curr = 1;\n pthread_mutex_init(&obj->m, NULL);\n pthread_cond_init(&obj->cv, NULL);\n return obj;\n}\n\n// printFizz() outputs "fizz".\nvoid fizz(FizzBuzz* obj) {\n while (1) {\n pthread_mutex_lock(&obj->m);\n while (obj->curr <= obj->n &&\n (obj->curr % 5 == 0 || obj->curr % 3 != 0)) {\n pthread_cond_wait(&obj->cv, &obj->m);\n }\n\n if (obj->curr > obj->n) {\n pthread_mutex_unlock(&obj->m);\n return;\n }\n\n printFizz();\n obj->curr++;\n pthread_cond_broadcast(&obj->cv);\n pthread_mutex_unlock(&obj->m);\n }\n}\n\n// printBuzz() outputs "buzz".\nvoid buzz(FizzBuzz* obj) {\n while (1) {\n pthread_mutex_lock(&obj->m);\n while (obj->curr <= obj->n &&\n (obj->curr % 5 != 0 || obj->curr % 3 == 0)) {\n pthread_cond_wait(&obj->cv, &obj->m);\n }\n\n if (obj->curr > obj->n) {\n pthread_mutex_unlock(&obj->m);\n return;\n }\n\n printBuzz();\n obj->curr++;\n pthread_cond_broadcast(&obj->cv);\n pthread_mutex_unlock(&obj->m);\n } \n}\n\n// printFizzBuzz() outputs "fizzbuzz".\nvoid fizzbuzz(FizzBuzz* obj) {\n while (1) {\n pthread_mutex_lock(&obj->m);\n while (obj->curr <= obj->n &&\n (obj->curr % 5 != 0 || obj->curr % 3 != 0)) {\n pthread_cond_wait(&obj->cv, &obj->m);\n }\n\n if (obj->curr > obj->n) {\n pthread_mutex_unlock(&obj->m);\n return;\n }\n\n printFizzBuzz();\n obj->curr++;\n pthread_cond_broadcast(&obj->cv);\n pthread_mutex_unlock(&obj->m);\n } \n}\n\n// You may call global function `void printNumber(int x)`\n// to output "x", where x is an integer.\nvoid number(FizzBuzz* obj) {\n while (1) {\n pthread_mutex_lock(&obj->m);\n while (obj->curr <= obj->n &&\n (obj->curr % 5 == 0 || obj->curr % 3 == 0)) {\n pthread_cond_wait(&obj->cv, &obj->m);\n }\n\n if (obj->curr > obj->n) {\n pthread_mutex_unlock(&obj->m);\n return;\n }\n\n printNumber(obj->curr);\n obj->curr++;\n pthread_cond_broadcast(&obj->cv);\n pthread_mutex_unlock(&obj->m);\n } \n}\n\nvoid fizzBuzzFree(FizzBuzz* obj) {\n pthread_mutex_destroy(&obj->m);\n pthread_cond_destroy(&obj->cv);\n free(obj);\n}\n```
5
0
[]
0
fizz-buzz-multithreaded
Python using just 1 Semaphore
python-using-just-1-semaphore-by-lamnguy-38i4
Unlike other solutions which use 4 semaphores, mine uses just one. This sole semaphore acts as a lock that prevent concurrent access to self.cur. Whenever one o
lamnguyen2187
NORMAL
2019-09-20T00:23:41.493327+00:00
2019-09-20T00:23:41.493374+00:00
1,296
false
Unlike other solutions which use 4 semaphores, mine uses just one. This sole semaphore acts as a lock that prevent concurrent access to `self.cur`. Whenever one of `fizz`, `buzz`, `fizzbuzz`, and `number` manages to acquire the lock, it checks if if its turn and act accordingly it if is. Before releasing the lock, it increases `self.cur` by `1`. When `self.cur` becomes bigger than `self.n`, all the while loops in these 4 functions are terminated.\n\n```\nimport threading\n\nclass FizzBuzz(object):\n def __init__(self, n):\n self.n = n\n self.cur = 1\n self.sem = threading.Semaphore(1)\n\n # printFizz() outputs "fizz"\n def fizz(self, printFizz):\n """\n :type printFizz: method\n :rtype: void\n """\n while True:\n self.sem.acquire()\n if self.cur <= self.n and self.cur % 3 == 0 and self.cur % 5 != 0:\n printFizz()\n self.cur += 1\n self.sem.release()\n \n if self.cur > self.n:\n break\n \t\n\n # printBuzz() outputs "buzz"\n def buzz(self, printBuzz):\n """\n :type printBuzz: method\n :rtype: void\n """\n while True:\n self.sem.acquire()\n if self.cur <= self.n and self.cur % 5 == 0 and self.cur % 3 != 0:\n printBuzz()\n self.cur += 1\n self.sem.release()\n\n if self.cur > self.n:\n break\n \t\n\n # printFizzBuzz() outputs "fizzbuzz"\n def fizzbuzz(self, printFizzBuzz):\n """\n :type printFizzBuzz: method\n :rtype: void\n """\n while True:\n self.sem.acquire()\n if self.cur <= self.n and self.cur % 3 == 0 and self.cur % 5 == 0:\n printFizzBuzz()\n self.cur += 1\n self.sem.release()\n \n if self.cur > self.n:\n break\n\t\t\n\n # printNumber(x) outputs "x", where x is an integer.\n def number(self, printNumber):\n """\n :type printNumber: method\n :rtype: void\n """\n while True:\n self.sem.acquire() \n if self.cur <= self.n and self.cur % 3 != 0 and self.cur % 5 != 0:\n printNumber(self.cur)\n self.cur += 1\n self.sem.release()\n \n if self.cur > self.n:\n break\n```
5
3
[]
1
fizz-buzz-multithreaded
Python clean symmetric solution using Condition
python-clean-symmetric-solution-using-co-z2lf
It may not be as fast as the most voted python solution but I think it\'s more concise in a sense that all 4 methods do the same thing but just the condition to
redtree1112
NORMAL
2022-02-26T07:30:23.774228+00:00
2022-02-26T07:30:23.774260+00:00
563
false
It may not be as fast as the most voted python solution but I think it\'s more concise in a sense that all 4 methods do the same thing but just the condition to wait is different.\n\n```\nfrom threading import *\n\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.cur = 1\n self.cond = Condition()\n\n # printFizz() outputs "fizz"\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n while True:\n with self.cond:\n self.cond.wait_for(lambda: self.cur > self.n or (self.cur % 3 == 0 and self.cur % 5 != 0))\n if self.cur > self.n:\n return\n printFizz()\n self.cur += 1\n self.cond.notify_all()\n\n # printBuzz() outputs "buzz"\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n while True:\n \t with self.cond:\n self.cond.wait_for(lambda: self.cur > self.n or (self.cur % 3 != 0 and self.cur % 5 == 0))\n if self.cur > self.n:\n return\n printBuzz()\n self.cur += 1\n self.cond.notify_all()\n\n # printFizzBuzz() outputs "fizzbuzz"\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n while True:\n with self.cond:\n self.cond.wait_for(lambda: self.cur > self.n or (self.cur % 3 == 0 and self.cur % 5 == 0))\n if self.cur > self.n:\n return\n printFizzBuzz()\n self.cur += 1\n self.cond.notify_all()\n\n # printNumber(x) outputs "x", where x is an integer.\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n while True:\n with self.cond:\n self.cond.wait_for(lambda: self.cur > self.n or (self.cur % 3 != 0 and self.cur % 5 != 0))\n if self.cur > self.n:\n return\n printNumber(self.cur)\n self.cur += 1\n self.cond.notify_all()\n \n \n \n```
4
0
[]
1
fizz-buzz-multithreaded
C++ | Condition Variable
c-condition-variable-by-vineet0692-5lw8
We can take advantage of condition variables predicate feature to our advantage so that only one thread is waken up to do its job.\n\n\nclass FizzBuzz {\nprivat
vineet0692
NORMAL
2021-07-03T16:40:41.273492+00:00
2021-07-03T16:40:41.273532+00:00
459
false
We can take advantage of condition variables predicate feature to our advantage so that only one thread is waken up to do its job.\n\n```\nclass FizzBuzz {\nprivate:\n int n;\n int i;\n mutex mtx;\n condition_variable cv;\n\npublic:\n FizzBuzz(int n) {\n i = 1;\n this->n = n;\n }\n\n // printFizz() outputs "fizz".\n void fizz(function<void()> printFizz) {\n while( true ){\n unique_lock<mutex> lock(mtx);\n cv.wait(lock, [this](){return i>n || (i%3 == 0 && i%5 != 0);});\n if( i > n ) break;\n printFizz(); i++;\n cv.notify_all();\n }\n }\n\n // printBuzz() outputs "buzz".\n void buzz(function<void()> printBuzz) {\n while( true ){\n unique_lock<mutex> lock(mtx);\n cv.wait(lock, [this]{return i>n || (i%3 != 0 && i%5 == 0);});\n if( i > n ) break;\n printBuzz(); i++;\n cv.notify_all();\n }\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n\tvoid fizzbuzz(function<void()> printFizzBuzz) {\n while( true ){\n unique_lock<mutex> lock(mtx);\n cv.wait(lock, [this]{return i>n || (i%3 == 0 && i%5 == 0);});\n if( i > n ) break;\n printFizzBuzz(); i++;\n cv.notify_all();\n }\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n void number(function<void(int)> printNumber) {\n while( true ){\n unique_lock<mutex> lock(mtx);\n cv.wait(lock, [this]{return i>n || (i%3 != 0 && i%5 != 0);});\n if( i > n ) break;\n printNumber(i++);\n cv.notify_all();\n }\n }\n};\n```
4
0
[]
0
fizz-buzz-multithreaded
C++ condition variable based sln, clean code
c-condition-variable-based-sln-clean-cod-y30g
```\nclass FizzBuzz {\nprivate:\n int n;\n\npublic:\n FizzBuzz(int n) {\n this->n = n;\n }\n\n void do_staff(function check, function print)
dmitrii_bokovikov
NORMAL
2021-03-24T17:44:10.391240+00:00
2021-03-24T17:44:10.391281+00:00
573
false
```\nclass FizzBuzz {\nprivate:\n int n;\n\npublic:\n FizzBuzz(int n) {\n this->n = n;\n }\n\n void do_staff(function<bool()> check, function<void()> print) {\n while (true) {\n unique_lock lck(mt);\n cv.wait(lck, [&check, this]() { return std::invoke(check) || current > n; });\n if (current <= n) {\n print();\n }\n \n ++current;\n cv.notify_all();\n if (current > n) {\n break;\n }\n }\n }\n \n // printFizz() outputs "fizz".\n void fizz(function<void()> printFizz) {\n do_staff([this]() { return current % 3 == 0 && current % 5 != 0; }, printFizz);\n }\n\n // printBuzz() outputs "buzz".\n void buzz(function<void()> printBuzz) {\n do_staff([this]() { return current % 3 != 0 && current % 5 == 0; }, printBuzz);\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n\tvoid fizzbuzz(function<void()> printFizzBuzz) {\n do_staff([this]() { return current % 3 == 0 && current % 5 == 0; }, printFizzBuzz);\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n void number(function<void(int)> printNumber) {\n do_staff([this]() { return current % 3 != 0 && current % 5 != 0; }, [printNumber, this]() {printNumber(current);});\n }\n \n mutex mt;\n condition_variable cv;\n int current = 1;\n};
4
0
[]
1
fizz-buzz-multithreaded
Python3 solution using barrier
python3-solution-using-barrier-by-johnny-gwrs
python\nfrom threading import Barrier\n\n\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.barrier = Barrier(4)\n\n # prin
johnny5
NORMAL
2021-01-01T13:10:13.977714+00:00
2021-01-01T13:10:13.977743+00:00
453
false
```python\nfrom threading import Barrier\n\n\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.barrier = Barrier(4)\n\n # printFizz() outputs "fizz"\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n for number in range(1, self.n+1):\n if number % 3 == 0 and number % 5:\n printFizz()\n self.barrier.wait()\n\n # printBuzz() outputs "buzz"\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n for number in range(1, self.n+1):\n if number % 3 and number % 5 == 0:\n printBuzz()\n self.barrier.wait()\n\n # printFizzBuzz() outputs "fizzbuzz"\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n for number in range(1, self.n+1):\n if number % 15 == 0:\n printFizzBuzz()\n self.barrier.wait()\n\n # printNumber(x) outputs "x", where x is an integer.\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n for number in range(1, self.n+1):\n if number % 3 and number % 5:\n printNumber(number)\n self.barrier.wait()\n```
4
0
[]
3
fizz-buzz-multithreaded
C# basic lock approach
c-basic-lock-approach-by-superfooman-oq2a
\npublic class FizzBuzz {\n private int n;\n private static int count = 1;\n private Object baton = new Object();\n\t\n\tpublic FizzBuzz(int n) {\n
superfooman
NORMAL
2020-12-09T04:05:53.134172+00:00
2020-12-09T04:05:53.134222+00:00
306
false
```\npublic class FizzBuzz {\n private int n;\n private static int count = 1;\n private Object baton = new Object();\n\t\n\tpublic FizzBuzz(int n) {\n this.n = n;\n }\n\t\n private void syncRun(Func<int, bool> condition, Action<int> action){\n\t\twhile(true){ \n lock(baton){\n \n if(count > n)\n return;\n \n if(condition(count)){\n action(count);\n count++;\n }\n }\n }\n }\n\t\n // printFizz() outputs "fizz".\n public void Fizz(Action printFizz) {\n syncRun( i => i%3 == 0 && i%5 != 0, x => printFizz());\n }\n\n // printBuzzz() outputs "buzz".\n public void Buzz(Action printBuzz) {\n syncRun( i => i%5 == 0 && i%3 != 0, x => printBuzz());\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n public void Fizzbuzz(Action printFizzBuzz) {\n syncRun( i => i%3 == 0 && i%5== 0 , x => printFizzBuzz());\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n public void Number(Action<int> printNumber) {\n syncRun( i => i%3 != 0 && i%5 != 0 , x => printNumber(x)); \n }\n \n}\n```
4
0
[]
0
fizz-buzz-multithreaded
C# using Barrier
c-using-barrier-by-polybios-f0k0
\nusing System.Threading;\npublic class FizzBuzz {\n \n private int n;\n private Barrier b = new Barrier(4);\n\n public FizzBuzz(int n)\n {\n
polybios
NORMAL
2020-06-06T17:17:40.531487+00:00
2020-06-06T17:19:24.107535+00:00
562
false
```\nusing System.Threading;\npublic class FizzBuzz {\n \n private int n;\n private Barrier b = new Barrier(4);\n\n public FizzBuzz(int n)\n {\n this.n = n;\n }\n\n // printFizz() outputs "fizz".\n public void Fizz(Action printFizz)\n {\n for (int i = 1; i <= n; ++i)\n {\n if (i % 3 == 0 && i % 5 != 0) printFizz();\n b.SignalAndWait();\n }\n }\n\n // printBuzzz() outputs "buzz".\n public void Buzz(Action printBuzz)\n {\n for (int i = 1; i <= n; ++i)\n {\n if (i % 3 != 0 && i % 5 == 0) printBuzz();\n b.SignalAndWait();\n }\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n public void Fizzbuzz(Action printFizzBuzz)\n {\n for (int i = 1; i <= n; ++i)\n {\n if (i % 3 == 0 && i % 5 == 0) printFizzBuzz();\n b.SignalAndWait();\n }\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n public void Number(Action<int> printNumber)\n {\n for (int i = 1; i <= n; ++i)\n {\n if (i % 3 != 0 && i % 5 != 0) printNumber(i);\n b.SignalAndWait();\n }\n }\n}\n```
4
0
[]
5
fizz-buzz-multithreaded
Python using Condition and Lock
python-using-condition-and-lock-by-lacg-3cbs
The other solutions I saw used Semaphores, so I am just sharing mine that is using Lock and Condition.\nI hope it can help someone.\nThe idea behind the lock is
lacg
NORMAL
2019-10-14T15:53:20.947549+00:00
2019-10-14T17:02:01.845875+00:00
1,236
false
The other solutions I saw used Semaphores, so I am just sharing mine that is using Lock and Condition.\nI hope it can help someone.\nThe idea behind the lock is to avoid the other threads look at the counter while one of the process updates its value.\nAlso, if one thread have the right condition, all the other threads wait until the right condition thread updates the count and notify all to wake the sleeping threads.\n\n```\nfrom threading import Condition, Lock\n\n\nclass FizzBuzz:\n\n def __init__(self, n: int):\n self.n = n\n self.count = 1\n self.condition = Condition()\n self.lock = Lock()\n\n # printFizz() outputs "fizz"\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n with self.condition:\n while self.count <= self.n:\n if not self.count % 3 and self.count % 5:\n self.lock.acquire()\n printFizz()\n self.count += 1\n self.lock.release()\n self.condition.notifyAll()\n else:\n self.condition.wait()\n\n # printBuzz() outputs "buzz"\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n with self.condition:\n while self.count <= self.n:\n if not self.count % 5 and self.count % 3:\n self.lock.acquire()\n printBuzz()\n self.count += 1\n self.lock.release()\n self.condition.notifyAll()\n else:\n self.condition.wait()\n\n # printFizzBuzz() outputs "fizzbuzz"\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n with self.condition:\n while self.count <= self.n:\n if not self.count % 3 and not self.count % 5:\n self.lock.acquire()\n printFizzBuzz()\n self.count += 1\n self.lock.release()\n self.condition.notifyAll()\n else:\n self.condition.wait()\n\n # printNumber(x) outputs "x", where x is an integer.\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n with self.condition:\n while self.count <= self.n:\n if self.count % 3 and self.count % 5:\n self.lock.acquire()\n printNumber(self.count)\n self.count += 1\n self.lock.release()\n self.condition.notifyAll()\n else:\n self.condition.wait()\n```\n\nAnd then we can improve it to:\n\n```\nfrom threading import Condition, Lock\nfrom inspect import signature\n\n\nclass FizzBuzz:\n\n def __init__(self, n: int):\n self.n = n\n self.count = 1\n self.condition = Condition()\n self.lock = Lock()\n\n def produce(self, cond, func) -> None:\n with self.condition:\n while self.count <= self.n:\n if cond(self.count):\n self.lock.acquire()\n if list(signature(func).parameters):\n func(self.count)\n else:\n func()\n self.count += 1\n self.lock.release()\n self.condition.notifyAll()\n else:\n self.condition.wait()\n\n # printFizz() outputs "fizz"\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n lFizz = lambda i: not i % 3 and i % 5\n self.produce(lFizz, printFizz)\n\n # printBuzz() outputs "buzz"\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n lBuzz = lambda i: not i % 5 and i % 3\n self.produce(lBuzz, printBuzz)\n\n # printFizzBuzz() outputs "fizzbuzz"\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n lFizzBuzz = lambda i: not i % 3 and not i % 5\n self.produce(lFizzBuzz, printFizzBuzz)\n\n # printNumber(x) outputs "x", where x is an integer.\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n lNumber = lambda i: i % 3 and i % 5\n self.produce(lNumber, printNumber)\n```
4
0
['Python', 'Python3']
2
fizz-buzz-multithreaded
Python 100% Semaphore
python-100-semaphore-by-awice-y8i1
\nfrom threading import Semaphore\n\nclass FizzBuzz(object):\n def __init__(self, n):\n self.n = n\n self.sem0 = Semaphore(1)\n self.sem
awice
NORMAL
2019-09-21T23:51:47.160892+00:00
2019-09-21T23:51:47.160946+00:00
1,185
false
```\nfrom threading import Semaphore\n\nclass FizzBuzz(object):\n def __init__(self, n):\n self.n = n\n self.sem0 = Semaphore(1)\n self.sem3 = Semaphore(0)\n self.sem5 = Semaphore(0)\n self.sem15 = Semaphore(0)\n\n def fizz(self, printFizz):\n for i in xrange(3, self.n + 1, 3):\n if i % 15:\n self.sem3.acquire()\n printFizz()\n self._release(i+1)\n \n def buzz(self, printBuzz):\n for i in xrange(5, self.n + 1, 5):\n if i % 15:\n self.sem5.acquire()\n printBuzz()\n self._release(i+1)\n \n def fizzbuzz(self, printFizzBuzz):\n for i in xrange(15, self.n + 1, 15):\n self.sem15.acquire()\n printFizzBuzz()\n self._release(i+1)\n\n def number(self, printNumber):\n for i in xrange(1, self.n + 1):\n if i % 3 and i % 5:\n self.sem0.acquire()\n printNumber(i)\n self._release(i+1)\n \n def _release(self, i):\n if i % 3 and i % 5:\n self.sem0.release()\n elif i % 5:\n self.sem3.release()\n elif i % 3:\n self.sem5.release()\n else:\n self.sem15.release()\n```
4
0
[]
0
fizz-buzz-multithreaded
very simple and easy to understand solution
very-simple-and-easy-to-understand-solut-xa3o
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Kishore_raok
NORMAL
2024-04-25T06:08:56.256227+00:00
2024-04-25T06:08:56.256255+00:00
570
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass FizzBuzz {\n private int n;\n Semaphore A,B,C,D;\n public FizzBuzz(int n) {\n this.n = n;\n A = new Semaphore(1);\n B = new Semaphore(0);\n C = new Semaphore(0);\n D = new Semaphore(0);\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n for(int i =1;i<=n;i++){\n A.acquire();\n if(i%3==0 && i%5 != 0){\n printFizz.run();\n }\n B.release();\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n for(int i =1;i<=n;i++){\n B.acquire();\n if(i%3 != 0 && i%5 == 0){\n printBuzz.run();\n }\n C.release();\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n for(int i =1;i<=n;i++){\n C.acquire();\n if(i%3==0 && i%5 == 0){\n printFizzBuzz.run();\n }\n D.release();\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n for(int i =1;i<=n;i++){\n D.acquire();\n if(i%3 !=0 && i%5 != 0){\n printNumber.accept(i);\n }\n A.release();\n }\n }\n}\n\n\n\n\n \n```
3
0
['Java']
2
fizz-buzz-multithreaded
Optimized Lock-Free C++ Solution with atomics
optimized-lock-free-c-solution-with-atom-9gkz
Approach\n- Using cache-line-sized alignment for atomics\n- Using weak memory ordering where possible\n- Using yield() instead of waiting\n\n# Code\n\nclass Fiz
nikmy
NORMAL
2023-02-21T12:25:33.066340+00:00
2023-02-21T12:27:00.066462+00:00
747
false
# Approach\n- Using cache-line-sized alignment for atomics\n- Using weak memory ordering where possible\n- Using `yield()` instead of waiting\n\n# Code\n```\nclass FizzBuzz {\nprivate:\n int n;\n atomic_int i{1};\n\n alignas(64) atomic_bool n_turn {true} ;\n alignas(64) atomic_bool f_turn {false};\n alignas(64) atomic_bool b_turn {false};\n alignas(64) atomic_bool fb_turn {false};\n\npublic:\n FizzBuzz(int n) {\n this->n = n;\n }\n\n // printFizz() outputs "fizz".\n void fizz(function<void()> printFizz) {\n while (i.load() <= n) {\n while (!f_turn.exchange(false, memory_order_relaxed)) {\n if (i.load(memory_order_relaxed) > n) {\n return;\n }\n std::this_thread::yield();\n }\n printFizz();\n step();\n }\n }\n\n // printBuzz() outputs "buzz".\n void buzz(function<void()> printBuzz) {\n while (i.load() <= n) {\n while (!b_turn.exchange(false, memory_order_relaxed)) {\n if (i.load(memory_order_relaxed) > n) {\n return;\n }\n std::this_thread::yield();\n }\n printBuzz();\n step();\n }\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n\tvoid fizzbuzz(function<void()> printFizzBuzz) {\n while (i.load() <= n) {\n while (!fb_turn.exchange(false, memory_order_relaxed)) {\n if (i.load(memory_order_relaxed) > n) {\n return;\n }\n std::this_thread::yield();\n }\n printFizzBuzz();\n step();\n }\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n void number(function<void(int)> printNumber) {\n while (i.load() <= n) {\n while (!n_turn.exchange(false, memory_order_relaxed)) {\n if (i.load(memory_order_relaxed) > n) {\n return;\n }\n std::this_thread::yield();\n }\n printNumber(i.load(memory_order_relaxed));\n step();\n }\n }\n\nprivate:\n void step() {\n int c = i.fetch_add(1) + 1;\n if (c > n) {\n return;\n }\n bool f = (c % 3 == 0);\n bool b = (c % 5 == 0);\n if (f && b) {\n fb_turn.store(true);\n return;\n }\n if (f) {\n f_turn.store(true);\n return;\n }\n if (b) {\n b_turn.store(true);\n return;\n }\n n_turn.store(true);\n }\n};\n```
3
0
['Concurrency', 'C++']
3
fizz-buzz-multithreaded
C++ using semaphores
c-using-semaphores-by-anshu2-jh4v
\n# Code\n\n#include <semaphore.h>\n\nclass FizzBuzz {\nprivate:\n int n;\n sem_t sem_f, sem_b, sem_fb, sem_i;\n int f_cnt = 0, b_cnt = 0, fb_cnt = 0,
anshu2
NORMAL
2022-11-17T02:58:01.135086+00:00
2022-11-17T02:58:01.135130+00:00
256
false
\n# Code\n```\n#include <semaphore.h>\n\nclass FizzBuzz {\nprivate:\n int n;\n sem_t sem_f, sem_b, sem_fb, sem_i;\n int f_cnt = 0, b_cnt = 0, fb_cnt = 0, i_cnt = 0;\n int i = 1;\n\npublic:\n FizzBuzz(int n) {\n this->n = n;\n\n sem_init(&sem_f, 0, 0);\n sem_init(&sem_b, 0, 0);\n sem_init(&sem_fb, 0, 0);\n sem_init(&sem_i, 0, 1);\n\n for (int i = 1; i <= n; ++i) {\n if (i % 3 == 0 && i % 5 == 0) ++fb_cnt;\n else if (i % 3 == 0 && i % 5 != 0) ++f_cnt;\n else if (i % 3 != 0 && i % 5 == 0) ++b_cnt;\n else ++i_cnt;\n }\n }\n\n // printFizz() outputs "fizz".\n void fizz(function<void()> printFizz) {\n while(f_cnt > 0) {\n sem_wait(&sem_f);\n printFizz();\n ++i;\n postSem();\n --f_cnt;\n }\n }\n\n // printBuzz() outputs "buzz".\n void buzz(function<void()> printBuzz) {\n while(b_cnt > 0) {\n sem_wait(&sem_b);\n printBuzz();\n ++i;\n postSem();\n --b_cnt;\n }\n }\n\n void postSem() {\n if (i % 3 == 0 && i % 5 == 0) sem_post(&sem_fb);\n else if (i % 3 == 0 && i % 5 != 0) sem_post(&sem_f);\n else if (i % 3 != 0 && i % 5 == 0) sem_post(&sem_b);\n else sem_post(&sem_i);\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n\tvoid fizzbuzz(function<void()> printFizzBuzz) {\n while(fb_cnt > 0) {\n sem_wait(&sem_fb);\n printFizzBuzz();\n ++i;\n postSem();\n --fb_cnt;\n }\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n void number(function<void(int)> printNumber) {\n while(i_cnt > 0) {\n sem_wait(&sem_i);\n printNumber(i);\n ++i;\n postSem();\n --i_cnt;\n }\n }\n};\n```
3
0
['C++']
0
fizz-buzz-multithreaded
_Fizz Buzz Multithreaded Java - no using any classes java.util.concurrent.*
fizz-buzz-multithreaded-java-no-using-an-sqx9
I don\'t get what knowledge "1195. Fizz Buzz Multithreaded problem tries to check.\nHow don\'t write multithreaded or concurrent programs on Java?\n\nRuntime: 8
zazzazzza
NORMAL
2022-08-01T11:46:56.178295+00:00
2022-08-01T11:46:56.178337+00:00
734
false
I don\'t get what knowledge "[1195. Fizz Buzz Multithreaded](https://leetcode.com/problems/fizz-buzz-multithreaded) problem tries to check.\nHow don\'t write multithreaded or concurrent programs on Java?\n\nRuntime: 8 ms, faster than 81.09% of Java online submissions for Fizz Buzz Multithreaded.\nMemory Usage: 41.5 MB, less than 99.03% of Java online submissions for Fizz Buzz Multithreaded.\n```\nclass FizzBuzz { \n private volatile int cursor = 1;\n private int n;\n\n public FizzBuzz(int n) {\n this.n = n;\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n while (cursor <= n) {\n synchronized (this) {\n if (cursor % 15 != 0 && cursor % 3 == 0 && cursor <= n) {\n printFizz.run();\n cursor++;\n }\n }\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n while (cursor <= n) {\n synchronized (this) {\n if (cursor % 15 != 0 && cursor % 5 == 0 && cursor <= n) {\n printBuzz.run();\n cursor++;\n }\n }\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n while (cursor <= n) {\n synchronized (this) {\n if (cursor % 15 == 0 && cursor <= n) {\n printFizzBuzz.run();\n cursor++;\n }\n }\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n while (cursor <= n) {\n synchronized (this) {\n if (cursor % 5 != 0 && cursor % 3 != 0 && cursor <= n) {\n printNumber.accept(cursor);\n cursor++;\n }\n }\n }\n }\n}\n```
3
0
['Java']
3
fizz-buzz-multithreaded
Python3 | Very Simple solution using Barriers (only) | Beats 72%
python3-very-simple-solution-using-barri-8opp
\nfrom threading import Barrier\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.bar = Barrier(4)\n\n # printFizz() output
thunderVan
NORMAL
2022-07-23T22:43:56.260928+00:00
2022-07-23T22:44:47.062075+00:00
1,014
false
```\nfrom threading import Barrier\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.bar = Barrier(4)\n\n # printFizz() outputs "fizz"\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n \t\n for i in range(1,self.n+1):\n if i%5!=0 and i%3==0:\n printFizz()\n self.bar.wait()\n\n # printBuzz() outputs "buzz"\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n \n for i in range(1,self.n+1):\n if i%3!=0 and i %5 ==0:\n printBuzz()\n self.bar.wait()\n \t\n\n # printFizzBuzz() outputs "fizzbuzz"\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n \n for i in range(1,self.n+1):\n if i%5==0 and i%3==0:\n printFizzBuzz()\n self.bar.wait()\n\n # printNumber(x) outputs "x", where x is an integer.\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n \n for i in range(1,self.n+1):\n \n if (i % 3) !=0 and (i%5) !=0:\n printNumber(i)\n self.bar.wait()\n\n```
3
0
['Python']
1
fizz-buzz-multithreaded
Java 5ms Simple Semaphores Solution
java-5ms-simple-semaphores-solution-by-a-cr8y
Few pointers:\n1. Semphore(0) makes some threads locked initially\n2. After every fizz, buzz or fizzBuzz we would always print a number.\n\n\n\nclass FizzBuzz {
amma
NORMAL
2022-07-07T00:58:48.586659+00:00
2022-07-07T00:58:48.586718+00:00
388
false
Few pointers:\n1. Semphore(0) makes some threads locked initially\n2. After every fizz, buzz or fizzBuzz we would always print a number.\n\n\n```\nclass FizzBuzz {\n private int n;\n\n private Semaphore number, fizz , buzz, fizzBuzz;\n \n public FizzBuzz(int n) {\n this.n = n;\n\t\tnumber = new Semaphore(1);\n fizz = new Semaphore(0);\n\t\tbuzz = new Semaphore(0);\n\t\tfizzBuzz = new Semaphore(0);\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n for(int i = 3; i<= n; i+=3){\n if (i%5 != 0)\n {\n fizz.acquire();\n printFizz.run();\n number.release();\n }\n }\n \n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n for(int i = 5; i<= n; i+=5){\n if (i%3 != 0)\n {\n buzz.acquire();\n printBuzz.run();\n number.release();\n }\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n for(int i = 15; i<= n; i+=15){\n \n fizzBuzz.acquire();\n printFizzBuzz.run();\n number.release();\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n for(int i=1; i<=n ;i++){\n number.acquire();\n if (i%15 == 0)\n fizzBuzz.release();\n else if ( i % 5 == 0)\n buzz.release();\n else if (i %3 == 0 )\n fizz.release();\n else\n {\n printNumber.accept(i);\n number.release();\n }\n }\n }\n}\n```
3
0
['Java']
0
fizz-buzz-multithreaded
Java solution, 99% faster using Lock, includes test code
java-solution-99-faster-using-lock-inclu-6uqi
Java solution, faster than 99% Java submisions, also includes the code that I used for tests below.\n\n\nclass FizzBuzz {\n private final int n;\n private
stefancomanita
NORMAL
2022-03-10T21:45:35.222366+00:00
2022-03-10T21:45:35.222396+00:00
1,514
false
Java solution, faster than 99% Java submisions, also includes the code that I used for tests below.\n\n```\nclass FizzBuzz {\n private final int n;\n private int currentValue = 1;\n private final java.util.concurrent.locks.Lock lock = new java.util.concurrent.locks.ReentrantLock();\n\n public FizzBuzz(int n) {\n this.n = n;\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n\n while(currentValue <= n) {\n\n lock.lock();\n try {\n if (currentValue <= n && (currentValue % 3 == 0 && currentValue % 5 != 0)) {\n\n printFizz.run();\n currentValue++;\n }\n } finally {\n lock.unlock();\n }\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n while(currentValue <= n) {\n\n lock.lock();\n try {\n if (currentValue <= n && (currentValue % 3 != 0 && currentValue % 5 == 0)) {\n\n printBuzz.run();\n currentValue++;\n }\n } finally {\n lock.unlock();\n }\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n while(currentValue <= n) {\n\n lock.lock();\n try {\n if (currentValue <= n && (currentValue % 3 == 0 && currentValue % 5 == 0)) {\n\n printFizzBuzz.run();\n currentValue++;\n }\n } finally {\n lock.unlock();\n }\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(java.util.function.IntConsumer printNumber) throws InterruptedException {\n\n while(currentValue <= n) {\n\n lock.lock();\n try {\n if (currentValue <= n && (currentValue % 3 != 0 && currentValue % 5 != 0)) {\n\n printNumber.accept(currentValue);\n currentValue++;\n }\n } finally {\n lock.unlock();\n }\n }\n\n }\n}\n```\n\nCode that I used for testing/debuging\n\n```\n private static void testFizzBuzz() {\n\n\n FizzBuzz fizzBuzz = new FizzBuzz(15);\n\n Runnable fizz = () -> System.out.print("fizz");\n Runnable buzz = () -> System.out.print("buzz");\n Runnable fBuzz = () -> System.out.print("fizzbuzz");\n\n IntConsumer number = System.out::print;\n\n\n new Thread(() -> {\n\n try {\n fizzBuzz.fizz(fizz);\n } catch (InterruptedException e) {\n\n e.printStackTrace();\n\n throw new RuntimeException(e);\n }\n }).start();\n\n new Thread(() -> {\n\n try {\n fizzBuzz.buzz(buzz);\n } catch (InterruptedException e) {\n\n e.printStackTrace();\n\n throw new RuntimeException(e);\n }\n }).start();\n\n new Thread(() -> {\n\n try {\n fizzBuzz.fizzbuzz(fBuzz);\n } catch (InterruptedException e) {\n\n e.printStackTrace();\n\n throw new RuntimeException(e);\n }\n }).start();\n\n new Thread(() -> {\n\n try {\n fizzBuzz.number(number);\n } catch (InterruptedException e) {\n\n e.printStackTrace();\n\n throw new RuntimeException(e);\n }\n }).start();\n }\n```
3
0
['Java']
2
fizz-buzz-multithreaded
Java using ReentrantLock and Condition
java-using-reentrantlock-and-condition-b-2qje
This is the essentially the same idea taken from Java, using synchronized with short explanation.. Thanks @Hai_dee for the great explanation there.\n\nJava\ncla
cielong
NORMAL
2022-01-17T03:02:27.252012+00:00
2022-01-17T03:02:27.252055+00:00
613
false
This is the essentially the same idea taken from [Java, using synchronized with short explanation.](https://leetcode.com/problems/fizz-buzz-multithreaded/discuss/385395/Java-using-synchronized-with-short-explanation.). Thanks [@Hai_dee](https://leetcode.com/Hai_dee/) for the great explanation there.\n\n```Java\nclass FizzBuzz { \n private final Lock lock = new ReentrantLock();\n private final Condition nextNumber = lock.newCondition();\n \n private final int n;\n private int currentIndex;\n\n public FizzBuzz(int n) {\n this.n = n;\n this.currentIndex = 1;\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n while (currentIndex <= n) {\n lock.lock();\n try {\n if (currentIndex % 3 != 0 || currentIndex % 5 == 0) {\n nextNumber.await();\n continue;\n }\n\n //System.out.println("fizz " + currentIndex);\n\n printFizz.run();\n currentIndex++;\n\t\t\t\t\n\t\t\t\t// the reason we use signalAll instead of signal because signal may awake the wrong thread\n\t\t\t\t// and incur signal miss\n nextNumber.signalAll();\n } finally {\n lock.unlock();\n }\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n while (currentIndex <= n) {\n lock.lock();\n try {\n if (currentIndex % 5 != 0 || currentIndex % 3 == 0) {\n nextNumber.await();\n continue;\n }\n\n //System.out.println("buzz " + currentIndex);\n\n printBuzz.run();\n currentIndex++;\n nextNumber.signalAll();\n } finally {\n lock.unlock();\n }\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n while (currentIndex <= n) {\n lock.lock();\n \n try {\n if (currentIndex % 15 != 0) {\n nextNumber.await();\n continue;\n }\n //System.out.println("fizzbuzz " + currentIndex);\n\n printFizzBuzz.run();\n currentIndex++;\n nextNumber.signalAll();\n } finally {\n lock.unlock();\n }\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n while (currentIndex <= n) {\n lock.lock();\n try {\n if (currentIndex % 3 == 0 || currentIndex % 5 == 0) {\n nextNumber.await();\n continue; \n }\n //System.out.println("number " + currentIndex);\n\n printNumber.accept(currentIndex++);\n nextNumber.signalAll();\n } finally {\n lock.unlock();\n }\n }\n } \n}\n```
3
0
['Java']
1
fizz-buzz-multithreaded
Java 's semaphore solution's explaination for most multithread problem
java-s-semaphore-solutions-explaination-m0dpd
Overall, a semaphore is a kind of token counter controlled by us (developer). \n\nEach time, when a thread runs acquire() method, it acuqires , and then, immed
laodasb
NORMAL
2020-12-01T10:59:29.060922+00:00
2020-12-22T23:31:59.252272+00:00
349
false
Overall, a semaphore is a kind of token counter controlled by us (developer). \n\nEach time, when a thread runs acquire() method, it acuqires , and then, **immediately consumes** that permit token, which allows the thread to run but also decrease its permit token by one.\n\nBy contrast, if a thread calls its release() method,it will release a permit token, and then can be acquired by others later.\n\nIn conclusion, acquire() makes a decrement of token held by us (developer) and release() makes an increment, once a thread acquire, it can run.\n\nHope it can help.\n```\nimport java.util.concurrent.Semaphore;\nclass FizzBuzz {\n private int n;\n private Semaphore s1,s3,s5,s15;\n public FizzBuzz(int n) {\n this.n = n;\n s1=new Semaphore(1);\n s3=new Semaphore(0);\n s5=new Semaphore(0);\n s15=new Semaphore(0);\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n for(int i=3;i<=n;i+=3){\n if(i%5==0) continue;\n s3.acquire();\n printFizz.run();\n s1.release();\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n for(int i=5;i<=n;i+=5){\n if(i%3==0) continue;\n s5.acquire();\n printBuzz.run();\n s1.release();\n } \n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n for(int i=15;i<=n;i+=15){\n s15.acquire();\n printFizzBuzz.run();\n s1.release();\n } \n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n for(int i=1;i<=n;i+=1){\n s1.acquire();\n if(i%15==0){\n s15.release();\n }else if(i%5==0){\n s5.release();\n }else if(i%3==0){\n s3.release();\n }else{\n printNumber.accept(i);\n s1.release();\n }\n } \n }\n}\n```
3
0
[]
0
fizz-buzz-multithreaded
Python Solution with Condition Variable
python-solution-with-condition-variable-ap2g1
The idea is that each of 4 threads tries to print numbers that it\'s responsible for. fizz prints numbers divisible only by 3, buzz prints numbers divisible onl
saulpayne
NORMAL
2020-05-19T20:57:54.005684+00:00
2020-05-19T20:57:54.005736+00:00
422
false
The idea is that each of 4 threads tries to print numbers that it\'s responsible for. ```fizz``` prints numbers divisible only by 3, ```buzz``` prints numbers divisible only by 5, ```fizzbuzz``` prints numbers divisible by 15, and ```number``` prints remaining numbers. But we have to handle order of prints.\n\n```\nfrom threading import Condition\n\n\nclass FizzBuzz:\n def __init__(self, n: int):\n self.cv = Condition() # condition variable\n self.n = n #\n self.k = 1 # current number\n\n \n # printFizz() outputs "fizz"\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n i = 3\n while i <= self.n: # iterate over multiples of 3\n with self.cv:\n self.cv.wait_for(lambda: self.k == i) # check if it\'s fizz\'s turn to print\n printFizz()\n self.k += 1\n self.cv.notify_all() # notify other threads that self.k has been changed and they can check their conditions (other threads are blocked in their wait_for statements)\n i += 3\n if i % 5 == 0: # skip, because \'i\' is divisible by 15 and it should be handled by \'fizzbuzz\'\n i += 3\n \n\n # printBuzz() outputs "buzz"\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n i = 5\n while i <= self.n: # iterate over multiples of 5\n with self.cv:\n self.cv.wait_for(lambda: self.k == i) # check if it\'s buzz\'s turn to print\n printBuzz()\n self.k += 1\n self.cv.notify_all() # notify other threads that self.k has been changed and they can check their conditions (other threads are blocked in their wait_for statements)\n i += 5\n if i % 3 == 0: # skip, because \'i\' is divisible by 15 and it should be handled by \'fizzbuzz\'\n i += 5\n \t\n\n # printFizzBuzz() outputs "fizzbuzz"\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n for i in range(15, self.n + 1, 15): # iterate over multiples of 15\n with self.cv:\n self.cv.wait_for(lambda: self.k == i) # check if it\'s fizzbuzz\'s turn to print\n printFizzBuzz()\n self.k += 1\n self.cv.notify_all() # notify other threads that self.k has been changed and they can check their conditions (other threads are blocked in their wait_for statements)\n\n \n # printNumber(x) outputs "x", where x is an integer.\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n i = 1\n while i <= self.n:\n if i % 3 and i % 5: # consider only numbers that are not divisible by 3 and 5\n with self.cv:\n self.cv.wait_for(lambda: self.k == i) # check if it\'s number\'s turn to print\n printNumber(self.k)\n self.k += 1\n self.cv.notify_all() # notify other threads that self.k has been changed and they can check their conditions (other threads are blocked in their wait_for statements)\n i += 1\n \n\t\t\t\n```\n\nNumbers printed by 4 threads are mutually exclusive; therefore, we can be sure that at each change of ```k``` only one ```print``` is called. Also, union of numbers of each thread gives all numbers in the range ```[1, n]```, so we can be sure that deadlock won\'t occur.\n
3
0
[]
1
fizz-buzz-multithreaded
c# faster than 94% (44ms) using AutoResetEvent
c-faster-than-94-44ms-using-autoreseteve-9c5t
csharp\npublic class FizzBuzz\n\t{\n private readonly AutoResetEvent fizz = new AutoResetEvent(false);\n\t\tprivate readonly AutoResetEvent buzz = new Au
giometrix
NORMAL
2020-04-24T17:07:13.092460+00:00
2020-04-24T17:07:13.092513+00:00
404
false
```csharp\npublic class FizzBuzz\n\t{\n private readonly AutoResetEvent fizz = new AutoResetEvent(false);\n\t\tprivate readonly AutoResetEvent buzz = new AutoResetEvent(false);\n\t\tprivate readonly AutoResetEvent buzzComplete = new AutoResetEvent(false);\n\t\tprivate readonly AutoResetEvent fizzbuzz = new AutoResetEvent(false);\n\t\tprivate readonly AutoResetEvent fizzBuzzComplete = new AutoResetEvent(false);\n\t\tprivate readonly AutoResetEvent fizzComplete = new AutoResetEvent(false);\n\t\t\n private readonly int n;\n private int curr = 1;\n\n\t\tpublic FizzBuzz(int n)\n\t\t{\n\t\t\tthis.n = n;\n\t\t}\n\n\t\t// printFizz() outputs "fizz".\n\t\tpublic void Fizz(Action printFizz)\n\t\t{\n\t\t\twhile (fizz.WaitOne() && curr <= n)\n\t\t\t{\n\t\t\t\t//fizz.WaitOne();\n\t\t\t\tprintFizz();\n\t\t\t\tfizzComplete.Set();\n\t\t\t}\n\t\t}\n\n\t\t// printBuzzz() outputs "buzz".\n\t\tpublic void Buzz(Action printBuzz)\n\t\t{\n\t\t\twhile (buzz.WaitOne() && curr <= n)\n\t\t\t{\n\t\t\t\tprintBuzz();\n\t\t\t\tbuzzComplete.Set();\n\t\t\t}\n\t\t}\n\n\t\t// printFizzBuzz() outputs "fizzbuzz".\n\t\tpublic void Fizzbuzz(Action printFizzBuzz)\n\t\t{\n\t\t\twhile (fizzbuzz.WaitOne() && curr <= n)\n\t\t\t{\n\t\t\t\tprintFizzBuzz();\n\t\t\t\tfizzBuzzComplete.Set();\n\t\t\t}\n\t\t}\n\n\t\t// printNumber(x) outputs "x", where x is an integer.\n\t\tpublic void Number(Action<int> printNumber)\n\t\t{\n\t\t\tfor (; curr <= n; curr++)\n\t\t\t\tif (curr % 3 == 0 && curr % 5 == 0)\n\t\t\t\t{\n\t\t\t\t\tfizzbuzz.Set();\n\t\t\t\t\tfizzBuzzComplete.WaitOne();\n\t\t\t\t}\n\t\t\t\telse if (curr % 3 == 0 && curr % 5 > 0)\n\t\t\t\t{\n\t\t\t\t\tfizz.Set();\n\t\t\t\t\tfizzComplete.WaitOne();\n\t\t\t\t}\n\t\t\t\telse if (curr % 3 > 0 && curr % 5 == 0)\n\t\t\t\t{\n\t\t\t\t\tbuzz.Set();\n\t\t\t\t\tbuzzComplete.WaitOne();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tprintNumber(curr);\n\t\t\t\t}\n\n\t\t\tfizz.Set();\n\t\t\tbuzz.Set();\n\t\t\tfizzbuzz.Set();\n\t\t}\n\t}\n\t\n\t```
3
0
[]
0
fizz-buzz-multithreaded
Python3 using Lock, 96%
python3-using-lock-96-by-nightybear-l8u0
Attached is the solution using Lock, welcome to discuss.\n\npython\n\nfrom threading import Lock\n\nclass FizzBuzz:\n def __init__(self, n: int):\n se
nightybear
NORMAL
2019-11-13T01:31:04.023876+00:00
2019-11-13T01:31:04.023954+00:00
922
false
Attached is the solution using Lock, welcome to discuss.\n\n```python\n\nfrom threading import Lock\n\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.l1 = [Lock() for _ in range(3)]\n self.l2 = [Lock() for _ in range(3)]\n \n # lock all the locks\n for i in range(3):\n self.l1[i].acquire()\n self.l2[i].acquire()\n \n # printFizz() outputs "fizz"\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n \tfor val in range(1, self.n+1):\n if val % 3 == 0 and val % 5:\n self.l1[0].acquire()\n printFizz()\n self.l2[0].release()\n \n # printBuzz() outputs "buzz"\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n \tfor val in range(1, self.n+1):\n if val % 5 == 0 and val % 3:\n self.l1[1].acquire()\n printBuzz()\n self.l2[1].release()\n\n # printFizzBuzz() outputs "fizzbuzz"\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n \tfor val in range(1, self.n+1):\n if val % 3 == 0 and val % 5 == 0:\n self.l1[2].acquire()\n printFizzBuzz()\n self.l2[2].release()\n\n # printNumber(x) outputs "x", where x is an integer.\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n \tfor val in range(1, self.n+1):\n if val % 3 and val % 5:\n printNumber(val)\n elif val % 3 == 0 and val % 5:\n # fizz\n self.l1[0].release()\n self.l2[0].acquire()\n \n elif val % 5 == 0 and val % 3:\n # Buzz\n self.l1[1].release()\n self.l2[1].acquire()\n else:\n # FizzBuzz\n self.l1[2].release()\n self.l2[2].acquire()\n\n```
3
1
['Python3']
0
fizz-buzz-multithreaded
unique_lock and condition variable C++
unique_lock-and-condition-variable-c-by-dikad
class FizzBuzz {\nprivate:\n int n;\n mutex mtx;\n condition_variable cv;\n int tmp; bool a;\n \npublic:\n FizzBuzz(int n) {\n this->n
_CodeSlayer_
NORMAL
2019-10-28T05:03:18.992992+00:00
2019-10-28T05:03:18.993038+00:00
594
false
class FizzBuzz {\nprivate:\n int n;\n mutex mtx;\n condition_variable cv;\n int tmp; bool a;\n \npublic:\n FizzBuzz(int n) {\n this->n = n; this->tmp=1;//this->tmp2=0;\n }\n\n // printFizz() outputs "fizz".\n void fizz(function<void()> printFizz) {\n while(tmp<=n) {\n { \n // a = ; //cout<<a ;\n unique_lock<mutex> lk(mtx);\n cv.wait(lk, [this]() {return (((tmp%5)!=0)&&(((tmp%3)==0))); }); cout<<"fizz";\n printFizz() ;\n tmp++; \n }\n cv.notify_all();\n }\n }\n\n // printBuzz() outputs "buzz".\n void buzz(function<void()> printBuzz) {\n while(tmp<=n) {\n {\n unique_lock<mutex> lk(mtx);\n cv.wait(lk, [this]() { return ((tmp%3)!=0)&&(((tmp%5)==0)) ; });\n cout<<"buzz" ;\n printBuzz() ;\n tmp++; \n }\n cv.notify_all();\n }\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n\tvoid fizzbuzz(function<void()> printFizzBuzz) {\n while(tmp<=n) {\n {\n unique_lock<mutex> lk(mtx);\n cv.wait(lk, [this]() { return (((tmp%5)==0)&&(((tmp%3)==0))); }); cout<<"fizz-Buzz";\n printFizzBuzz() ; //printFizz() ;\n tmp++; \n }\n cv.notify_all();\n }\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n void number(function<void(int)> printNumber) {\n while(tmp<=n) {\n {\n unique_lock<mutex> lk(mtx);\n cv.wait(lk, [this]() { return (((tmp%5)!=0)&&(((tmp%3)!=0))); }); cout<<tmp;\n printNumber(tmp) ;\n tmp++; \n }\n cv.notify_all();\n }\n }\n};\n\n\nSomeone please help me out with the bug :(
3
0
['C']
1
fizz-buzz-multithreaded
Intuitive Java Solution With Explanation
intuitive-java-solution-with-explanation-u1uw
Idea\nUse Guarded Blocks and the logic is similar to producer-consumer problem from\nhttps://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.htm
naveen_kothamasu
NORMAL
2019-10-06T01:11:48.496803+00:00
2019-10-06T01:11:48.496855+00:00
481
false
**Idea**\nUse `Guarded Blocks` and the logic is similar to producer-consumer problem from\nhttps://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html\n\n```\nclass FizzBuzz {\n private int n;\n private int counter = 1;\n public FizzBuzz(int n) {\n this.n = n;\n }\n\n // printFizz.run() outputs "fizz".\n public synchronized void fizz(Runnable printFizz) throws InterruptedException {\n while(true){\n while(counter <= n && (counter % 3 != 0 || counter % 5 == 0)){\n wait();\n }\n if(counter > n) break;\n printFizz.run();\n ++counter;\n notifyAll();\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public synchronized void buzz(Runnable printBuzz) throws InterruptedException {\n while(true){\n while(counter <= n && (counter % 5 != 0 || counter % 3 == 0)){\n wait();\n }\n if(counter > n) break;\n printBuzz.run();\n ++counter;\n notifyAll();\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public synchronized void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n while(true){\n while(counter <= n && !(counter % 3 == 0 && counter % 5 == 0)){\n wait();\n }\n if(counter > n) break;\n printFizzBuzz.run();\n ++counter;\n notifyAll();\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public synchronized void number(IntConsumer printNumber) throws InterruptedException {\n while(true){\n while(counter <= n && (counter % 3 == 0 || counter % 5 == 0)){\n wait();\n }\n if(counter > n) break;\n printNumber.accept(counter);\n ++counter;\n notifyAll();\n }\n }\n}\n```
3
0
[]
1
fizz-buzz-multithreaded
C# 52 ms, barrier
c-52-ms-barrier-by-csuporj-fwbn
\tpublic class FizzBuzz\n {\n private int n;\n private int i;\n private System.Threading.Barrier barrier;\n\n public FizzBuzz(int
csuporj
NORMAL
2019-09-22T00:11:50.675205+00:00
2019-09-22T00:16:10.833396+00:00
473
false
\tpublic class FizzBuzz\n {\n private int n;\n private int i;\n private System.Threading.Barrier barrier;\n\n public FizzBuzz(int n)\n {\n this.n = n;\n barrier = new System.Threading.Barrier(4);\n }\n\n // printFizz() outputs "fizz".\n public void Fizz(Action printFizz)\n {\n while (true)\n {\n barrier.SignalAndWait();\n if (i > n)\n {\n break;\n }\n if (i % 3 == 0 && i % 5 != 0)\n {\n printFizz();\n }\n barrier.SignalAndWait();\n }\n }\n\n // printBuzzz() outputs "buzz".\n public void Buzz(Action printBuzz)\n {\n while (true)\n {\n barrier.SignalAndWait();\n if (i > n)\n {\n break;\n }\n if (i % 5 == 0 && i % 3 != 0)\n {\n printBuzz();\n }\n barrier.SignalAndWait();\n }\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n public void Fizzbuzz(Action printFizzBuzz)\n {\n while (true)\n {\n barrier.SignalAndWait();\n if (i > n)\n {\n break;\n }\n if (i % 15 == 0)\n {\n printFizzBuzz();\n }\n barrier.SignalAndWait();\n }\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n public void Number(Action<int> printNumber)\n {\n while (true)\n {\n i++;\n barrier.SignalAndWait();\n if (i > n)\n {\n break;\n }\n if (i % 3 != 0 && i % 5 != 0)\n {\n printNumber(i);\n }\n barrier.SignalAndWait();\n }\n }\n }\n
3
0
[]
2
fizz-buzz-multithreaded
Simple std::barrier solution
simple-stdbarrier-solution-by-user4153oo-t7gv
\n# Code\ncpp []\n#include <barrier>\n\nclass FizzBuzz {\nprivate:\n int n;\n std::barrier<> sync_point{ 4 };\npublic:\n FizzBuzz(int n) {\n thi
user4153oO
NORMAL
2024-10-15T19:12:28.058985+00:00
2024-10-15T19:12:28.059009+00:00
225
false
\n# Code\n```cpp []\n#include <barrier>\n\nclass FizzBuzz {\nprivate:\n int n;\n std::barrier<> sync_point{ 4 };\npublic:\n FizzBuzz(int n) {\n this->n = n;\n }\n\n // printFizz() outputs "fizz".\n void fizz(function<void()> printFizz) {\n for (unsigned i = 1; i <= n; ++i)\n {\n if ((i % 3 == 0) && (i % 5 != 0)) {\n printFizz();\n }\n sync_point.arrive_and_wait();\n }\n }\n\n // printBuzz() outputs "buzz".\n void buzz(function<void()> printBuzz) {\n for (unsigned i = 1; i <= n; ++i)\n {\n if ((i % 3 != 0) && (i % 5 == 0)) {\n printBuzz();\n }\n sync_point.arrive_and_wait();\n }\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n\tvoid fizzbuzz(function<void()> printFizzBuzz) {\n for (unsigned i = 1; i <= n; ++i)\n {\n if ((i % 3 == 0) && (i % 5 == 0)) {\n printFizzBuzz();\n }\n sync_point.arrive_and_wait();\n }\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n void number(function<void(int)> printNumber) {\n for (unsigned i = 1; i <= n; ++i)\n {\n if ((i % 3 != 0) && (i % 5 != 0)) {\n printNumber(i);\n }\n sync_point.arrive_and_wait();\n }\n }\n};\n```
2
0
['C++']
1
fizz-buzz-multithreaded
Java - Sync-step with Phaser
java-sync-step-with-phaser-by-give_me_th-o6mv
Intuition\nThe result for a given number n is deterministic, and only 1 of the operations will produce output. The shared resource is essentially the iteration
give_me_the_formuoli
NORMAL
2024-05-02T17:00:45.195422+00:00
2024-05-02T17:00:45.195444+00:00
396
false
# Intuition\nThe result for a given number `n` is deterministic, and only 1 of the operations will produce output. The shared resource is essentially the iteration order, so we produce synchronization around that. Additionally, there is only a single result for each value `n`, so each call/thread can independently determine if it should call it\'s input function. Using a barrier allows the threads to be parked allowing for other work to be scheduled on them.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Each thread independently determines if it should call it\'s `Runnable`/`IntConsumer`. If it is supposed to call it, it calls it. We are guaranteed exactly 1 call per "round"\n- Each thread parks at the `Phaser`, awaiting for the others\n- Only when all threads arrive to the `Phaser`, do they sync-step and advance to the next number.\n\n# Complexity\n- Time complexity: $O(n)$ - each function iterates $n$ times\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(1)$ - a single, shared `Phaser` instance\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass FizzBuzz {\n private final int n;\n private final Phaser phaser = new Phaser(4);\n\n public FizzBuzz(int n) {\n this.n = n;\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n for (int i = 1; i <= n; i++) {\n var shouldPrint = i % 3 == 0 && i % 5 != 0;\n if (shouldPrint) printFizz.run();\n phaser.arriveAndAwaitAdvance();\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n for (int i = 1; i <= n; i++) {\n var shouldPrint = i % 5 == 0 && i % 3 != 0;\n if (shouldPrint) printBuzz.run();\n phaser.arriveAndAwaitAdvance();\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n for (int i = 1; i <= n; i++) {\n var shouldPrint = i % 5 == 0 && i % 3 == 0;\n if (shouldPrint) printFizzBuzz.run();\n phaser.arriveAndAwaitAdvance();\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n for (int i = 1; i <= n; i++) {\n var shouldPrint = i % 3 != 0 && i % 5 != 0;\n if (shouldPrint) printNumber.accept(i);\n phaser.arriveAndAwaitAdvance();\n }\n }\n}\n```
2
0
['Java']
0
fizz-buzz-multithreaded
Best Java Solution || Beats 100%
best-java-solution-beats-100-by-ravikuma-5idz
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
ravikumar50
NORMAL
2023-09-28T09:30:24.215074+00:00
2023-09-28T09:30:24.215095+00:00
1,308
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass FizzBuzz {\n // taken help\n \n private int n;\n private int i;\n\n public FizzBuzz(int n) {\n this.n = n;\n this.i = 1;\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n synchronized (this) {\n while (i<=n) {\n if (i%3==0 && i%5!=0) {\n printFizz.run();\n i+=1;\n notifyAll(); \n } else {\n wait();\n }\n }\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n synchronized (this) {\n while (i<=n) {\n if (i%3!=0 && i%5==0) {\n printBuzz.run();\n i+=1;\n notifyAll(); \n } else {\n wait();\n }\n }\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n synchronized (this) {\n while (i<=n) {\n if (i%15==0) {\n printFizzBuzz.run();\n i+=1;\n notifyAll(); \n } else {\n wait();\n }\n }\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n synchronized (this) {\n while (i<=n) {\n if (i%3!=0 && i%5!=0) {\n printNumber.accept(i);\n i+=1;\n notifyAll(); \n } else {\n wait();\n }\n }\n }\n }\n}\n```
2
0
['Java']
1
fizz-buzz-multithreaded
C++ EASY SOLUTION
c-easy-solution-by-arpiii_7474-gatw
Code\n\nclass FizzBuzz {\nprivate:\n int n;\n mutex m;\n condition_variable cv;\n int i;\npublic:\n FizzBuzz(int n) {\n this->n = n;\n
arpiii_7474
NORMAL
2023-09-26T05:21:46.909746+00:00
2023-09-26T05:21:46.909770+00:00
677
false
# Code\n```\nclass FizzBuzz {\nprivate:\n int n;\n mutex m;\n condition_variable cv;\n int i;\npublic:\n FizzBuzz(int n) {\n this->n = n;\n this->i=1;\n }\n\n // printFizz() outputs "fizz".\n void fizz(function<void()> printFizz) {\n while(i<=n){\n unique_lock<mutex> lock(m);\n while(i<=n && !((i%3==0) && (i%5!=0))) cv.wait(lock);\n if(i<=n){\n printFizz();\n i++;\n }\n cv.notify_all();\n }\n }\n\n // printBuzz() outputs "buzz".\n void buzz(function<void()> printBuzz) {\n while(i<=n){\n unique_lock<mutex> lock(m);\n while(i<=n && !((i%3!=0) && (i%5==0))) cv.wait(lock);\n if(i<=n){\n printBuzz();\n i++;\n }\n cv.notify_all();\n }\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n\tvoid fizzbuzz(function<void()> printFizzBuzz) {\n while(i<=n){\n unique_lock<mutex> lock(m);\n while(i<=n && !((i%3==0) && (i%5==0))) cv.wait(lock);\n if(i<=n){\n printFizzBuzz();\n i++;\n }\n cv.notify_all();\n }\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n void number(function<void(int)> printNumber) {\n while(i<=n){\n unique_lock<mutex> lock(m);\n while(i<=n && !((i%3!=0) && (i%5!=0))) cv.wait(lock);\n if(i<=n){\n printNumber(i);\n i++;\n }\n cv.notify_all();\n }\n }\n};\n```
2
0
['C++']
0
fizz-buzz-multithreaded
Trivial C++ beats 100%
trivial-c-beats-100-by-shoumikhin-khfl
\n\nclass FizzBuzz {\nprivate:\n int n;\n atomic_int i{1};\n\npublic:\n FizzBuzz(int n) {\n this->n = n;\n }\n\n // printFizz() outputs "f
shoumikhin
NORMAL
2023-02-01T03:50:27.350798+00:00
2023-02-01T03:50:27.350845+00:00
301
false
\n```\nclass FizzBuzz {\nprivate:\n int n;\n atomic_int i{1};\n\npublic:\n FizzBuzz(int n) {\n this->n = n;\n }\n\n // printFizz() outputs "fizz".\n void fizz(function<void()> printFizz) {\n for (auto ii = i.load(); ii <= n; ii = i.load()) {\n if (ii % 3 == 0 && ii % 5 != 0) {\n printFizz();\n i.store(ii + 1);\n }\n }\n }\n\n // printBuzz() outputs "buzz".\n void buzz(function<void()> printBuzz) {\n for (auto ii = i.load(); ii <= n; ii = i.load()) {\n if (ii % 5 == 0 && ii % 3 != 0) {\n printBuzz();\n i.store(ii + 1);\n }\n }\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n\tvoid fizzbuzz(function<void()> printFizzBuzz) {\n for (auto ii = i.load(); ii <= n; ii = i.load()) {\n if (ii % 3 == 0 && ii % 5 == 0) {\n printFizzBuzz();\n i.store(ii + 1);\n }\n }\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n void number(function<void(int)> printNumber) {\n for (auto ii = i.load(); ii <= n; ii = i.load()) {\n if (ii % 3 != 0 && ii % 5 != 0) {\n printNumber(ii);\n i.store(ii + 1);\n }\n }\n }\n};\n```
2
0
['C++']
1
fizz-buzz-multithreaded
Python Barrier Solution
python-barrier-solution-by-christopher71-x80v
Straight forward simple solution.\n\nAll 4 threads work on 1 iteration the loop together concurrently, then step together after all have reached.\n\n```\nfrom t
christopher71
NORMAL
2022-12-05T10:13:37.382238+00:00
2022-12-05T10:13:37.382276+00:00
355
false
Straight forward simple solution.\n\nAll 4 threads work on 1 iteration the loop together concurrently, then step together after all have reached.\n\n```\nfrom threading import Barrier\n\nbarrier = Barrier(4)\n\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n + 1\n\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n for cur in range(1, self.n):\n if cur % 3 == 0 and cur % 5 != 0:\n printFizz()\n\n barrier.wait()\n\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n for cur in range(1, self.n):\n if cur % 3 != 0 and cur % 5 == 0:\n printBuzz()\n\n barrier.wait()\n\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n for cur in range(1, self.n):\n if cur % 3 == 0 and cur % 5 == 0:\n printFizzBuzz()\n\n barrier.wait()\n\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n for cur in range(1, self.n):\n if cur % 3 != 0 and cur % 5 != 0:\n printNumber(cur)\n\n barrier.wait()
2
0
[]
1
fizz-buzz-multithreaded
C++ using mutex, condition_variable, and unique_lock with Core Guideline annotations
c-using-mutex-condition_variable-and-uni-12ka
I added notes and links to the excellent C++ Core Guidelines section on Concurrency.\n\n\nclass FizzBuzz {\npublic:\n explicit FizzBuzz(int n)\n : n(n
user6040iN
NORMAL
2022-09-08T17:31:19.513874+00:00
2022-09-08T17:31:19.513922+00:00
584
false
I added notes and links to the excellent [C++ Core Guidelines section on Concurrency](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#SScp-con).\n\n```\nclass FizzBuzz {\npublic:\n explicit FizzBuzz(int n)\n : n(n), i(1), mutex(), condition()\n {\n }\n\n // printFizz() outputs "fizz".\n void fizz(std::function<void()> printFizz)\n {\n auto predicate = [](int v) { return (v % 3 == 0) && (v % 5 != 0); };\n auto printer = [printFizz](int) { printFizz(); };\n run(printer, predicate);\n }\n\n // printBuzz() outputs "buzz".\n void buzz(std::function<void()> printBuzz)\n {\n auto predicate = [](int v) { return (v % 3 != 0) && (v % 5 == 0); };\n auto printer = [printBuzz](int) { printBuzz(); };\n run(printer, predicate);\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n void fizzbuzz(std::function<void()> printFizzBuzz)\n {\n auto predicate = [](int v) { return (v % 3 == 0) && (v % 5 == 0); };\n auto printer = [printFizzBuzz](int) { printFizzBuzz(); };\n run(printer, predicate);\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n void number(std::function<void(int)> printNumber)\n {\n auto predicate = [](int v) { return (v % 3 != 0) && (v % 5 != 0); };\n run(printNumber, predicate);\n }\n\nprivate:\n int n;\n int i;\n std::mutex mutex;\n std::condition_variable condition;\n\n // Thread function, do it once to make sure we have uniform behavior\n template <typename Printer, typename Predicate>\n void run(Printer printer, Predicate predicate)\n {\n for (;;) {\n int v = 0;\n {\n // CP.20: Use RAII, never plain lock()/unlock()\n // https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp20-use-raii-never-plain-lockunlock\n std::unique_lock<std::mutex> lock(mutex);\n\n // Wait until predicate is satisfied or we are finished\n // CP.42: Don\'t wait without a condition\n // https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp42-dont-wait-without-a-condition\n condition.wait(lock, [this, predicate]() {\n return (i > n) || predicate(i);\n });\n\n if (i > n) {\n break;\n }\n\n v = i;\n }\n\n // CP.22: Never call unknown code while holding a lock (e.g., a\n // callback)\n // https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp22-never-call-unknown-code-while-holding-a-lock-eg-a-callback\n printer(v);\n\n {\n std::unique_lock<std::mutex> lock(mutex);\n i++;\n }\n\n // We called our printer, allow the other threads to take their turn\n condition.notify_all();\n }\n }\n};\n```
2
0
['C']
0
fizz-buzz-multithreaded
Efficient Java Solution using Semaphore
efficient-java-solution-using-semaphore-98azi
\nclass FizzBuzz {\n private int n;\n private int current;\n private int fizzBuzzTotal;\n private int fizzTotal;\n private int buzzTotal;\n pr
HYRFAL
NORMAL
2022-05-07T16:41:14.780270+00:00
2022-05-07T16:41:14.780314+00:00
374
false
```\nclass FizzBuzz {\n private int n;\n private int current;\n private int fizzBuzzTotal;\n private int fizzTotal;\n private int buzzTotal;\n private int numTotal;\n private Semaphore fizzBuzzSem = new Semaphore(0);\n private Semaphore fizzSem = new Semaphore(0);\n private Semaphore buzzSem = new Semaphore(0);\n private Semaphore numSem = new Semaphore(1);\n\n\n public FizzBuzz(int n) {\n this.n = n;\n this.current = 1;\n // figure out how many total times each thing should print\n this.fizzBuzzTotal = n/15;\n this.fizzTotal = n/3 - fizzBuzzTotal;\n this.buzzTotal = n/5 - fizzBuzzTotal;\n this.numTotal = n - fizzTotal - buzzTotal - fizzBuzzTotal;\n\n }\n\n private void signalNext() {\n current++;\n if (current % 15 == 0) {\n fizzBuzzSem.release();\n } else if (current % 3 == 0) {\n fizzSem.release();\n } else if (current % 5 == 0) {\n buzzSem.release();\n } else {\n numSem.release();\n }\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n for (int i = 0; i < fizzTotal; i++) {\n fizzSem.acquire();\n printFizz.run();\n signalNext();\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n for (int i = 0; i < buzzTotal; i++) {\n buzzSem.acquire();\n printBuzz.run();\n signalNext();\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n for (int i = 0; i < fizzBuzzTotal; i++) {\n fizzBuzzSem.acquire();\n printFizzBuzz.run();\n signalNext();\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n int num = 1;\n for (int i = 0; i < numTotal; i++) {\n numSem.acquire();\n printNumber.accept(num);\n // find the next number\n num++;\n while (num % 3 == 0 || num % 5 == 0) {\n num++;\n }\n signalNext();\n }\n }\n}\n```
2
0
[]
1
fizz-buzz-multithreaded
Java 3 solutions
java-3-solutions-by-mypanacea-3u5x
Semaphors\n\n\npublic class Solution1195 {\n\n\tprivate int n;\n\n\tSemaphore fizz = new Semaphore(0);\n\n\tSemaphore buzz = new Semaphore(0);\n\n\tSemaphore fi
mypanacea
NORMAL
2022-02-15T21:26:04.423763+00:00
2022-02-15T21:27:11.120418+00:00
326
false
Semaphors\n\n```\npublic class Solution1195 {\n\n\tprivate int n;\n\n\tSemaphore fizz = new Semaphore(0);\n\n\tSemaphore buzz = new Semaphore(0);\n\n\tSemaphore fizzbuzz = new Semaphore(0);\n\n\tSemaphore number = new Semaphore(1);\n\n\tprivate int count;\n\n\tpublic Solution1195(int n) {\n\t\tthis.n = n;\n\t\tthis.count = 1;\n\t}\n\n\tpublic void fizz(Runnable printFizz) throws InterruptedException {\n\t\twhile (count <= n) {\n\t\t\tif (count % 3 == 0 && count % 5 != 0) {\n\t\t\t\tfizz.acquire();\n\t\t\t\tprintFizz.run();\n\t\t\t\tcount++;\n\t\t\t\treleaseSemaphore(count);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void buzz(Runnable printBuzz) throws InterruptedException {\n\t\twhile (count <= n) {\n\t\t\tif (count % 5 == 0 && count % 3 != 0) {\n\t\t\t\tbuzz.acquire();\n\t\t\t\tprintBuzz.run();\n\t\t\t\tcount++;\n\t\t\t\treleaseSemaphore(count);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n\t\twhile (count <= n) {\n\t\t\tif (count % 15 == 0) {\n\t\t\t\tfizzbuzz.acquire();\n\t\t\t\tprintFizzBuzz.run();\n\t\t\t\tcount++;\n\t\t\t\treleaseSemaphore(count);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void number(IntConsumer printNumber) throws InterruptedException {\n\t\twhile (count <= n) {\n\t\t\tif (count % 5 != 0 && count % 3 != 0) {\n\t\t\t\tnumber.acquire();\n\t\t\t\tprintNumber.accept(count);\n\t\t\t\tcount++;\n\t\t\t\treleaseSemaphore(count);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void releaseSemaphore(final int i) {\n\t\tif (i % 15 == 0) {\n\t\t\tfizzbuzz.release();\n\t\t\treturn;\n\t\t}\n\t\tif (i % 3 == 0) {\n\t\t\tfizz.release();\n\t\t\treturn;\n\t\t}\n\t\tif (i % 5 == 0) {\n\t\t\tbuzz.release();\n\t\t\treturn;\n\t\t}\n\t\tnumber.release();\n\t}\n}\n\n```\nWait-notify\n\n```\npublic class Solution1195v2 {\n\n\tprivate final int n;\n\n\tprivate int count = 1;\n\n\tpublic Solution1195v2(int n) {\n\t\tthis.n = n;\n\t}\n\n\t// printFizz.run() outputs "fizz".\n\tpublic void fizz(Runnable printFizz) throws InterruptedException {\n\t\tcheckAndPrint(printFizz, x -> x % 3 == 0 && x % 5 != 0);\n\t}\n\n\t// printBuzz.run() outputs "buzz".\n\tpublic void buzz(Runnable printBuzz) throws InterruptedException {\n\t\tcheckAndPrint(printBuzz, x -> x % 5 == 0 && x % 3 != 0);\n\t}\n\n\t// printFizzBuzz.run() outputs "fizzbuzz".\n\tpublic void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n\t\tcheckAndPrint(printFizzBuzz, x -> x % 15 == 0);\n\t}\n\n\t// printNumber.accept(x) outputs "x", where x is an integer.\n\tpublic void number(IntConsumer printNumber) throws InterruptedException {\n\t\tcheckAndPrint(() -> printNumber.accept(count), x -> x % 3 != 0 && x % 5 != 0);\n\t}\n\n\tprivate synchronized void checkAndPrint(final Runnable runnable, final IntPredicate predicate) throws InterruptedException {\n\t\twhile (count <= n) {\n\t\t\tif (predicate.test(count)) {\n\t\t\t\trunnable.run();\n\t\t\t\tcount++;\n\t\t\t\tnotifyAll();\n\t\t\t} else {\n\t\t\t\twait();\n\t\t\t}\n\t\t}\n\t}\n}\n```\n\nAtomicInteger\n\n```\npublic class Solution1195v3 {\n\n\tprivate final AtomicInteger count = new AtomicInteger(1);\n\n\tprivate final int n;\n\n\tpublic Solution1195v3(int n) {\n\t\tthis.n = n;\n\t}\n\n\t// printFizz.run() outputs "fizz".\n\tpublic void fizz(Runnable printFizz) throws InterruptedException {\n\t\tint i;\n\t\twhile ((i = count.get()) <= n) {\n\t\t\tif (i % 3 == 0 && i % 5 != 0) {\n\t\t\t\tprintFizz.run();\n\t\t\t\tcount.compareAndSet(i, i + 1);\n\t\t\t}\n\t\t}\n\t}\n\n\t// printBuzz.run() outputs "buzz".\n\tpublic void buzz(Runnable printBuzz) throws InterruptedException {\n\t\tint i;\n\t\twhile ((i = count.get()) <= n) {\n\t\t\tcount.get();\n\t\t\tif (i % 5 == 0 && i % 3 != 0) {\n\t\t\t\tprintBuzz.run();\n\t\t\t\tcount.compareAndSet(i, i + 1);\n\t\t\t}\n\t\t}\n\t}\n\n\t// printFizzBuzz.run() outputs "fizzbuzz".\n\tpublic void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n\t\tint i;\n\t\twhile ((i = count.get()) <= n) {\n\t\t\tif (i % 15 == 0) {\n\t\t\t\tprintFizzBuzz.run();\n\t\t\t\tcount.compareAndSet(i, i + 1);\n\t\t\t}\n\t\t}\n\t}\n\n\t// printNumber.accept(x) outputs "x", where x is an integer.\n\tpublic void number(IntConsumer printNumber) throws InterruptedException {\n\t\tint i;\n\t\twhile ((i = count.get()) <= n) {\n\t\t\tif (i % 5 != 0 && i % 3 != 0) {\n\t\t\t\tprintNumber.accept(i);\n\t\t\t\tcount.compareAndSet(i, i + 1);\n\t\t\t}\n\t\t}\n\t}\n}\n```\n
2
0
[]
0
fizz-buzz-multithreaded
[Java] Poor Coder's Concurrency - no lock, mutex, semaphore, or other nonsense
java-poor-coders-concurrency-no-lock-mut-4h12
```\n// Is this a solution that respects the electricty costs of slamming every thread every millisecond? No.\n// This bad boy is, however, faster than 98.88% o
mikedupuis
NORMAL
2021-12-16T06:56:25.391461+00:00
2021-12-16T07:00:51.278442+00:00
374
false
```\n// Is this a solution that respects the electricty costs of slamming every thread every millisecond? No.\n// This bad boy is, however, faster than 98.88% of other Java submissions as of 12/16/2021.\n// This is poor coder\'s concurrency, where we need not worry about fancy semaphores, mutexes, locks, etc.\n// Fair warning: if you implement this in a coding interview, you will likely face some... concerned looks.\nclass FizzBuzz {\n private int n;\n \n // The value being printed, fizzed, buzzed, or fizzbuzzed\n int value = 1;\n \n // Whose turn is it?\n int turn = 0;\n \n // Turn sequence, works nicely because fizzbuzz has a cycle length of 15\n // Yes, an enum would be nicer, don\'t @ me\n // 0 - number\n // 1 - fizz\n // 2 - buzz\n // 3 - fizzbuzz\n int turns[] = {\n 0, 0, 1, 0, 2,\n 1, 0, 0, 1, 2,\n 0, 1, 0, 0, 3\n };\n \n // Iterate through turn sequence and increment value\n void nextTurn() {\n turn = (turn + 1)% 15;\n value++;\n }\n \n boolean numTurn() {\n return turns[turn] == 0;\n }\n \n boolean fizzTurn() {\n return turns[turn] == 1;\n }\n \n boolean buzzTurn() {\n return turns[turn] == 2;\n }\n \n boolean fizzBuzzTurn() {\n return turns[turn] == 3;\n }\n \n boolean done() {\n return value == n + 1;\n }\n\n public FizzBuzz(int n) {\n this.n = n;\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n while (true) {\n if (done()) {\n return;\n }\n \n if (!fizzTurn()) {\n Thread.sleep(1);\n continue;\n }\n \n printFizz.run();\n nextTurn();\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n while (true) {\n if (done()) {\n return;\n }\n \n if (!buzzTurn()) {\n Thread.sleep(1);\n continue;\n }\n \n printBuzz.run();\n nextTurn();\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n while (true) {\n if (done()) {\n return;\n }\n \n if (!fizzBuzzTurn()) {\n Thread.sleep(1);\n continue;\n }\n \n printFizzBuzz.run();\n nextTurn();\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n while (true) {\n if (done()) {\n return;\n }\n \n if (!numTurn()) {\n Thread.sleep(1);\n continue;\n }\n \n printNumber.accept(value);\n nextTurn();\n } \n }\n}
2
0
['Java']
0
fizz-buzz-multithreaded
Java Synchronized, very easy to understand and implement, faster than 99%
java-synchronized-very-easy-to-understan-zzou
\nimport java.util.function.Function;\nimport java.util.function.IntConsumer;\n\nclass FizzBuzz {\n private int n;\n private int i;\n\n public FizzBuzz
quandang2002
NORMAL
2021-12-05T06:06:17.172692+00:00
2021-12-05T06:15:50.570194+00:00
260
false
```\nimport java.util.function.Function;\nimport java.util.function.IntConsumer;\n\nclass FizzBuzz {\n private int n;\n private int i;\n\n public FizzBuzz(int n) {\n this.n = n;\n this.i = 1;\n }\n\n private synchronized boolean testAndIncrease(Function<Integer, Boolean> fn) {\n if (i <= n && fn.apply(i))\n i++;\n return i <= n;\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n while (\n testAndIncrease((index) -> {\n if (index % 3 == 0 && index % 5 != 0) {\n printFizz.run();\n return true;\n }\n return false;\n })\n ) ;\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n while (\n testAndIncrease((index) -> {\n if (index % 3 != 0 && index % 5 == 0) {\n printBuzz.run();\n return true;\n }\n return false;\n })\n ) ;\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n while (\n testAndIncrease((index) -> {\n if (index % 3 == 0 && index % 5 == 0) {\n printFizzBuzz.run();\n return true;\n }\n return false;\n })\n ) ;\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n while (\n testAndIncrease((index) -> {\n if (index % 3 != 0 && index % 5 != 0) {\n printNumber.accept(index);\n return true;\n }\n return false;\n })\n ) ;\n }\n}\n```
2
0
[]
0
fizz-buzz-multithreaded
JAVA EASY SOLUTION
java-easy-solution-by-aniket7419-r40n
\nclass FizzBuzz {\n private int i;\n private int n=1;\n public FizzBuzz(int n) {\n i = n;\n }\n\n // printFizz.run() outputs "fizz".\n
aniket7419
NORMAL
2021-11-29T13:38:50.290912+00:00
2021-11-29T13:38:50.290950+00:00
251
false
```\nclass FizzBuzz {\n private int i;\n private int n=1;\n public FizzBuzz(int n) {\n i = n;\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n while(n<=i)\n {\n synchronized(FizzBuzz.class){\n if(n<=i)\n if(n%3==0&&n%5!=0)\n {\n printFizz.run();\n n++;\n }\n }\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n while(n<=i){\n synchronized(FizzBuzz.class){\n if(n<=i)\n if(n%3!=0&&n%5==0)\n {\n printBuzz.run();\n n++;\n }\n }\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n while(n<=i){\n synchronized(FizzBuzz.class){\n if(n<=i)\n if(n%5==0&&n%3==0){\n printFizzBuzz.run();\n n++;\n }\n }\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n while(n<=i){ \n synchronized(FizzBuzz.class){\n if(n<=i)\n if(n%5!=0&&n%3!=0){\n printNumber.accept(n);\n n++;\n }\n }\n }\n }\n}\n```
2
0
[]
0
fizz-buzz-multithreaded
Python3 solution using Barrier
python3-solution-using-barrier-by-barema-5ee7
Most of the solutions on here are more complicated than they need to be. If you use Barrier to make sure that each thread is looping\nthrough n elements in a sy
baremaximum
NORMAL
2021-11-06T07:39:23.814157+00:00
2021-11-06T07:39:23.814198+00:00
149
false
Most of the solutions on here are more complicated than they need to be. If you use Barrier to make sure that each thread is looping\nthrough `n` elements in a synchronized way, the solution isn\'t much different than regular fizzbuzz.\n```\nfrom threading import Barrier\n\nclass FizzBuzz:\n def __init__(self, n: int):\n self.b = Barrier(4)\n self.n = n\n\n # printFizz() outputs "fizz"\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n \n for cnt in range(1, self.n + 1):\n \n if cnt % 3 == 0 and cnt % 5 != 0:\n printFizz()\n \n self.b.wait()\n \n # printBuzz() outputs "buzz"\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n \n for cnt in range(1, self.n + 1):\n\n if cnt % 3 != 0 and cnt % 5 == 0:\n printBuzz()\n\n self.b.wait()\n \t\n # printFizzBuzz() outputs "fizzbuzz"\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n \n for cnt in range(1, self.n + 1):\n \n if cnt % 3 == 0 and cnt % 5 == 0:\n printFizzBuzz()\n \n self.b.wait()\n\n # printNumber(x) outputs "x", where x is an integer.\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n \n for cnt in range(1, self.n + 1):\n \n if cnt % 3 != 0 and cnt % 5 != 0:\n printNumber(cnt)\n \n self.b.wait()\n```
2
0
[]
0
fizz-buzz-multithreaded
Very Simple Java ReentrantLock solution
very-simple-java-reentrantlock-solution-nqiaf
All the methods do the same thing, this can be abstracted out. Acquire the lock, do your business, unlock for others and continue. \n\n\n\nclass FizzBuzz {\n
hughesj919
NORMAL
2021-09-08T03:17:41.550351+00:00
2021-09-08T03:17:41.550391+00:00
291
false
All the methods do the same thing, this can be abstracted out. Acquire the lock, do your business, unlock for others and continue. \n\n```\n\nclass FizzBuzz {\n private int n;\n private int i;\n private ReentrantLock lock;\n\n public FizzBuzz(int n) {\n this.n = n;\n this.i = 1;\n this.lock = new ReentrantLock();\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n Predicate<Integer> pred = val -> val % 5 != 0 && val % 3 == 0;\n runThread(() -> printFizz.run(), pred);\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n Predicate<Integer> pred = val -> val % 5 == 0 && val % 3 != 0;\n runThread(() -> printBuzz.run(), pred);\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n Predicate<Integer> pred = val -> val % 3 == 0 && val % 5 == 0;\n runThread(() -> printFizzBuzz.run(), pred);\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n Predicate<Integer> pred = val -> val % 3 != 0 && val % 5 != 0;\n runThread(() -> printNumber.accept(i), pred);\n }\n \n \n private void runThread(Runnable runnable, Predicate p) throws InterruptedException {\n try {\n lock.lock();\n while (i <= n) {\n if (p.test(i)) {\n runnable.run();\n i++;\n }\n lock.unlock();\n lock.lock();\n }\n \n } finally {\n lock.unlock();\n }\n }\n}\n\n```
2
0
[]
0
fizz-buzz-multithreaded
Java | Clean code with synchronized helper function
java-clean-code-with-synchronized-helper-ssu8
\nclass FizzBuzz {\n private final int n;\n private int i = 1;\n\n public FizzBuzz(int n) {\n this.n = n;\n }\n \n private synchronized
arruw
NORMAL
2021-07-12T14:50:45.250978+00:00
2021-07-12T14:50:45.251025+00:00
231
false
```\nclass FizzBuzz {\n private final int n;\n private int i = 1;\n\n public FizzBuzz(int n) {\n this.n = n;\n }\n \n private synchronized void helper(Runnable printer, boolean divBy3, boolean divBy5) throws InterruptedException {\n while (i <= n) {\n if ((i % 3 == 0) == divBy3 && (i % 5 == 0) == divBy5) {\n printer.run();\n i++;\n notifyAll();\n } else {\n wait();\n }\n }\n }\n \n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n helper(printFizz, true, false);\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n helper(printBuzz, false, true);\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n helper(printFizzBuzz, true, true);\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n final Runnable printer = new Runnable() {\n @Override\n public void run() {\n printNumber.accept(i);\n }\n };\n helper(printer, false, false);\n }\n}\n```
2
0
[]
0
fizz-buzz-multithreaded
C++ Semaphores / Efficient, Clean, and Easy to Understand
c-semaphores-efficient-clean-and-easy-to-oon4
\n#include <semaphore.h>\n\nclass FizzBuzz {\nprivate:\n int n;\n \n int count = 1;\n \n sem_t sem_fizz;\n sem_t sem_buzz;\n sem_t sem_fizz
unpoopenzoid
NORMAL
2021-07-07T22:31:23.132909+00:00
2021-07-07T22:33:43.671968+00:00
223
false
```\n#include <semaphore.h>\n\nclass FizzBuzz {\nprivate:\n int n;\n \n int count = 1;\n \n sem_t sem_fizz;\n sem_t sem_buzz;\n sem_t sem_fizzbuzz;\n sem_t sem_number;\n \n void notify_next() {\n count++;\n \n if (count > n) {\n sem_post(&sem_fizz);\n sem_post(&sem_buzz);\n sem_post(&sem_fizzbuzz);\n sem_post(&sem_number);\n return; \n }\n\n if (count % 15 == 0) {\n sem_post(&sem_fizzbuzz);\n } else if (count % 3 == 0) {\n sem_post(&sem_fizz);\n } else if (count % 5 == 0) {\n sem_post(&sem_buzz);\n } else {\n sem_post(&sem_number);\n }\n }\npublic:\n FizzBuzz(int n) {\n this->n = n;\n sem_init(&sem_fizz, 0, 0);\n sem_init(&sem_buzz, 0, 0);\n sem_init(&sem_fizzbuzz, 0, 0);\n sem_init(&sem_number, 0, 1);\n }\n\n // printFizz() outputs "fizz".\n void fizz(function<void()> printFizz) {\n while (1) {\n sem_wait(&sem_fizz);\n if (count > n) {\n return;\n }\n printFizz();\n notify_next();\n }\n }\n\n // printBuzz() outputs "buzz".\n void buzz(function<void()> printBuzz) {\n while (1) {\n sem_wait(&sem_buzz);\n if (count > n) {\n return;\n }\n printBuzz();\n notify_next();\n }\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n\tvoid fizzbuzz(function<void()> printFizzBuzz) {\n while (1) {\n sem_wait(&sem_fizzbuzz);\n if (count > n) {\n return;\n }\n printFizzBuzz();\n notify_next();\n }\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n void number(function<void(int)> printNumber) {\n while (1) {\n sem_wait(&sem_number);\n if (count > n) {\n return;\n }\n printNumber(count);\n notify_next();\n }\n }\n};\n```\n\nThis code uses a semaphore per thread / function, doesn\'t have the clunky for loop logic of a lot of solutions on here, and efficitiently notifies only threads that need to wake up. The `number()` thread is always the first to print, so that semaphore is initialized to `1`.\n\nOne note about the variable `count`, which is accessed without locks by multiple threads. The code is structured so that only one thread will ever be modifying `count` at a time (in the `notify_next()` function) and during that time no other thread will be reading it. When `count > n` and we need to finish executing, multiple threads will be reading from `count`, but this isn\'t a problem.\n\nPlease let me know if you have any questions or suggestions. Thanks!
2
0
[]
0
fizz-buzz-multithreaded
Java, no locks and non-blocking solution
java-no-locks-and-non-blocking-solution-ce6wl
Optimistic locking/ Conditional writes based solution. \n\n\nclass FizzBuzz {\n private int n;\n private int max;\n\n public FizzBuzz(int n) {\n
azhartas
NORMAL
2021-05-25T10:36:33.485788+00:00
2021-05-25T10:42:45.864862+00:00
471
false
Optimistic locking/ Conditional writes based solution. \n\n```\nclass FizzBuzz {\n private int n;\n private int max;\n\n public FizzBuzz(int n) {\n this.max = n;\n this.n = 1;\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n while(true) {\n int tmp = this.n;\n if(tmp > this.max)\n break;\n if(tmp % 3 == 0 && tmp % 5 != 0) {\n printFizz.run();\n n++;\n }}\n\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n while(true) {\n int tmp = this.n;\n if(tmp > this.max)\n break;\n if(tmp % 3 != 0 && tmp % 5 == 0 ) {\n printBuzz.run();\n n++;\n }}\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n while(true) {\n int tmp = this.n;\n if(tmp > this.max)\n break;\n if(tmp % 3 == 0 && tmp % 5 == 0) {\n printFizzBuzz.run();\n n++;\n }\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n while(true) {\n int tmp = this.n;\n if(tmp > this.max)\n break;\n if(tmp % 3 != 0 && tmp % 5 != 0) {\n printNumber.accept(tmp);\n n++;\n }\n }\n }\n}\n```
2
1
['Java']
1
fizz-buzz-multithreaded
[Python3] using Lock()
python3-using-lock-by-ye15-bdq8
\n\nfrom threading import Lock\n\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.fizzLock = Lock(); self.fizzLock.acquire()\
ye15
NORMAL
2021-05-14T20:19:43.021181+00:00
2021-05-14T20:19:43.021208+00:00
688
false
\n```\nfrom threading import Lock\n\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.fizzLock = Lock(); self.fizzLock.acquire()\n self.buzzLock = Lock(); self.buzzLock.acquire()\n self.fzbzLock = Lock(); self.fzbzLock.acquire()\n self.numberLock = Lock()\n\n # printFizz() outputs "fizz"\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n \twhile True: \n self.fizzLock.acquire()\n if self.n == 0: break \n printFizz()\n self.numberLock.release()\n\n # printBuzz() outputs "buzz"\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n \twhile True: \n self.buzzLock.acquire()\n if self.n == 0: break \n printBuzz()\n self.numberLock.release()\n\n # printFizzBuzz() outputs "fizzbuzz"\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n while True: \n self.fzbzLock.acquire()\n if self.n == 0: break \n printFizzBuzz()\n self.numberLock.release()\n\n # printNumber(x) outputs "x", where x is an integer.\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n for x in range(1, self.n+1):\n self.numberLock.acquire()\n if x % 15 == 0: \n self.fzbzLock.release()\n elif x % 3 == 0: \n self.fizzLock.release()\n elif x % 5 == 0: \n self.buzzLock.release()\n else: \n printNumber(x)\n self.numberLock.release()\n \n self.numberLock.acquire()\n self.n = 0 \n self.fizzLock.release()\n self.buzzLock.release()\n self.fzbzLock.release()\n \n```
2
0
['Python3']
0
fizz-buzz-multithreaded
C++ MUTEX AND CONDITIONAL VARIABLE 40MS
c-mutex-and-conditional-variable-40ms-by-jcr9
\nclass FizzBuzz {\nprivate:\n int n;\n mutex m;\n condition_variable fizzCond;\n condition_variable buzzCond;\n condition_variable fizzbuzzCond;
abhi_tom
NORMAL
2021-04-11T05:04:27.927081+00:00
2021-04-11T05:04:27.927110+00:00
288
false
```\nclass FizzBuzz {\nprivate:\n int n;\n mutex m;\n condition_variable fizzCond;\n condition_variable buzzCond;\n condition_variable fizzbuzzCond;\n condition_variable numberCond;\n int cnt;\n \n bool onlyDivByThree(int n){\n if(n%3==0 and n%5!=0)\n return true;\n return false;\n }\n bool onlyDivByFive(int n){\n if(n%3!=0 and n%5==0)\n return true;\n return false;\n }\n bool DivByBoth(int n){\n if(n%3==0 and n%5==0)\n return true;\n return false;\n }\n bool DivByNone(int n){\n if(n%3!=0 and n%5!=0)\n return true;\n return false;\n }\npublic:\n FizzBuzz(int n) {\n this->n = n;\n cnt=1;\n }\n\n // printFizz() outputs "fizz".\n void fizz(function<void()> printFizz) {\n unique_lock<mutex> locker(m);\n \n while(cnt<=n){\n fizzCond.wait_for(locker,50ms,[&](){\n return onlyDivByThree(cnt);\n });\n \n if(cnt>n){\n cnt++;\n return;\n }\n \n printFizz();\n cnt++;\n \n if(onlyDivByFive(cnt)){\n buzzCond.notify_one();\n } else if(DivByBoth(cnt)){\n fizzbuzzCond.notify_one();\n }else{\n numberCond.notify_one();\n }\n }\n }\n\n // printBuzz() outputs "buzz".\n void buzz(function<void()> printBuzz) {\n unique_lock<mutex> locker(m);\n \n while(cnt<=n){\n buzzCond.wait_for(locker,50ms,[&](){\n return onlyDivByFive(cnt);\n });\n \n if(cnt>n){\n cnt++;\n return;\n }\n \n printBuzz();\n cnt++;\n \n if(onlyDivByThree(cnt)){\n fizzCond.notify_one();\n } else if(DivByBoth(cnt)){\n fizzbuzzCond.notify_one();\n }else{\n numberCond.notify_one();\n }\n }\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n\tvoid fizzbuzz(function<void()> printFizzBuzz) {\n unique_lock<mutex> locker(m);\n \n while(cnt<=n){\n fizzbuzzCond.wait_for(locker,50ms,[&](){\n return DivByBoth(cnt);\n });\n \n if(cnt>n){\n cnt++;\n return;\n }\n \n printFizzBuzz();\n cnt++;\n \n if(onlyDivByThree(cnt)){\n fizzCond.notify_one();\n } else if(onlyDivByFive(cnt)){\n buzzCond.notify_one();\n }else{\n numberCond.notify_one();\n }\n }\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n void number(function<void(int)> printNumber) {\n unique_lock<mutex> locker(m);\n \n while(cnt<=n){\n numberCond.wait_for(locker,50ms,[&](){\n return DivByNone(cnt);\n });\n \n if(cnt>n){\n cnt++;\n return;\n }\n \n printNumber(cnt);\n cnt++;\n \n if(onlyDivByThree(cnt)){\n fizzCond.notify_one();\n } else if(onlyDivByFive(cnt)){\n buzzCond.notify_one();\n }else if(DivByBoth(cnt)){\n fizzbuzzCond.notify_one();\n }else{\n numberCond.notify_one();\n }\n }\n }\n};\n```
2
0
[]
0
fizz-buzz-multithreaded
[Java] 7ms | 99% using semaphores for each type of 'token writer'
java-7ms-99-using-semaphores-for-each-ty-a6qq
\nclass FizzBuzz {\n private final int n;\n private final Semaphore numberSemaphore = new Semaphore(1);\n private final Semaphore fizzSemaphore = new S
TheRuminator
NORMAL
2021-03-10T14:31:26.933628+00:00
2021-03-10T14:55:09.051900+00:00
480
false
```\nclass FizzBuzz {\n private final int n;\n private final Semaphore numberSemaphore = new Semaphore(1);\n private final Semaphore fizzSemaphore = new Semaphore(0);\n private final Semaphore buzzSemaphore = new Semaphore(0);\n private final Semaphore fizzbuzzSemaphore = new Semaphore(0);\n\n public FizzBuzz(int n) {\n this.n = n;\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n for (int i = 1; i <= n; i++) {\n if (i % 3 == 0 && i % 5 != 0) {\n fizzSemaphore.acquire();\n printFizz.run();\n releaseNextSemaphore(i + 1);\n }\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n for (int i = 1; i <= n; i++) {\n if (i % 5 == 0 && i % 3 != 0) {\n buzzSemaphore.acquire();\n printBuzz.run();\n releaseNextSemaphore(i + 1);\n }\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n for (int i = 1; i <= n; i++) {\n if (i % 15 == 0) {\n fizzbuzzSemaphore.acquire();\n printFizzBuzz.run();\n releaseNextSemaphore(i + 1);\n }\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n for (int i = 1; i <= n; i++) {\n if (i % 5 != 0 && i % 3 != 0) {\n numberSemaphore.acquire();\n printNumber.accept(i);\n releaseNextSemaphore(i + 1);\n }\n }\n }\n\n public void releaseNextSemaphore(int next) {\n if (next % 15 == 0) {\n fizzbuzzSemaphore.release();\n } else if (next % 3 == 0) {\n fizzSemaphore.release();\n } else if (next % 5 == 0) {\n buzzSemaphore.release();\n } else {\n numberSemaphore.release();\n }\n }\n}\n```
2
0
[]
1
fizz-buzz-multithreaded
[Java] Just volatile
java-just-volatile-by-jokersun-7r3j
\nclass FizzBuzz {\n\n private volatile int i;\n\n private final int n;\n\n public FizzBuzz(int n) {\n this.i = 1;\n this.n = n;\n }\n
jokersun
NORMAL
2021-02-15T12:49:51.560026+00:00
2021-03-01T02:13:35.698360+00:00
407
false
```\nclass FizzBuzz {\n\n private volatile int i;\n\n private final int n;\n\n public FizzBuzz(int n) {\n this.i = 1;\n this.n = n;\n }\n\n public void fizz(Runnable printFizz) throws InterruptedException {\n for (int j = i; j <= n; j = i) {\n if (j % 3 == 0 && j % 5 != 0) {\n printFizz.run();\n i = j + 1;\n }\n Thread.yield();\n }\n }\n\n public void buzz(Runnable printBuzz) throws InterruptedException {\n for (int j = i; j <= n; j = i) {\n if (j % 5 == 0 && j % 3 != 0) {\n printBuzz.run();\n i = j + 1;\n }\n Thread.yield();\n }\n }\n\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n for (int j = i; j <= n; j = i) {\n if (j % 3 == 0 && j % 5 == 0) {\n printFizzBuzz.run();\n i = j + 1;\n }\n Thread.yield();\n }\n }\n\n public void number(IntConsumer printNumber) throws InterruptedException {\n for (int j = i; j <= n; j = i) {\n if (j % 3 != 0 && j % 5 != 0) {\n printNumber.accept(i);\n i = j + 1;\n }\n Thread.yield();\n }\n }\n}\n```
2
0
[]
1
fizz-buzz-multithreaded
[Python] Barrier solution with explanation
python-barrier-solution-with-explanation-499p
There are four threads, and they need to interate through 1 to n synchronously, meaning that no thread can advance to 2 until all threads have "processed" 1, an
goldie213
NORMAL
2021-02-11T02:48:29.881314+00:00
2021-02-11T02:48:29.881459+00:00
368
false
There are four threads, and they need to interate through 1 to n synchronously, meaning that no thread can advance to 2 until all threads have "processed" 1, and so on. Therefore we can use Barrier from python, a convenient helper to make every thread wait until all of them reach some condition.\n\n\n```\nimport threading\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.b = threading.Barrier(4)\n \n # printFizz() outputs "fizz"\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n for i in range(1, self.n+1):\n if i % 3 == 0 and i % 5 != 0:\n printFizz()\n self.b.wait()\n \n\n # printBuzz() outputs "buzz"\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n \tfor i in range(1, self.n+1):\n if i % 3 != 0 and i % 5 == 0:\n printBuzz()\n self.b.wait()\n\n\n # printFizzBuzz() outputs "fizzbuzz"\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n for i in range(1, self.n+1):\n if i % 3 == 0 and i % 5 == 0:\n printFizzBuzz()\n self.b.wait()\n \n\n # printNumber(x) outputs "x", where x is an integer.\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n for i in range(1, self.n+1):\n if i % 3 != 0 and i % 5 != 0:\n printNumber(i)\n self.b.wait()\n```
2
0
[]
0
fizz-buzz-multithreaded
C Solution: mutex and cond wait and broadcast
c-solution-mutex-and-cond-wait-and-broad-swdr
``\n#include <pthread.h>\ntypedef struct {\n int nsize;\n int cur;\n pthread_mutex_t lock;\n pthread_cond_t cond;\n} FizzBuzz;\n\nFizzBuzz* fizzBuzz
leet_jx
NORMAL
2020-12-31T17:44:21.527989+00:00
2020-12-31T17:44:21.528037+00:00
321
false
```\n#include <pthread.h>\ntypedef struct {\n int nsize;\n int cur;\n pthread_mutex_t lock;\n pthread_cond_t cond;\n} FizzBuzz;\n\nFizzBuzz* fizzBuzzCreate(int n) {\n FizzBuzz* obj=malloc(sizeof(FizzBuzz));\n obj->nsize=n;\n obj->cur=1;\n pthread_mutex_init(&obj->lock, NULL);\n pthread_cond_init(&obj->cond, NULL);\n return obj;\n}\n\n// printFizz() outputs "fizz".\nvoid fizz(FizzBuzz* obj) {\n while(1){\n pthread_mutex_lock(&obj->lock);\n if(obj->cur > obj->nsize){ \n pthread_mutex_unlock(&obj->lock);\n return;\n }\n if(obj->cur%3==0 && obj->cur%5!=0){\n printFizz();\n obj->cur++;\n pthread_cond_broadcast(&obj->cond);\n }else{\n pthread_cond_wait(&obj->cond, &obj->lock);\n }\n pthread_mutex_unlock(&obj->lock); \n }\n}\n\n// printBuzz() outputs "buzz".\nvoid buzz(FizzBuzz* obj) {\n while(1){\n pthread_mutex_lock(&obj->lock);\n if(obj->cur > obj->nsize){ \n pthread_mutex_unlock(&obj->lock);\n return;\n } \n if(obj->cur%3!=0 && obj->cur%5==0){\n printBuzz();\n obj->cur++;\n pthread_cond_broadcast(&obj->cond);\n }else{\n pthread_cond_wait(&obj->cond, &obj->lock);\n }\n pthread_mutex_unlock(&obj->lock); \n }\n}\n\n// printFizzBuzz() outputs "fizzbuzz".\nvoid fizzbuzz(FizzBuzz* obj) {\n while(1){\n pthread_mutex_lock(&obj->lock); \n if(obj->cur > obj->nsize){\n pthread_mutex_unlock(&obj->lock);\n return;\n }\n if(obj->cur%3==0 && obj->cur%5==0){\n printFizzBuzz();\n obj->cur++;\n pthread_cond_broadcast(&obj->cond);\n }else{\n pthread_cond_wait(&obj->cond, &obj->lock);\n }\n pthread_mutex_unlock(&obj->lock); \n }\n}\n\n// You may call global function `void printNumber(int x)`\n// to output "x", where x is an integer.\nvoid number(FizzBuzz* obj) {\n while(1){\n pthread_mutex_lock(&obj->lock);\n if(obj->cur > obj->nsize){ \n pthread_mutex_unlock(&obj->lock);\n return;\n } \n if(obj->cur%3!=0 && obj->cur%5!=0){\n printNumber(obj->cur);\n obj->cur++;\n pthread_cond_broadcast(&obj->cond);\n }else{\n pthread_cond_wait(&obj->cond, &obj->lock);\n }\n pthread_mutex_unlock(&obj->lock); \n } \n}\n\nvoid fizzBuzzFree(FizzBuzz* obj) {\n pthread_mutex_destroy(&obj->lock);\n pthread_cond_destroy(&obj->cond);\n free(obj);\n}\n
2
0
[]
0
fizz-buzz-multithreaded
Java - Beats 100% simple solution
java-beats-100-simple-solution-by-maorbr-gwb1
java\n\nclass FizzBuzz {\n\tprivate int n;\n\n\tprivate AtomicInteger counter;\n\n\tpublic FizzBuzz(int n) {\n\t\tthis.n = n;\n\t\tthis.counter = new AtomicInte
maorbril
NORMAL
2020-09-17T23:35:05.844707+00:00
2020-09-17T23:35:05.844746+00:00
378
false
```java\n\nclass FizzBuzz {\n\tprivate int n;\n\n\tprivate AtomicInteger counter;\n\n\tpublic FizzBuzz(int n) {\n\t\tthis.n = n;\n\t\tthis.counter = new AtomicInteger(1);\n\t}\n\n\n // printFizz.run() outputs "fizz".\n\tpublic void fizz(Runnable printFizz) throws InterruptedException {\n\t\twhile (counter.get() <= n) {\n\t\t\tsynchronized(counter) {\n\t\t\t\tif (counter.get() > n) return;\n\t\t\t\tif (counter.get() % 3 == 0 && counter.get() % 5 != 0) {\n\t\t\t\t\tprintFizz.run();\n\t\t\t\t\tcounter.incrementAndGet();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n // printBuzz.run() outputs "buzz".\n\tpublic void buzz(Runnable printBuzz) throws InterruptedException {\n\t\twhile (counter.get() <= n) {\n\t\t\tsynchronized(counter) {\n\t\t\t\tif (counter.get() > n) return;\n\t\t\t\tif (counter.get() % 5 == 0 && counter.get() % 3 != 0) {\n\t\t\t\t\tprintBuzz.run();\n\t\t\t\t\tcounter.incrementAndGet();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n\tpublic void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n\t\twhile (counter.get() <= n) {\n\t\t\tsynchronized(counter) {\n\t\t\t\tif (counter.get() > n) return;\n\t\t\t\tif (counter.get() % 5 == 0 && counter.get() % 3 == 0) {\n\t\t\t\t\tprintFizzBuzz.run();\n\t\t\t\t\tcounter.incrementAndGet();\n\t\t\t\t}\n\t\t\t} \n\t\t}\n\t}\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n\tpublic void number(IntConsumer printNumber) throws InterruptedException {\n\t\twhile (counter.get() <= n) {\n\t\t\tsynchronized(counter) {\n\t\t\t\tif (counter.get() > n) return;\n\t\t\t\tif (counter.get() % 5 != 0 && counter.get() % 3 != 0) {\n\t\t\t\t\tprintNumber.accept(counter.getAndIncrement());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n```
2
1
[]
2
fizz-buzz-multithreaded
[C++] Mutex-based Solution Explained, ~70% Time, ~65% Space
c-mutex-based-solution-explained-70-time-wryi
So, we have 4 class variables: n to store our the input passed in the constructor, i to keep track of our currently printed number (initially set to 1), a mutex
ajna
NORMAL
2020-08-26T20:20:12.936887+00:00
2020-08-26T20:20:12.936947+00:00
856
false
So, we have 4 class variables: `n` to store our the input passed in the constructor, `i` to keep track of our currently printed number (initially set to `1`), a [mutex](https://en.cppreference.com/w/cpp/thread/mutex) `m` and a [`condition _variable`](https://en.cppreference.com/w/cpp/thread/condition_variable) `c`.\n\nWe can create a helper `run` in order to avoid too much WET code and we expect it to receive a `check` and a `print` function; inside we will run an infinite loop that constantly locks, wait for a condition in `check` to be valid and move on; if the condition is the first, we are done counting and then we `break`.\n\nOtherwise we run the function, increase `i`, unlock, notify all and move again until done.\n\nProbably not the best solution at all, but I am kind of a n00b on both C++ and multithreading, so feel free to bash me hard on this one with suggestions, criticism and general advice if you wish :)\n\nThe code:\n\n```cpp\nclass FizzBuzz {\nprivate:\n int n, i = 1;\n mutex m;\n condition_variable c;\n\npublic:\n FizzBuzz(int n) {\n // nothing to see here\n this->n = n;\n }\n \n // helper to keep the code a bit DRY\n void run(function<bool(int)> check, function<void(int)> print) {\n while (true) {\n // setting the lock\n unique_lock<mutex> lock(m);\n // setting the conditions\n c.wait(lock, [&](){return i > n || check(i);});\n // breaking if we are done\n if (i > n) break;\n // printing otherwise while also incrementing\n print(i++);\n lock.unlock();\n c.notify_all();\n }\n }\n\n // printFizz() outputs "fizz".\n void fizz(function<void()> printFizz) {\n run(\n [](int i){return i % 3 == 0 && i % 5;},\n [&](int i){printFizz();}\n );\n }\n\n // printBuzz() outputs "buzz".\n void buzz(function<void()> printBuzz) {\n run(\n [](int i){return i % 3 && i % 5 == 0;},\n [&](int i){printBuzz();}\n );\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n\tvoid fizzbuzz(function<void()> printFizzBuzz) {\n run(\n [](int i){return i % 15 == 0;},\n [&](int i){printFizzBuzz();}\n );\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n void number(function<void(int)> printNumber) {\n run(\n [](int i){return i % 3 && i % 5;},\n [&](int i){printNumber(i);}\n );\n }\n};\n```
2
0
['C', 'C++']
1
fizz-buzz-multithreaded
c# semaphore
c-semaphore-by-code-world-7lcb
Key points of problem:\n\n1. Four threads has same object but calls different method.\n2. This require four threads to signal each other for execution. Think it
code-world
NORMAL
2020-08-10T06:11:27.911329+00:00
2020-08-10T06:11:27.911379+00:00
662
false
Key points of problem:\n\n1. Four threads has same object but calls different method.\n2. This require four threads to signal each other for execution. Think it as a traffic signal, traffic from four side has to wait for there signal to go. This makes Semaphore as my pick for this problem.\n\n\n```\nusing System.Threading;\n\npublic class FizzBuzz {\n private int n;\n private int x;\n private Semaphore semNum;\n private Semaphore semFizz;\n private Semaphore semBuzz;\n private Semaphore semFizzBuzz;\n \n public FizzBuzz(int n) {\n this.n = n;\n this.x = 1;\n semNum = new Semaphore(1,1);\n semFizz = new Semaphore(0,1);\n semBuzz = new Semaphore(0,1);\n semFizzBuzz = new Semaphore(0,1);\n }\n\n // printFizz() outputs "fizz".\n public void Fizz(Action printFizz) {\n while(x <= n){\n semFizz.WaitOne();\n\n if(x > n)\n return;\n \n if(x%3 == 0){\n printFizz();\n x++;\n }\n ReleaseSemaphore(x);\n }\n }\n\n // printBuzzz() outputs "buzz".\n public void Buzz(Action printBuzz) {\n while(x <= n){\n semBuzz.WaitOne();\n\n if(x > n)\n return;\n \n if(x%5 == 0){\n printBuzz();\n x++;\n }\n ReleaseSemaphore(x);\n }\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n public void Fizzbuzz(Action printFizzBuzz) {\n while(x <= n){\n semFizzBuzz.WaitOne();\n\n if(x > n)\n return;\n \n if(x%15==0){\n printFizzBuzz();\n x++;\n }\n\n ReleaseSemaphore(x);\n }\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n public void Number(Action<int> printNumber) {\n while(x <= n){\n semNum.WaitOne();\n\n if(x > n)\n return;\n \n if(x%3 != 0 && x%5 != 0){\n printNumber(x);\n x++;\n }\n\n ReleaseSemaphore(x);\n }\n }\n \n private void ReleaseSemaphore(int i){\n if(i > n){\n semNum.Release();\n semFizz.Release();\n semBuzz.Release();\n semFizzBuzz.Release();\n return;\n }\n \n if(i % 15 == 0){\n semFizzBuzz.Release();\n } else if(i % 3 == 0){\n semFizz.Release();\n }else if(i % 5 == 0){\n semBuzz.Release();\n }else{\n semNum.Release();\n }\n }\n}\n```
2
0
[]
2
fizz-buzz-multithreaded
Need to notify others when we exit thread task- C++
need-to-notify-others-when-we-exit-threa-1vnd
In many of the C++ posts, I see that we are missing notifying other threads when count > n. Since the order of the execution is never gaurenteed, I belive we ne
swapnai
NORMAL
2020-06-23T01:38:00.992052+00:00
2020-06-23T01:56:00.755429+00:00
175
false
In many of the C++ posts, I see that we are missing notifying other threads when count > n. Since the order of the execution is never gaurenteed, I belive we need to notify others before exiting a thread. \n\n```\nclass FizzBuzz {\nprivate:\n int n;\n int count;\n condition_variable cv;\n mutex mux;\n\npublic:\n FizzBuzz(int n) {\n this->n = n;\n count = 1;\n }\n\n void run(function<void()> task, function<bool()> predicate) {\n // 0. run forever\n for (;;) {\n // 1. enable lock scope\n {\n // 2. aquire unique lock\n unique_lock<mutex> lck(mux);\n \n // 3. wait for predicate to be true\n cv.wait(lck, [&]() {return predicate() || count > n;});\n // 4. test task exit condition \n if (count > n) {\n lck.unlock();\n cv.notify_all();\n return;\n }\n // 5. mutate data\n task(); count++;\n } // 6. exit lock scope\n // 7. notify other threads\n cv.notify_all();\n }\n }\n // printFizz() outputs "fizz".\n void fizz(function<void()> printFizz) {\n run(printFizz, [&](){return count % 3 == 0 && count % 5 != 0;});\n }\n\n // printBuzz() outputs "buzz".\n void buzz(function<void()> printBuzz) {\n run(printBuzz, [&](){return count % 3 != 0 && count % 5 == 0;}); \n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n\tvoid fizzbuzz(function<void()> printFizzBuzz) {\n run(printFizzBuzz, [&](){return count % 3 == 0 && count % 5 == 0;}); \n }\n\n // printNumber(x) outputs "x", where x is an integer.\n void number(function<void(int)> printNumber) {\n run([&]() { printNumber(count);}, [&]() { return count % 3 != 0 && count % 5 != 0;}); \n }\n};\n```
2
0
[]
1
fizz-buzz-multithreaded
Java simple semaphore
java-simple-semaphore-by-cuny-66brother-6mwl
\nclass FizzBuzz {\n private int n;\n Semaphore f=new Semaphore(1);\n Semaphore b=new Semaphore(1);\n Semaphore fb=new Semaphore(1);\n Semaphore
CUNY-66brother
NORMAL
2020-05-21T12:15:38.208883+00:00
2020-05-21T12:15:38.208960+00:00
286
false
```\nclass FizzBuzz {\n private int n;\n Semaphore f=new Semaphore(1);\n Semaphore b=new Semaphore(1);\n Semaphore fb=new Semaphore(1);\n Semaphore num=new Semaphore(1);\n public FizzBuzz(int n) {\n this.n = n;\n try{\n f.acquire();\n b.acquire();\n fb.acquire();\n }catch(Exception e){\n \n }\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n for(int i=1;i<=n;i++){\n f.acquire();\n if(i%3==0&&i%5!=0){\n printFizz.run();\n num.release();\n }else{\n f.release();\n }\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n for(int i=1;i<=n;i++){\n b.acquire();\n if(i%3!=0&&i%5==0){\n printBuzz.run();\n num.release();\n }else{\n b.release();\n }\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n for(int i=1;i<=n;i++){\n fb.acquire();\n if(i%3==0&&i%5==0){\n printFizzBuzz.run();\n num.release();\n }else{\n fb.release();\n }\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n for(int i=1;i<=n;i++){\n num.acquire();\n if(i%3==0&&i%5==0){\n fb.release();\n }else if(i%3==0){\n f.release();\n }else if(i%5==0){\n b.release();\n }else{\n printNumber.accept(i);\n num.release();\n }\n }\n f.release();\n b.release();\n fb.release();\n }\n}\n```
2
0
[]
0
fizz-buzz-multithreaded
C : simply sema
c-simply-sema-by-universalcoder12-578l
\ntypedef struct {\n sem_t sn, s3, s5, s35; // Individual semaphores for threads\n int i, n;\n} FizzBuzz;\n\nFizzBuzz* fizzBuzzCreate(int n) {\n FizzBu
universalcoder12
NORMAL
2020-03-25T06:55:43.209468+00:00
2020-03-25T07:01:42.304025+00:00
631
false
```\ntypedef struct {\n sem_t sn, s3, s5, s35; // Individual semaphores for threads\n int i, n;\n} FizzBuzz;\n\nFizzBuzz* fizzBuzzCreate(int n) {\n FizzBuzz* obj = malloc(sizeof (FizzBuzz));\n sem_init(&obj->sn, 0, 0); // All three will wait for number-thread to wake them up\n sem_init(&obj->s3, 0, 0);\n sem_init(&obj->s5, 0, 0);\n \n sem_init(&obj->s35, 0, 0);\n obj->i = 1;\n obj->n = n;\n return obj;\n}\n\nvoid fz(void) { printFizz(); }\nvoid bz(void) { printBuzz(); }\nvoid fbz(void) { printFizzBuzz(); }\ninline void cstub(FizzBuzz *obj, sem_t *t, sem_t *n, void (*f) (void));\ninline void pnum(FizzBuzz *o);\ninline void dl(FizzBuzz *o);\n\nvoid fizz(FizzBuzz* obj) {\n cstub(obj, &obj->s3, &obj->sn, fz);\n}\n\nvoid buzz(FizzBuzz* obj) {\n cstub(obj, &obj->s5, &obj->sn, bz); \n}\n\nvoid fizzbuzz(FizzBuzz* obj) {\n cstub(obj, &obj->s35, &obj->sn, fbz); \n}\n\nvoid number(FizzBuzz* obj) {\n pnum(obj);\n}\n\nvoid fizzBuzzFree(FizzBuzz* obj) {\n dl(obj); \n}\n\n// Process number\ninline void pnum(FizzBuzz *o) {\n while (o->i <= o->n) {\n bool m3 = !(o->i % 3);\n bool m5 = !(o->i % 5); \n if (m3 || m5) {\n m3 && m5 ? sem_post(&o->s35) : // Wake up *only* one of the three\n m5 ? sem_post(&o->s5) :\n sem_post(&o->s3);\n sem_wait(&o->sn); // Get ack\n } else\n printNumber(o->i);\n o->i++; \n }\n sem_post(&o->s35); // Wake all three so that they can exit/return\n sem_post(&o->s5);\n sem_post(&o->s3); \n}\n\n// Common stub for all of the above three\ninline void cstub(FizzBuzz *obj, sem_t *t, sem_t *n, void (*f) (void)) {\n while (1) {\n sem_wait(t);\n if (obj->i > obj->n) {\n sem_post(n);\n return;\n }\n f();\n sem_post(n);\n } \n}\n\n// Relinquish the resources\ninline void dl(FizzBuzz *o) {\n sem_destroy(&o->sn);\n sem_destroy(&o->s3);\n sem_destroy(&o->s5);\n sem_destroy(&o->s35);\n free(o); \n}\n```\n
2
0
['C']
0
fizz-buzz-multithreaded
c++ pre-wait solution with mutex and condition_variable
c-pre-wait-solution-with-mutex-and-condi-slgg
with this solution, each thread will lock the mutex and wait only when it is going to print.\n\nclass FizzBuzz {\nprivate:\n int n;\n int cnt;\n mutex
jay6987
NORMAL
2020-03-25T01:21:53.239649+00:00
2020-03-25T01:46:08.862884+00:00
203
false
with this solution, each thread will lock the mutex and wait only when it is going to print.\n```\nclass FizzBuzz {\nprivate:\n int n;\n int cnt;\n mutex mtx;\n condition_variable cv;\n\npublic:\n FizzBuzz(int n) {\n this->n = n;\n this->cnt = 1;\n }\n\n // printFizz() outputs "fizz".\n void fizz(function<void()> printFizz) {\n for(int i = 3; i<= n; i+=3)\n {\n if(i%5!=0)\n {\n unique_lock lk(mtx); \n cv.wait(lk,[=](){return cnt==i;});\n ++cnt;\n cv.notify_all();\n printFizz();\n }\n } \n }\n\n // printBuzz() outputs "buzz".\n void buzz(function<void()> printBuzz) {\n for(int i = 5; i<= n; i+=5)\n {\n if(i%3!=0)\n {\n unique_lock lk(mtx); \n cv.wait(lk,[=](){return cnt==i;});\n ++cnt;\n cv.notify_all();\n printBuzz();\n }\n } \n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n\tvoid fizzbuzz(function<void()> printFizzBuzz) {\n for(int i = 15; i<= n; i+=15)\n { \n {\n unique_lock lk(mtx); \n cv.wait(lk,[=](){return cnt==i;});\n ++cnt;\n cv.notify_all();\n printFizzBuzz();\n }\n } \n }\n\n // printNumber(x) outputs "x", where x is an integer.\n void number(function<void(int)> printNumber) {\n for(int i = 1; i<= n; ++i)\n {\n if(i%3!=0 && i%5!=0)\n {\n unique_lock lk(mtx); \n cv.wait(lk,[=](){return cnt==i;});\n ++cnt;\n cv.notify_all();\n printNumber(i);\n }\n } \n }\n};\n```
2
0
[]
0
fizz-buzz-multithreaded
Java use wait and notifyAll()
java-use-wait-and-notifyall-by-hobiter-6z88
\nclass FizzBuzz {\n private int n;\n int curr;\n\n public FizzBuzz(int n) {\n this.n = n;\n curr = 1;\n }\n\n // printFizz.run() o
hobiter
NORMAL
2020-03-14T06:39:21.453269+00:00
2020-03-14T06:39:21.453302+00:00
537
false
```\nclass FizzBuzz {\n private int n;\n int curr;\n\n public FizzBuzz(int n) {\n this.n = n;\n curr = 1;\n }\n\n // printFizz.run() outputs "fizz".\n public synchronized void fizz(Runnable printFizz) throws InterruptedException {\n while(curr <= n) {\n if (curr % 5 == 0 || curr % 3 != 0) {\n wait();\n continue;\n }\n printFizz.run();\n curr++;\n notifyAll();\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public synchronized void buzz(Runnable printBuzz) throws InterruptedException {\n while(curr <= n) {\n if (curr % 5 != 0 || curr % 3 == 0) {\n wait();\n continue;\n }\n printBuzz.run();\n curr++;\n notifyAll();\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public synchronized void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n while (curr <= n) {\n if (curr % 5 != 0 || curr % 3 != 0) {\n wait();\n continue;\n }\n printFizzBuzz.run();\n curr++;\n notifyAll();\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public synchronized void number(IntConsumer printNumber) throws InterruptedException {\n while (curr <= n) {\n if (curr % 5 == 0 || curr % 3 == 0) {\n wait();\n continue;\n }\n printNumber.accept(curr);\n curr++;\n notifyAll();\n }\n }\n}\n```\nRef: https://leetcode.com/problems/fizz-buzz-multithreaded/discuss/385395/Java-using-synchronized-with-short-explanation.
2
0
[]
0
fizz-buzz-multithreaded
[Java] Use Semaphore
java-use-semaphore-by-yuhwu-sn4d
\nclass FizzBuzz {\n private int n;\n private int number;\n private Semaphore fizzS;\n private Semaphore buzzS;\n private Semaphore fizzBuzzS;\n
yuhwu
NORMAL
2020-02-04T07:34:59.993932+00:00
2020-02-04T07:34:59.993985+00:00
426
false
```\nclass FizzBuzz {\n private int n;\n private int number;\n private Semaphore fizzS;\n private Semaphore buzzS;\n private Semaphore fizzBuzzS;\n private Semaphore numberS;\n public FizzBuzz(int n) {\n this.n = n;\n number = 0;\n fizzS = new Semaphore(0);\n buzzS = new Semaphore(0);\n fizzBuzzS = new Semaphore(0);\n numberS = new Semaphore(1);\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n for(int i=1; i<=(n/3-n/15); i++){\n fizzS.acquire();\n printFizz.run();\n numberS.release();\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n for(int i=1; i<=(n/5-n/15); i++){\n buzzS.acquire();\n printBuzz.run();\n numberS.release();\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n for(int i=1; i<=n/15; i++){\n fizzBuzzS.acquire();\n printFizzBuzz.run();\n numberS.release();\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n for(int num=1; num<=n; num++){\n numberS.acquire();\n if(num%15==0){\n fizzBuzzS.release();\n }\n else if(num%3==0){\n fizzS.release();\n }\n else if(num%5==0){\n buzzS.release();\n }\n else{\n printNumber.accept(num);\n numberS.release();\n }\n }\n }\n}\n```
2
0
[]
2
fizz-buzz-multithreaded
Python 3 using one Barrier
python-3-using-one-barrier-by-kangtastic-3ezg
Maintain a counter as an instance attribute and synchronize execution of the four threads using threading.Barrier(). Barrier() takes a Callable during initializ
kangtastic
NORMAL
2019-12-11T05:15:51.730498+00:00
2019-12-11T05:49:55.007612+00:00
432
false
Maintain a counter as an instance attribute and synchronize execution of the four threads using `threading.Barrier()`. `Barrier()` takes a `Callable` during initialization that will mutate object state immediately before all the threads are released.\n```\nimport threading\n\n\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n\n self.k = 0\n self.div_3 = None\n self.div_5 = None\n\n def step():\n self.k += 1\n self.div_3 = not self.k % 3\n self.div_5 = not self.k % 5\n\n self.sync = threading.Barrier(4, action=step)\n\n def _thread(self, printer, div_3=False, div_5=False):\n while self.k < self.n:\n self.sync.wait()\n if self.div_3 == div_3 and self.div_5 == div_5:\n printer()\n\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n self._thread(printFizz, div_3=True)\n\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n self._thread(printBuzz, div_5=True)\n\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n self._thread(printFizzBuzz, div_3=True, div_5=True)\n\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n self._thread(lambda: printNumber(self.k))\n```\nThis is the same idea as https://leetcode.com/problems/fizz-buzz-multithreaded/discuss/441036/Very-simple:-Python-Barrier()-94-100 but using constant space.\n
2
0
[]
0
fizz-buzz-multithreaded
Very simple: Python Barrier(), 94% / 100%
very-simple-python-barrier-94-100-by-zob-m2jf
We use a single primitive, threading.Barrier. Barrier(4) forces all four threads to count together: all threads pass the barrier if an only if all four threads
zobeebee
NORMAL
2019-11-30T20:47:09.642300+00:00
2019-11-30T21:11:44.588885+00:00
279
false
We use a single primitive, `threading.Barrier`. `Barrier(4)` forces all four threads to count together: all threads pass the barrier if an only if all four threads have reached it. There is one `Barrier` per integer we need to count. That\'s it.\n\n```\nfrom threading import Barrier\n\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.barriers = [Barrier(4)] * self.n\n\n def count(self, cond, fxn, arg=False):\n for j in range(self.n):\n self.barriers[j].wait()\n i = j + 1\n if cond(i):\n fxn(i) if arg else fxn()\n \n # printFizz() outputs "fizz"\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n self.count(\n lambda i: i % 3 == 0 and i % 5 != 0,\n printFizz\n )\n\n # printBuzz() outputs "buzz"\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n self.count(\n lambda i: i % 3 != 0 and i % 5 == 0,\n printBuzz\n )\n\n # printFizzBuzz() outputs "fizzbuzz"\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n self.count(\n lambda i: i % 3 == 0 and i % 5 == 0,\n printFizzBuzz\n )\n\n # printNumber(x) outputs "x", where x is an integer.\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n self.count(\n lambda i: i % 3 != 0 and i % 5 != 0,\n printNumber,\n True\n )\n```
2
0
[]
0
fizz-buzz-multithreaded
Python 99.17% time by cheating
python-9917-time-by-cheating-by-easytea-trub
Experimented with different python threading primitives, but performance were all consistently terrible. My guess is that underhanded solutions like these are s
easytea
NORMAL
2019-10-13T05:24:51.183498+00:00
2019-10-13T05:24:51.183544+00:00
434
false
Experimented with different python `threading` primitives, but performance were all consistently terrible. My guess is that underhanded solutions like these are skewing the runtime stats.\n\nCheating solution: store function references and run normal fizzbuzz once all functions are registered. Lock is still necessary to prevent double printing. \n\n```\nfrom threading import Lock\n\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.registered = 0\n self.lock = Lock()\n\n # printFizz() outputs "fizz"\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n self.printFizz = printFizz\n self.doFizzBuzz()\n\n # printBuzz() outputs "buzz"\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n self.printBuzz = printBuzz\n self.doFizzBuzz()\n\n # printFizzBuzz() outputs "fizzbuzz"\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n self.printFizzBuzz = printFizzBuzz\n self.doFizzBuzz()\n\n # printNumber(x) outputs "x", where x is an integer.\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n self.printNumber = printNumber\n self.doFizzBuzz()\n \n def doFizzBuzz(self):\n with self.lock:\n self.registered += 1\n if self.registered < 4:\n return\n \n for i in range(1, self.n+1):\n if i % 15 == 0:\n self.printFizzBuzz()\n elif i % 3 == 0:\n self.printFizz()\n elif i % 5 == 0:\n self.printBuzz()\n else:\n self.printNumber(i)\n```
2
0
[]
1
fizz-buzz-multithreaded
Java simple AtomicInteger solution without locks.
java-simple-atomicinteger-solution-witho-vg81
\nclass FizzBuzz {\n private int n;\n AtomicInteger cur = new AtomicInteger(1);\n\n public FizzBuzz(int n) {\n this.n = n;\n }\n\n // prin
todor91
NORMAL
2019-10-07T12:09:13.683717+00:00
2019-10-07T12:09:13.683754+00:00
401
false
```\nclass FizzBuzz {\n private int n;\n AtomicInteger cur = new AtomicInteger(1);\n\n public FizzBuzz(int n) {\n this.n = n;\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n while (true) {\n int x = cur.get();\n if (x > n) return;\n if (x % 3 == 0 && x % 5 != 0) {\n printFizz.run();\n cur.incrementAndGet();\n }\n Thread.sleep(1);\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n while (true) {\n int x = cur.get();\n if (x > n) return;\n if (x % 3 != 0 && x % 5 == 0) {\n printBuzz.run();\n cur.incrementAndGet();\n }\n Thread.sleep(1);\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n while (true) {\n int x = cur.get();\n if (x > n) return;\n if (x % 3 == 0 && x % 5 == 0) {\n printFizzBuzz.run();\n cur.incrementAndGet();\n }\n Thread.sleep(1);\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n while (true) {\n int x = cur.get();\n if (x > n) return;\n if (x % 3 != 0 && x % 5 != 0) {\n printNumber.accept(x);\n cur.incrementAndGet();\n }\n Thread.sleep(1);\n }\n }\n}\n```
2
1
[]
2
fizz-buzz-multithreaded
C implementation with pthread
c-implementation-with-pthread-by-kamanel-lk03
\ntypedef enum Status_s{NUM, THR, FIV, THRFIV} Status;\ntypedef struct {\n int n;\n int cur;\n Status s;\n pthread_mutex_t m;\n pthread_cond_t th
kamanelf
NORMAL
2019-10-03T22:20:36.095244+00:00
2019-10-03T22:20:36.095285+00:00
587
false
```\ntypedef enum Status_s{NUM, THR, FIV, THRFIV} Status;\ntypedef struct {\n int n;\n int cur;\n Status s;\n pthread_mutex_t m;\n pthread_cond_t th;\n pthread_cond_t fv;\n pthread_cond_t thfv;\n pthread_cond_t num;\n} FizzBuzz;\n\nFizzBuzz* fizzBuzzCreate(int n) {\n FizzBuzz* obj = (FizzBuzz*) malloc(sizeof(FizzBuzz));\n pthread_mutex_init(&obj->m, NULL);\n pthread_cond_init(&obj->th, NULL);\n pthread_cond_init(&obj->fv, NULL);\n pthread_cond_init(&obj->thfv, NULL);\n pthread_cond_init(&obj->num, NULL);\n \n obj->s = NUM;\n obj->cur = 1;\n obj->n = n;\n return obj;\n}\n// printFizz() outputs "fizz".\nvoid fizz(FizzBuzz* obj) {\n int i = 3;\n pthread_mutex_lock(&obj->m);\n while(i <= obj->n){\n while(obj->s != THR)\n pthread_cond_wait(&obj->th, &obj->m);\n printFizz();\n obj->s = NUM;\n pthread_cond_signal(&obj->num);\n i += 3;\n if(i % 5 == 0)\n i += 3;\n }\n pthread_mutex_unlock(&obj->m);\n}\n\n// printBuzz() outputs "buzz".\nvoid buzz(FizzBuzz* obj) {\n int i = 5;\n pthread_mutex_lock(&obj->m);\n while(i <= obj->n){\n while(obj->s != FIV)\n pthread_cond_wait(&obj->fv, &obj->m);\n printBuzz();\n obj->s = NUM;\n pthread_cond_signal(&obj->num);\n i += 5;\n if(i % 3 == 0)\n i += 5; \n }\n pthread_mutex_unlock(&obj->m);\n}\n\n// printFizzBuzz() outputs "fizzbuzz".\nvoid fizzbuzz(FizzBuzz* obj) {\n int i = 15;\n pthread_mutex_lock(&obj->m);\n while(i <= obj->n){\n while(obj->s != THRFIV)\n pthread_cond_wait(&obj->thfv, &obj->m);\n printFizzBuzz();\n obj->s = NUM;\n pthread_cond_signal(&obj->num);\n i += 15;\n }\n pthread_mutex_unlock(&obj->m);\n}\n\n// You may call global function `void printNumber(int x)`\n// to output "x", where x is an integer.\nvoid number(FizzBuzz* obj) {\n int i;\n pthread_mutex_lock(&obj->m);\n while(obj->cur <= obj->n){\n while(obj->s != NUM)\n pthread_cond_wait(&obj->num, &obj->m);\n if (obj->cur % 3 == 0 && obj->cur % 5 != 0) {\n obj->s = THR;\n pthread_cond_signal(&obj->th);\n }\n else if (obj->cur % 5 == 0 && obj->cur % 3 != 0) {\n obj->s = FIV;\n pthread_cond_signal(&obj->fv);\n }\n else if (obj->cur % 3 == 0 && obj->cur % 5 == 0) {\n obj->s = THRFIV;\n pthread_cond_signal(&obj->thfv);\n }\n else {\n printNumber(obj->cur);\n }\n obj->cur++;\n }\n pthread_mutex_unlock(&obj->m); \n}\n\nvoid fizzBuzzFree(FizzBuzz* obj) {\n pthread_mutex_destroy(&obj->m);\n pthread_cond_destroy(&obj->th);\n pthread_cond_destroy(&obj->fv);\n pthread_cond_destroy(&obj->thfv);\n pthread_cond_destroy(&obj->num);\n free(obj);\n}\n```
2
0
[]
0
fizz-buzz-multithreaded
Python solution using only threading.Lock (not Condition, Semaphore, or Event)
python-solution-using-only-threadinglock-18js
Uses threading.Lock\n\nNot very fast though. Got:\n\n runtime: 64 ms, faster than 27.89% of Python3 submissions\n memory usage: 16.4 MB, less than 100.00% of Py
butterscotchchip
NORMAL
2019-10-03T03:54:24.057162+00:00
2019-10-03T03:56:21.789062+00:00
302
false
Uses `threading.Lock`\n\nNot very fast though. Got:\n\n* runtime: 64 ms, faster than 27.89% of Python3 submissions\n* memory usage: 16.4 MB, less than 100.00% of Python3 submissions\n\n```python\nfrom threading import Lock\n\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.fizzLock = Lock() # div 3\n self.fizzLock.acquire()\n self.buzzLock = Lock() # div 5\n self.buzzLock.acquire()\n self.fizzBuzzLock = Lock() # div 3 and div 5\n self.fizzBuzzLock.acquire()\n self.numberLock = Lock() # else\n\n def _release(self, num):\n if num % 3 == 0 and num % 5 == 0:\n self.fizzBuzzLock.release()\n elif num % 3 == 0:\n self.fizzLock.release()\n elif num % 5 == 0:\n self.buzzLock.release()\n else:\n self.numberLock.release()\n\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n for i in range(1, self.n + 1):\n if i % 3 == 0 and i % 5 != 0:\n self.fizzLock.acquire()\n printFizz()\n self._release(i + 1)\n\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n for i in range(1, self.n + 1):\n if i % 3 != 0 and i % 5 == 0:\n self.buzzLock.acquire()\n printBuzz()\n self._release(i + 1)\n\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n for i in range(1, self.n + 1):\n if i % 3 == 0 and i % 5 == 0:\n self.fizzBuzzLock.acquire()\n printFizzBuzz()\n self._release(i + 1)\n\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n for i in range(1, self.n + 1):\n if i % 3 != 0 and i % 5 != 0:\n self.numberLock.acquire()\n printNumber(i)\n self._release(i + 1)\n```
2
0
[]
0
fizz-buzz-multithreaded
Python naive condition variable
python-naive-condition-variable-by-make_-gigc
~~~python\n\nfrom threading import Condition\nclass FizzBuzz:\n def init(self, n: int):\n self.n = n\n self.cur = 1\n self.cv = Conditio
make_up
NORMAL
2019-09-29T19:40:26.353323+00:00
2019-09-29T19:40:26.353381+00:00
408
false
~~~python\n\nfrom threading import Condition\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.cur = 1\n self.cv = Condition()\n\n def next(self):\n self.cur+=1\n self.cv.notify_all()\n \n # printFizz() outputs "fizz"\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n while 1:\n with self.cv:\n self.cv.wait_for(lambda : self.cur > self.n or (self.cur % 3 == 0 and self.cur%5 !=0))\n if self.cur > self.n:\n return\n printFizz()\n self.next()\n\n # printBuzz() outputs "buzz"\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n while 1:\n with self.cv:\n self.cv.wait_for(lambda : self.cur > self.n or (self.cur % 5 == 0 and self.cur%3 != 0))\n if self.cur > self.n:\n return\n printBuzz()\n self.next()\n \n\n # printFizzBuzz() outputs "fizzbuzz"\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n while 1:\n with self.cv:\n self.cv.wait_for(lambda : self.cur > self.n or (self.cur % 3 == 0 and self.cur%5 == 0))\n if self.cur > self.n:\n return\n printFizzBuzz()\n self.next()\n\n # printNumber(x) outputs "x", where x is an integer.\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n while 1:\n with self.cv:\n self.cv.wait_for(lambda : self.cur > self.n or (self.cur % 3 != 0 and self.cur%5 !=0))\n if self.cur > self.n:\n return\n printNumber(self.cur)\n self.next()\n~~~\nnaive and simple :)
2
0
[]
0