Tag Info

105

Updated answer in response to bounty: See Is that your final answer? at the end, and other changes - basically answer is significantly rewritten. To break your problem down in to requirements: you need a set of random numbers the numbers need to be unique the order of the returned numbers needs to be random Your current code indicates that the range of ...

53

Python is often described as a "batteries included" kind of language, and this is no exception. There's a module just for IP address manipulation and another module to generate random numbers. Put together, they do exactly what you want, in a way that's slightly more readable (IMO). For this example, I'll assume that the variable v contains either 4 or 6. ...

50

Apart from the compiler errors, implementation issues and code style suggestions others have pointed out, your shuffling algorithm is fundamentally flawed. Wikipedia explains it nicely: Similarly, always selecting i from the entire range of valid array indices on every iteration also produces a result which is biased, albeit less obviously so. This ...

43

Yes. I would go one step further and declare your functions as private static final, if possible. The combination of those three keywords means that the code would be unaffected by any instance variable, any superclass, or any subclass, and is also not callable by any code external to the class. Therefore, the compiler has enough of a hint that it could ...

40

Yes, there definitely is. You generate a collection of elements, mash it around and start pulling items out of it. A quick oneliner would be: Enumerable.Range(0,100).OrderBy(x => Guid.NewGuid()).Take(20); or alternatively Enumerable.Range(0,100).OrderBy(x => random.Next()).Take(20); This will give you 20 unique random values from the 0 to 100 ...

37

I see some things that I think could help you improve your code. Decompose your program into functions All of the logic here is in main in one rather long and dense chunk of code. It would be better to decompose this into separate functions. Check return values for errors The call to scanf can fail. You must check the return values to make sure they ...

36

Well, first off, why do you use a std::vector for a comparatively small sequence of known length? A raw array or std::array suffice and avoids any dynamic allocation. Next, avoid needless magic numbers. Use std::mt19937::state_size instead of manually specifying 624. Why do you use a lambda? A simple std::ref(source) suffices. The seeding itself looks ...

36

