New answers tagged

5

General remarks This using namespace std; is considered bad practice, see for example Why is “using namespace std” considered bad practice? on Stack Overflow. Consistent indenting and spacing increases the legibility of the code. Use curly braces for if/else blocks even if they consist only of a single statement. Enable all compiler warnings and fix ...


4

int day = 4; // Lets number the days of week from 1:7 && Sunday is the first day;;; note : 1 jan 1901 was Tue day The comment gets lost on the right edge of this narrow screen. The position of the comment implies that it is specific to the variable day, but that's not true of the first sentence. For working with % it would be less confusing to use ...


0

Fairly simple code. On thing that caught my eye was the isLeapYear method. I think the logic would be easier to understand by keeping it in one line: if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){ return true; }


0

the given answers would fail on some cases i.e [1,2,5,3,7,8,6,4] The solution has 2 steps: 1- is it Too chaotic (first loop) 2- move the element to its right position(second loop). function minimumBribes(q) { let min = 0; for(let i = 0; i < q.length; i++){ if(q[i] - (i + 1) > 2 ){ return console.log('Too chaotic'); } ...


1

Overall your implementation is fine, I would just suggest a few things: Naming - move_rings and helper are not very descriptive. Give them better names, and give them good docstrings (I like NumpyDoc, but personal preference is fine) move_rings shouldn't both do calculations and print to stdout. Instead, move_rings should return the information, and the ...


6

Review This review may sound a bit harsh, but bad habits are hard to break so I point them out. Use constants for variables that do not change. Don't create single use variables if they do not improve readability. Don't test for equality / inequality when the statement expression evaluates to a boolean. eg if(str.includes(target) === true){ is the same as ...


4

This looks good. I assume this results in correct answer. What you can use instead of converting to String and back to int is to use divideAndRemainder method with 10 since we need to treat this as a base 10 number. This method is available in BigInteger for situations like this. We can also directly use BigInteger constants such as TWO and TEN. ...


2

The solution makes sense, but like @dfhwze said, there are too many variables. As a future maintainer, I skim your solution and wonder what subtractLengths is, because it's ambiguous unless you move your eyes up to read more code to get the context. It doesn't read very smoothly. I would re-arrange it a bit to read more like this: str.lastIndexOf(target) +...


14

Your solution is far too complicated. It's also inefficient, because it uses functions .lastIndexOf() and .includes(), both of which analyze the entire str looking for target, whereas an optimal solution should look only starting at a known position at the end of str. Here are two simple solutions: function confirmEnding(str, target) { return str....


8

Review You have a bit too many variables to my taste, but that's not much of a problem. let lengthOfString = str.length; // is a variable that useful here? I would use const instead of let because the variables are only set once. The if-statements could be written with much less overhead. First, str.includes(target) === true could be written as str....


2

Welcome to Python! "Project Euler exists to encourage, challenge, and develop the skills and enjoyment of anyone with an interest in the fascinating world of mathematics." Like you, I went to Project Euler when I was learning Python as yet another language for my toolbox. Unfortunately, Project Euler is primarily a mathematics challenge site, not a ...


3

Observations Your algorithm uses a brute force with backtracking and history, which is a nice verification method to get all paths that don't include any cycles. As you can see, there are 2 solutions. Each solution requires to use a flow from one bottle to the other. One bottle is the main bottle that you fill with water and move its content to the other. ...


1

Without even doing anything clever regarding the algorithm, this: new_count = count + sum(stones[start:start + k]) merged_count = sum(stones[start:start + k]) can be cleaned up as merged_count = sum(stones[start:start + k]) new_count = merged_count + count


5

Your concept of "string" seems incomplete. I would look to firm up that definition and precisely match the need. Is "" a string? Do you want "valid identifiers" (/^[^\d\W]\w+$/) or "plausible ASCII words" (/^[A-Za-z]+$/) or just "not numbers" (!/ ^ ( [+-]? \d* \.? \d+ (?:[Ee][+-]?\d+)? ) $/x)? I like use warnings FATAL => 'all'; so that I don't ...


3

One thing I don't like is, that you merge "in place" - that is: the input linked lists change as a side effect. I would expect them to be untouched by the method. Consider to make a new linked list as the result. As a micro optimization you could probably spare a couple of ticks, if the input lists contain a lot of duplicate values, by iterate to the first ...


3

Overall the code is fairly easy to read and I don't spot any portability issues. Program design The module handling the allocation should also clean up after itself. If transferring this to a proper multi-file program, you would have a lib with a header/code pair like base64.h + base64.c. If there exists a function in base64.c that calls malloc, there ...


2

Here is a better algorithm to solve the problem. Let \$c(n, m)\$ be the number of ways to cover \$n\$ units with red blocks of minimum length \$m\$. Let \$c_r(n, m)\$ and \$c_b(n, m)\$ be the respective number of covers that ends with a red or black unit. We have $$ c(n, m) = c_r(n, m) + c_b(n, m)\label{f1}\tag{1} $$ Since any length-\$(n-1)\$ cover can be ...


1

There is not much to review here. This algorithm looks to be as good as it gets. I don't know how much value there is in nitpicking, but here I go: Review The summary tag should be used to describe a type or a type member. Use remarks to add supplemental information (xmldoc summary) -> put the challenge URL in a remarks tag, not in the summary. The ...


4

Firstly, I have to admit to not doing too much in the way of thinking up better variable names; in part because the algorithm was a little hard to follow without solving the problem myself. The spacing is all over the place: I'm not a PEP 8 purist but you have -= with a space before on one line, with a space after on another, and neither on a third. I fixed ...


1

Review I would return IEnumerable<IEnumerable<int>> rather than IList<IList<int>>. We don't want the caller to change the return value, only to iterate it. The two inner loops are almost exactly the same, except that the order of node.left and node.right gets swapped. This part I would refactor to get DRY code. You should use var a ...


4

The problem can be solved using math formulas, which will lead to an O(1) solution. But here I show another way to implement it, which is more efficient than a naive loop: def sum_multiples(n): return sum(range(0, n, 3)) + sum(range(0, n, 5)) - sum(range(0, n, 3*5)) Or alternatively, def sum_multiples(n): numbers = range(n) return sum(numbers[:...


5

The keyword sum is a built in function and you shouldn't name variables from within the reserved keywords. Here's a list of the most common used keywords which you shouldn't be naming any of your variables: [False, class, finally, is, return, None, continue, for, lambda, try, True, def, from, nonlocal, while, and, del, global, not, with, as, elif, if or,...


1

Laziness is a programmer virtue. These folks are spending more time on theory than doing it the lazy way would take in practice. The big problem here is you're doing a bunch of unnecessary work, particularly around storage. You're constantly appending to arrays for no apparent reason. You don't need the history of old numbers. Throw them away. ...


4

Project Euler problems generally can be computed with a calculator or manually. So, take a different approach: For ascending numbers, choose the transitions (digits 0-9; 9 transitions). For descending numbers, choose the transitions (initial zeros, digits 9-0; 10 transitions). Subtract those where initial zeros are followed only by a non-empty string of a ...


0

As 200_success says, you can look at how the numbers are derived to generate the numbers one by one. So rather than creating all the numbers and checking for an intersection, a simple algorithm is to look at a pentagon and hexagon number. If they are equal, you're done. If the pentagon number is larger than the hexagon number, then check whether the next ...


4

bouncy You did a good job by extracting the check for bouncyness to a separate function. Plus points for the docstringThe function itself can be a bit better: You can use the builtin sorted instead of list.sort. And since a string is an iterable too, you don't need the explicit casts to list You can also immediately return the result of the test number != ...


6

Speed up the bouncy function Since you are timing it, I guess speed if of essence. You are sorting a list twice, while you actually don't need to sort it at all. Instead, just check the digits two at a time and see that the difference never change sign. That is O(n) instead of O(n*log(n)) as sorting. Here's the code. Further changes are highlighted in ...


7

First of all, the question asks for the least number which the proportion is exactly 99%. Your code finds the first number that the proportion is more or equal to 99%. That is not quite right. Also, comparing floating-numbers is inaccurate and you should change it to integer comparision for exactness: bou * 100 == total * 99 Secondly, in the bouncy function,...


8

Code structure The most common and widely accepted structure found in Python scripts from a high-level point of view looks something like: # imports import ... # functions and classes, aka "library code" class Foo: ... def bar(batz): ... if __name__ == "__main__": # part that is supposed to be run as script ... Your code on the other hand ...


1

Python is a great choice of language for a challenge like this, mainly because of how easy it is to use sets. Basically, any challenge which states "find a number that matches these criteria" can be thought of as a set intersection problem. We want to find \$T \cap P \cap H\$, the intersection of triangular, pentagonal, and hexagonal numbers. Depending on ...


2

For a start, the code is missing several items of whitespace which PEP8 says it should have. There are automated PEP8 checkers which will tell you more. def _121_(N): #N - number of turns The Pythonic way to document the arguments is with a docstring. TOTAL_PROBABILITY = 0 This use of upper case is also not conventional. #Calclulate min number ...


0

You can easily check that H(n) = T(2n - 1). So all hexagonal numbers are triangular numbers, meaning we can ignore the triangular numbers altogether. To compute pentagonal numbers: Start with p = 1, dp = 4. To get the next pentagonal number, let p = p + dp, dp = dp + 3. To compute hexagonal numbers: Start with h = 1, dh = 5. To get the next hexagonal ...


1

Pedantically, none of the included headers are guaranteed to define std::size_t. It is (in principle) possible to implement those headers without defining that type, and we're required to include one of the headers that does define it (e.g. <cstddef>). We could avoid the push_back loop by using the std::copy() algorithm with a std::back_inserter as ...


7

The algorithm provided by the OP presumes that the array is important and preserves the original array. In addition, the displayed algorithm seeks an "instantaneous answer", as if the routine may be interrogated at any point to get that answer at the point in time. All that is important here is the output - a single number. Any other information used to ...


-1

x1: initial location of kangaroo 1 & x2: initial location of kangaroo 2 If it is given that x2 > x1 static String kangaroo(int x1, int v1, int x2, int v2) { int i; for(i=0; x1<x2; i++){ x1 = x1 + v1; x2 = x2 + v2; if(x1 == x2){ return "YES"; } } return "NO"; } Below solution covers ...


3

Why is read7 declared inline? You should only do this when it's needed as an optimization. (And it's particularly confusing when the function contains a static variable.) It's not necessary for is to be static. It should really be an argument to read7, so it can work on any istream. (In real code, buffer should also be a parameter to readN, but for this toy ...


0

(I wrote this months ago and forgot to post it, so it may no longer matter, but I'll post it anyway.) wordsArray is used for two different things. At first it's an array of words, but then it becomes an array of the words' values. This tends to be confusing, so it's better to use a new variable. The first loop in solution goes through a list and collects ...


5

Better complexity can be achieved using a heap. The input array can be organized into a min-heap in \$O(n)\$ time with negative integers dropped. Then the smallest number can be popped one by one until the target number is found. The complexity of this algorithm is \$O(n + klogn)\$ where \$k\$ is the insertion index of the target number among the sorted ...


8

I then tried putting the array into an arraylist, which reduces big-O since each object is "touched" only once, and I can use .Contains which is more efficient than iteration (not sure if that's true; I just sort of remember reading it somewhere). As was mentioned in the comments, for your purpose, there is no significant difference in performance between ...


1

Maybe the code is time efficient because you are lucky. Maybe the code is time efficient because you have good intuitions. This review is about moving toward luck playing less of a role in the performance of your code and/or reaching good intuitive conclusions by a more formal path. Top Down The code seems to be written bottom up from loops rather than top ...


5

Readability I'll focus this review around this statement: I hate it, it is ugly as hell and I feel like there should be more simpler and elegant .. You then suggest some object-oriented (visitor, composite) and functional (generator) patterns as ways to improve readability. I would indeed make the code adhere more to OO principles. Separation of ...


12

As this is a simple text transformation, the regular-expression module re is your friend. Processing letters one at a time is h-a-r-d. It would be simpler to process things one word at a time, as suggested by @Carcigenicate. The re.sub(pattern, repl, text, ...) function is interesting in that it allows you to specify a string or a function for the ...


41

Arithmetic Project Euler questions are meant to educate you about both mathematics and programming. It would be a good idea to understand what these triangular, pentagonal, and hexagonal numbers actually are, rather than blindly applying the given formulas. One performance improvement would be to find a way to generate successive elements of each sequence ...


18

First, at the top you list all the consonants out. There are two things that can be improved here: Since you only use it to check whether or not something is a consonant, it should be a set. It's much more efficient to to a membership lookup on a set than it is to do one on a list. Just replace the [] with {}. consonants = {'b', 'c', 'd', 'f', 'g', 'h', 'j'...


6

The main reason why your code is so slow is because your for loop in main spends most of the time checking for things that are logically impossible to be true. You have one million elements in every number group, every iteration of the for loop you are comparing one value to 2 million other values, when most of them can not be true. for _, terms in ...


13

Code limit = 1000000 triangle = [] pentagonal = [] hexagonal = [] triangle_number = [] Global variables do not help readability. What's the difference between triangle and triangle_number? Those names don't help me understand what they represent. class Shape: def __init__(self, term): self.term = term def triangle(self): return ...


8

I want to include it as a practice of getting used to writing solutions that require classes. No solution "requires" classes, although some situations are better represented with classes than with other techniques. In this particular case, Shape doesn't really need to exist - as you've already identified. Since each of those methods only depends on term, ...


4

Your implementation is close, but it can be a bit shorter. You correctly use two stacks, but you duplicate the code alternating between using the two. That's a bit of a waste of space. Instead, at the end of the first while loop, you can just assign nextLevel to currentLevel, create a new stack to nextLevel, and repeat: while (currentLeveL.Count > 0 |...


3

The way you have divided the problem into subproblems seems fine, so I'll comment on the way you have solved each subproblem. toDigits: With the strategy of using show to generate a string and then convert each element in that string back to a number, you could also use read :: Read a => String -> a which takes a string (remember that String is an ...


2

Variable names The few keystrokes you save by not having to type digits or permutations in full is not worth it. Just name em digits and permutations. For the import, just import itertools instead of from itertools import permutations as perm to_int To take a sum, reduce is seldom needed. You can explain this logic simpler like : def to_int(digits): ...


Top 50 recent answers are included