7

Don't iterate over the indices of a list only to then access the element at that index. Instead iterate directly over the elements of the list! Have a look at Loop Like A Native by Ned Halder. In the standard library module itertools there is the groupby function, which groups equal elements together. You can use this to make your code easier: from ...


6

Generation of prime numbers is suboptimal. Use a sieve of Erathosthenes. isPrime is highly suboptimal. You already generated an array of all necessary primes, so just binary search it. Breaking the loop in if(sumFromTo(cumulativeSums,start,end)>limit) break; looks like a bug. The intention is to loop by decreasing end, yet since the ...


5

On top of @Graipher's style recommendations, you should use better, more descriptive names to begin with. In this context, it's fairly clear what at least part of the intent of H and T are. H has to do with "heads"... but what about "heads"? I would name it something closer to head_streak, or something else descriptive. Especially with as short of lines as ...


4

Not much to say for such a simple algorithm. However there is an optimization that you could employ. Check for odd instead of even, then convert to even. Then divide by 2. At most this cuts your iterations by half. It would look like this: public int NumberOfSteps(int num) { int count = 0; while (num != 0) { if(num % 2 == 1) ...


4

I went a bit crazy about it just for fun, and found a solution that is much more efficient than a loop :) If you look at the bits as the game progresses, you can reframe the problem. Subtracting 1 from an odd number is flipping the right-most bit from 1 to 0. Dividing by 2 is shifting the bits 1 place to the right. Example in binary: 1001101 There are ...


4

Possibly not the best solution, but here's one that uses F# more extensively: let rec processProgram (i: int) (ops: int list) = match ops with | opCode :: aPos :: bPos :: outPos :: rest when opCode = 1 -> // add op code let a = ops |> List.item aPos let b = ops |> List.item bPos let complete = [opCode; aPos; bPos; ...


4

As noted in a comment, I think you've got a bug, but I'll do a pass over the code for style since it works for your test case at least. These are mostly minor style points rather than addressing the overall structure of the code; my goal is going to be to make the code easier to read without doing a full rewrite from scratch or changing the way it works. ...


3

Your answer should also be a template struct. It contains first and last element of type big_int but in the bubble _sort function it is constructed with template argument type T. template<class T> struct answer { std::size_t count; T first_element; T last_element; }; But actually maybe the structure Is redundant because first And last ...


3

Prime Generation As mentioned by vnp, use the Sieve of Eratosthenese. In that implementation, use a BitSet(1_000_000) for efficient memory usage during your sieve; a sieve for primes up to one million will only take 125 KB of memory. Keep the sieve around after you've generated your prime numbers, because it makes a very efficient \$O(1)\$ time complexity ...


3

You need to guard against a negative num, or else your algorithm will run infinitely (num = num - 1). Dividing 36 and 37 with 2 are both 18 with reminders of 0 and 1. So it should be possible to keep dividing by 2 and adding the reminder, in order to add 1 for odd and 0 for even numbers: public int Review(int num) { if (num == 0) return 0; int result =...


3

UPDATE: Second Review In my first review I said that your code may not be correct because you did not provide a pig latin specification, the algorithm used looked peculiar. I asked the you to post your pig latin specification. You did not do so. I found your pig latin specification anyway. Your code is not correct. The pig latin specification rules say ...


3

The line-too-long can be fixed by wrapping the long string. There are at least two obvious ways to do it. First, use a triple quoted string. This lets the string include span multiple lines. A possible problem is that the string now includes the extra spaces at the beginning of the second and third lines. However, those will get removed by the call to ...


3

Instead of the list-list value in var graph = new Dictionary<int, List<List<int>>>(); you could use a named tuple: var graph = new Dictionary<int, List<(int V, int W)>>(); foreach (var edge in times) { if (!graph.TryGetValue(edge[0], out var temp)) { temp = graph[edge[0]] = new List<(int V, int W)>(); } ...


3

if (graph.TryGetValue(candNode, out var node)) { foreach (var info in node) { _dist[info[0]] = Math.Min(_dist[info[0]], _dist[candNode]+info[1]); } }


2

Include the headers we need #include <string> #include <vector> Don't make unnecessary copies std::string longestSubstring(const std::string& digits) { Also, consider storing std::string_view objects internally, as these are much lighter than owning strings. Fix the bug I get a SIGABRT when I call with empty string as argument: ==...


2

My answer is an upgrade of Henrik's answer. (so it's a review of a review lol) Dividing an int by 2 is the same as shifting the bits 1 to the right. I'd expect a good compiler to make such optimizations automatically, but I think it's still worth mentioning. I got rid of the if statement at the start, which in most cases (non 0 input) is a waste of time. ...


2

There is no reason to use lists instead of arrays, new int[size] will give you an array full of 0s without any overhead. You can get away with creating only one array (leftMax) and then while computing the values of rightMax, instead of saving them into an array, complete the full calculation of how much to add to ans. Like this: public int ...


2

Here's some C# in accordance with my first suggestion of sorting the array and looping. public bool IsPossibleDivide(int[] nums, int k) { if (nums.Length % k != 0) { return false; } var dict = new Dictionary<int, int>(); foreach (var num in nums) { if (!dict.TryGetValue(num, out var value)) { ...


2

Missing-value logic This: try: counts[space] += count except: counts[space] = count has a few problems: A bare except is ill-advised; you probably want to be catching KeyError Avoid logic-by-exception; for instance: if space in counts: counts[space] += count else: counts[space] = count Do one better by calling setdefault: counts....


2

Overall, your code looks great. It's nicely structured, and having a well-defined answer type makes immediately clear what the question is about. At the bottom of the code, i=0 is missing some spaces. You can improve the speed of the bubble sort by 50% by not counting j from 0 to size but only from 0 to size - 1 - i, since the last few elements are already ...


2

Your ID is a long created from 2 ints, so you can fit both ints inside this one long side by side: long key = (long)nums[i] << 32 | i; You have a lot of unnecessary if statement evaluations. You could get rid of them by adding the first k elements from the array into the list in a separate loop, and then starting a second loop from i = k that can ...


2

Your code is pretty much perfect, the only problem is that you chose to sacrifice some performance in most cases (non 0 operands) for the sake of making the rare case faster. Here's a slight improvement based on the assumption that most of the times none of the operands will be 0. The trick is to keep it efficient in the case of 0 without wasting time on ...


1

A first simple clean up could be made here: | 1 -> let a = ops.[ops.[i+1]] let b = ops.[ops.[i+2]] ops.[ops.[i+3]] <- a + b i <- i + 4 | 2 -> let a = ops.[ops.[i+1]] let b = ops.[ops.[i+2]] ops.[ops.[i+3]] <- a * b i <- i + 4 The ...


1

You can optimize a bit by make it possible to step out of the first outer loop if the inner foreach-loop doesn't make any changes to dist in one iteration. Wouldn't it be possible to test for maxWait whenever you update dist[v] in the foreach-loop: { dist[v] = dist[u] + w; maxWait = Math.Max(maxWait, dist[v]); } This may og may not be an ...


1

Style Use CamalCase for class names, like class Amplifier. No need to explicitly extends object. When encountering unsupported opcode, raise an exception to kill the program immediately instead of printing an error message. It helps you discover bugs earlier. This is known as "fail fast". get_signal() should accept an Iterable instead of an Iterator. You ...


1

Just one remark: do not copy-paste code and then change one tiny bit of it. This indicates that you should create a method. What I mean is this: var newPoint = new CustomPoint(pointToProcess.Column, pointToProcess.Row + 1); grid[newPoint.Row, newPoint.Column] = 1; toPropagateInNextGeneration.Enqueue(newPoint); Those three lines are always the same, except ...


1

Code review: 1. You don't need to use u64, since the input data is all u8, so use Vec<u8> like the following code and parse all the input data in one line: fn main() { let s = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 ...


1

Thread safety getUrls() is modifying a collection (urlList.remove(i)), without any locking on the list. This is a potential thread safety problem. if multiple threads will attempt to access the method (and consequently modify the list), it is possible that the result will be wrong. Collection iteration your collection processing uses the old int index ...


1

This is a mere supplement to the other answers. First, there are several places in the code where you stack two if-statements on top of each other, because you want to check two different conditions before proceeding with an operation: if "Citizens of " in line: if "vaccination" not in line: ...


1

If r = number of rotations, a = int[] array, n = a.length, to rotate the array you need to move a[r to n] to the beginning of the array move a[0 to r] to end of array Also r can be reduced to r % n, as for every n rotations, the array repeats. Code: int[] result = new int[]; r = r % n; int count = 0; for(int i=r;i<n;i++){ ...


Only top voted, non community-wiki answers of a minimum length are eligible