It would be worth your while to take a look at the implementation of random.sample to see how it works. (It's different from all 20 implementations in the post, and it will be instructive to figure out why.) In this answer I will confine myself to describing bugs (or ways in which the code in the post is inadequate in comparison with random.sample). 1. ...

29

In general First and foremost, you were asked to produce a program that generates a list of 10,000 numbers in random orders. You've added far too much complexity. There's no need for input or output (other than the final output). It's not a good immediate impression to heavily over-architect the program. I would be expecting a few lines of code (5-10), with ...

29

Bug Winning a 6/49 game is, of course, unlikely. The probability of any single ticket having all six numbers correct is $$\dfrac{1}{\binom{49}{6}} = \dfrac{6!\,(49-6)!}{49!} = \dfrac{1}{13983816}$$ But your code required 1.5×109 draws to produce a win, which is 100 times more than the expected 1.4×107 draws. Why? Because your comparison loop… // ...

28

There's a lot that can be improved here, so I hope that these suggestions are useful to you. Don't abuse using namespace std Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid. Make sure you have all required #includes The code uses rand() but doesn't #include <cstdlib>. It's important to make sure ...

26

Here are a few ideas about your code. Check for command line arguments The code fails with an exception if it's invoked with no command line arguments because it attempts to use argv[1] and there isn't any. I'd suggest that it would be nice to print a "usage" message if the user enters either an invalid or no argument. Use a list comprehension List ...

25

As this part of the question has been skipped so far, I'll take it: Do you think this is too hard? I think it is. Similarly to your game, in classic Mastermind, the player has to guess a combination of 4 non-unique coloured pegs, and each time is given a mark for the number of correct position and colour combinations. 64 = 1,296 possible combinations ...

24

Data structure Why are you using a LinkedList<char>? Linked lists involve a lot of overhead for each node. You know exactly how long the result should be, so why not write to a char[] array? Actually, you may want to consider returning the result as a char[] rather than as a string. A security-sensitive program may wish to wipe the contents of the ...

23

Your main() function desperately needs to be busted up, for multiple reasons: You use a lot of variables, all of them declared at the top of main(). A human mind is only good at keeping track of about 7 things at a time, so this code is hard to follow. It violates the Single Responsibility Principle, by parsing the command line, throwing the dice, keeping ...

23

From this Stack Overflow question : import random foo = ['a', 'b', 'c', 'd', 'e'] print(random.choice(foo)) In your case, def get_one_random_domain(domains): return domains[random.randint( 0, len(domains)-1)] becomes : def get_one_random_domain(domains): return random.choice(domains) and maybe removes the need for a function in the ...

22

Declaring such methods static can increase the readability of your code. For the reader it will be obvious that the method does not depend on the internal state of an instance of the class.

22

Nice idea. I really like what you've done, but some of your implementation can definitely be improved. Let's start with the JSON. Some of those arrays are not needed. You wrap each clothes item in [], there's no need for this as there's just one item in the array! In fact you should only be using arrays to group like items. I'm also going to get rid of your ...

22

Instead of using a List<int>, you should use an HashSet<int>. The HashSet<> prohibites multiple identical values. And the Add method returns a bool that indicates if the element was added to the list, this way you could change this code : public static List<int> GetRandomNumbers(int count) { List<int> randomNumbers = new ...

22

Break it down into one function that randomly repeats a character, and another function which randomly executes that function 50% of the time: function repeatRandomChar(str) { var i = Math.floor(Math.random() * str.length); return str.slice(0, i+1) + str.slice(i); } function randomTypo(str) { return Math.random() > 0.5 ? repeatRandomChar(str) : ...

20

Expanding on my comment. This is called a linear congruential generator. I used common parameters, which come from what I think is called the Minimal Standard. Other parameters can be chosen, but that's a tricky task. The sequence starts at the seed, reaches all other numbers between 0 and M-1, and then restarts once it reaches the seed again. It's pseudo-...

19

Speed and efficiency Just don't worry about it. You need to generate 1000 random numbers, and do a little bit of accounting work. Any reasonable solution, such as yours, will perform similarly. Types Why use an array of char to keep track of the number of occurrences? You're putting 1000 random numbers into 10 bins. What if one of those bins gets more ...

19

Consider the real world scenario a little bit. Does a car know what the speed limit is? Does it issue itself a fine if it's speeding? Or do the police do this? Assuming we're talking about the current state of things and not some near future world where cars do these things, police do. A more proper OOP approach would be to create a Policeman class with a ...

19

By making it more Pythonic for one: string.letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#\$%^&*()' let1 = random.choice(string.letters) let2 = random.choice(string.letters) let3 = random.choice(string.letters) let4 = random.choice(string.letters) let5 = random.choice(string.letters) let6 = random.choice(string.letters) let7 = random....

19

For someone not familiar with Python, you have picked pretty good habits. Not everyone uses functions or the if __name__ == '__main__' guard first try. That being said, I think it would make more sense to provide 2 functions instead of a single one: random_ipv4 and random_ipv6. You could also feed generator expressions to join. They are both faster to ...

18

If you are driven to get the absolute best performance, there are a number of things I would change. These changes will not necessarily improve the readability, but the performance will be best. First up, creating a new Random() each time is going to slow you down. This may well be about half of your time, in fact. I recommend a static version if you can be ...

18

General Feedback The good thing is that it is quite clear what your code does. You have for the most part clear variable names and not too much clutter. However I would change bananas1 to lucys_bananas and bananas2 to tracys_bananas. It seems you are familiar with another programming language. Python has a style guide PEP 8 which explains in excruciating ...

18

Review Don't use the main entry point to implement an algorithm. Create a method instead. Think about how to allow this method to be usable for all kinds of types, not just integers. You have implemented the algorithm for integers, yet you show an example with strings. When creating an algorithm, surely you have made some unit tests, at least for the happy ...

17

A standard technique is to setup an array of strings and index it with a random number: char * answers[] = { "Wrong!", "No", "Try again"}; .... if (guess_is_wrong) { int i = random() % (sizeof(answers) / sizeof(answers[0])); printf("%s\n", answer[i]); }

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