text
stringlengths
1
2.12k
source
dict
homework, database, cobol The grammar here is not great. Always remember: the goal of a diagnostic is to tell the user what to do to Win, not to advise him that he is Losing. Here, the verb "ensure" is too passive. Be direct, tell the user what to do! Please input a proper.... Or better, please specify, though perhaps "input" is part of the relevant computing culture here, and will be better understood. Also, DRY, this diagnostic appears multiple times. Create a symbolic constant, which you DISPLAY as needed. grammar It seems clear that OPEN-FILE, despite the misleading name, recognizes some context free grammar. Which one, however, is obscure. Recall that you can put an * asterisk in column 7, and then offer any helpful comments that might spring to mind. Perhaps an EBNF grammar, or a regex, would be a concise way of explaining what this procedure promises to do. output specification DISPLAY "0" I have no idea what to make of that. Perhaps there was some Requirements Document? Which you did not include in the OP submission? If there's a requirement to report success in this fashion, then the source or the review context should make that clear. helpful prompts DISPLAY "Please enter input" ... DISPLAY "Please enter input" ... DISPLAY "Please enter input" ... DISPLAY "Please enter input" From a UX perspective, these are just terrible. You should at least remind me that I should enter {init, write, read, del} input. But, I have to believe, surely there are differences in those inputs, which you might helpfully remind me of?
{ "domain": "codereview.stackexchange", "id": 45412, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "homework, database, cobol", "url": null }
homework, database, cobol automated tests I have no idea what the current state-of-the-art is for COBOL unit tests. But certainly no such tests were offered in the OP submission. A suite of passing tests improves our level of confidence that code works correctly for the regular and for the corner cases. It gives us the confidence to maintain and refactor existing code, so we can see that after an edit we still get a Green bar. It is an educational resource that assists in quicky onboarding new colleagues to the project. I am willing to believe this code achieves some of its design goals. Those goals did not appear in the OP submission so it is hard to be certain. I might be willing to delegate maintenance tasks on this code to a colleague, who is well versed in COBOL. I would definitely not be willing to maintain this code in its current form, absent tests and project documentation.
{ "domain": "codereview.stackexchange", "id": 45412, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "homework, database, cobol", "url": null }
python, strings Title: One Time Pad encryption in Python Question: I made this code to encrypt a string with the One Time Pad method. Is this pythonic code, and are there obvious ways I can improve? The program accepts a plaintext and can either accept an inputted key or generate one itself. It adds the key and plaintext character by character, keeping it within the bounds of the string. e.g. "This is an example" encoded with "Mary had a little lamb" gives "8rJ!~zCc9x~zPDPKzd". import string import secrets random_generator = secrets.SystemRandom() def clean_str(input_str: str, check_str: str | list) -> tuple[str, list[tuple[int, chr]]]: letters: list[str] = [] invalid: list[tuple[int, chr]] = [] for index, char in enumerate(input_str): if char in check_str: letters.append(char) else: invalid.append((index, char)) cleaned_str: str = "".join(letters) return cleaned_str, invalid def insert_invalid(text_without_invalid: str, insert_chars: list[tuple[int, chr]]) -> str: text_list: list[str] = list(text_without_invalid) for position, char in insert_chars: text_list.insert(position, char) return "".join(text_list) def encode(encode_string: str, code_str: str = "") -> tuple[str, str]: encode_string, invalid_chars = clean_str(encode_string, legal_chars) num_chars: int = len(encode_string) unencoded_chars: list[chr] = list(encode_string) if not code_str: rand_chars: list[chr] = [random_generator.choice(legal_chars) for _ in range(num_chars)] code_str = "".join(rand_chars) encode_nums: list[int] = [legal_chars.index(char) for char in code_str] encoded_str: str = "" for index, char in enumerate(unencoded_chars): num: int = legal_chars.index(char) num += encode_nums[index] num %= len(legal_chars) encrypted_char: chr = legal_chars[num] encoded_str += encrypted_char
{ "domain": "codereview.stackexchange", "id": 45413, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, strings", "url": null }
python, strings encoded_str = insert_invalid(encoded_str, invalid_chars) return encoded_str, code_str def decode(decode_string: str, code_string: str) -> str: decode_string, invalid_chars = clean_str(decode_string, legal_chars) string_nums: list[int] = [legal_chars.index(char) for char in decode_string] code_nums: list[int] = [legal_chars.index(char) for char in code_string] decoded_str: str = "" for string_num, code_num in zip(string_nums, code_nums): decode_num: int = string_num - code_num character: chr = legal_chars[decode_num] decoded_str += character decoded_str = insert_invalid(decoded_str, invalid_chars) return decoded_str
{ "domain": "codereview.stackexchange", "id": 45413, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, strings", "url": null }
python, strings decoded_str = insert_invalid(decoded_str, invalid_chars) return decoded_str def run(runMode: chr) -> None: if runMode == "e": chars = "".join(legal_chars) print(f"Only the following characters are accepted: {chars}\n") text: str = input("Enter the message to be encoded: ") code: str = "1" # Initialize with length 1 to allow empty inputs to mean "random encryption key" while len(text) > len(code) > 0: print("Enter an encryption key, or hit Enter to get a random one. ", end="") code = input("It must be longer than the message: ") encoded_message: str encryption_key: str encoded_message, encryption_key = encode(text, code) print(f"Original message: {text}") print(f"Encrypted message: {encoded_message}") print(f"Encryption key: {encryption_key}") else: text = input("Enter the message to be decoded: ") check_text = [char for char in text if char in legal_chars] cypher = input("Enter the cypher to decode with: ") while len(cypher) < len(check_text): print("Cypher too short") cypher = input("Enter the cypher to decode with: ") decoded_message = decode(text, cypher) print(f"Encrypted message: {text}") print(f"Decoded message: {decoded_message}") print(f"Encryption key: {cypher}") if __name__ == "__main__": legal_chars = [char for char in string.printable if char not in string.whitespace] legal_chars.append(" ") while True: mode = input("Do you want to decode or encode a message (d/e): ").lower() while mode not in ["d", "e"]: print("Enter 'e' to encode and 'd' to decode.") mode = input("Do you want to decode or encode message (d/e): ").lower() run(mode) Answer: true random random_generator = secrets.SystemRandom()
{ "domain": "codereview.stackexchange", "id": 45413, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, strings", "url": null }
python, strings Answer: true random random_generator = secrets.SystemRandom() Kudos, thank you for using the appropriate interface. (No Mersenne Twister or other PRNG.) DRY mode = input("Do you ... while ... mode = input("Do you ... It's worth drying this up a bit. Even if you change nothing else, at least extract that repeated prompt into a variable. This wants to be a tiny helper function. There are several ways to re-phrase the looping and the conditional. For example, you could loop while not valid_response. Then it's a matter of initializing with an invalid response. Similar remarks for your "Enter the cypher..." loop. OTOH, initializing code = "1" primed another loop very nicely. Consider making this CLI issue someone else's problem, by using typer in conjunction with typing.Literal, or by using ArgumentParser. chr vs str def run(runMode: chr) -> None: No, please don't do that. I'm a little surprised it sneaks past mypy 1.8.0 with no errors. It definitely fails hard at runtime when we tack on a @beartype decorator. We're looking for type str, here. Also, pep8 asked you nicely to spell it run_mode, and you ignored it. Probably mode would suffice. globals chars = "".join(legal_chars) Prefer to write a get_legal_chars() helper. Or pass it in. Or use a class and then this is self.legal_chars. OBOB code = input("It must be longer than the message: ")
{ "domain": "codereview.stackexchange", "id": 45413, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, strings", "url": null }
python, strings I don't understand that. You meant to explain the key must be at least as long as the message, right? Also, wouldn't you rather call the key key or otp or pad, instead of code? I would expect a code variable to maybe contain ciphertext. I guess in fairness, the trouble started with the misleading "Enter an encryption key" prompt. Names matter, they affect how we think about a problem. Choose them carefully. implicit typing I appreciate some of the annotations above, like text: str. We don't really need them, but it's not a bad habit to be in. Clearly mypy, and the Gentle Reader, can easily work out certain obvious types. encoded_message: str encryption_key: str This impresses me as going slightly overboard, and as visually distracting to the flow of the source code. Now, if we didn't have the (very nice!) -> tuple[str, str]: result annotation (in the same module!), it might be worthwhile to call out those types explicitly. Especially if mypy complained that it couldn't work out the proper type. But here? Nah. Type annotations are tool, an aid to comprehension and one way for avoidance or early detection of bugs. But use tools where they make sense. Don't feel like there's some software component that's making you do it everywhere. chr versus str unencoded_chars: list[chr] = list(encode_string) The identifier is perfect. But please annotate that (or rand_chars) as list[str]. This isn't C, nor Java. Yes, you are storing individual characters in that container. But each one is a python str object. For example, let's ask about the SPACE character. >>> type(chr(32)) <class 'str'> Yup, that character is definitely a string. standard terminology Cryptographers have standard terms to describe crypto concepts. Instead of encode_str + encoded_str, prefer cleartext + ciphertext. time complexity num: int = legal_chars.index(char)
{ "domain": "codereview.stackexchange", "id": 45413, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, strings", "url": null }
python, strings This is a moderately expensive lookup. You're asking the cPython interpreter to repeatedly do a linear scan of that string. Now, it is C code doing the looping, not interpreted bytecode, but still. Consider building a dict beforehand, so within the loop we'll see just O(1) constant time lookups. Similar remarks apply when your're building encode_nums. Anyway, kudos, the num += and num %= expressions are extremely clear, and I thank you for them. (I still have to mentally translate that encode_nums is really "the pad".) Similar remarks when decoding: string_nums: list[int] = [legal_chars.index(char) for char in decode_string] code_nums: list[int] = [legal_chars.index(char) for char in code_string] There's many ways to do this efficiently. As an alternative to dict, you might find str.maketrans() to be of interest. simple identifiers def insert_invalid(text_without_invalid: str, insert_chars: list[tuple[int, chr]]) -> ... Wow, that first parameter takes a moment to wrap your head around. Why? Because it ain't got no single negative one time, no no it's double negative. Humans have a tougher time with negated identifiers than with positive ones. Prefer valid_text here. And zomg is that final type annotation ever helpful, thank you so much. Perfect! The insertion algorithm is nice enough, it looks correct. But perhaps it, and the list of tuples, are fancier than needed? If you were to tackle this encryption task again, you might prefer to just leave (unencoded) bad characters in the middle of ciphertext as you iterate along. I do really appreciate that you broke this out as a separate helper, very nice. Hmmm, interesting, this helper has two callers, for the two directions. Cool. alignment print(f"Original message: {text}") print(f"Encrypted message: {encoded_message}") print(f"Encryption key: {encryption_key}")
{ "domain": "codereview.stackexchange", "id": 45413, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, strings", "url": null }
python, strings nit: If you insert just a handful of SPACE characters after : colons, then it should be visually apparent to the user that cleartext, ciphertext, and OTP all have the identical length. (Or it will be apparent how many characters from end of pad went unused.) tricky code character: chr = legal_chars[decode_num] The detail here is we might be chasing a negative index, and then the Right Thing will still happen. Consider calling this out in a # comment. Consider using explicit % modulo, for parallel construction with the encryption operation, so we have non-negative indexes. If someone has to maintain this code a few months down the road, or has to translate it to a non-python language, there's no need to leave them scratching their head about how this ever managed to work in the first place. automated tests "This is an example" encoded with "Mary had a little lamb" gives "8rJ!~zCc9x~zPDPKzd".
{ "domain": "codereview.stackexchange", "id": 45413, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, strings", "url": null }
python, strings Thank you for that. It would have been even nicer if wrapped up within a test suite. summary You clearly went to a lot of trouble to come up with well-considered identifiers, and to break out single responsibility helpers where needed. That is all for the good, keep it up! And in some cases those optional type annotations proved super helpful. I would say, outside of the signatures, don't go overboard with redundant type annotations. Often the derived type is pretty obvious, both to man and machine. Where it isn't, then by all means throw an extra annotation in there. You have a tendency to accept an iterable or a container (like str), and explode it out into a list. I predict that you soon will be comfortable enough with such loops and transformations that you will no longer feel a need to always name and create a new container for an existing container. Put another way: if there's a name for a concept in the Business Domain, then by all means introduce a suitably named temp var for it, but if not then maybe an unnamed intermediate expression suffices. practices for handling keying material The well-known downside of OTP is that, while it lets you send a giant message, now you have a giant pad to carry around and securely disclose to the recipient. And reusing the pad Would Be Bad. In the code and the review context I saw no warnings or advice about how to properly handle sensitive pad material. Typically we would generate "a lot" of pad, maybe hand it off in person, on a thumb drive, to the intended recipient before they get on a plane, and then send several "short" messages. We would take care not to exhaust the pad. Yes, the current code could support such a scenario, but it would be clumsy. We don't store the pad in a file, and there's currently no support for seeking to appropriate offset for the "next" portion of the pad that we should use. There's no support for storing, and then burning, portions of the pad, to help prevent accidental reuse.
{ "domain": "codereview.stackexchange", "id": 45413, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, strings", "url": null }
python, strings portions of the pad, to help prevent accidental reuse. A pure CLI approach might be more convenient, and more composable, than the current interactive prompting. So there's room for feature requests, if you want to keep playing with this.
{ "domain": "codereview.stackexchange", "id": 45413, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, strings", "url": null }
python, strings This codebase achieves its design goals. I would be willing to delegate or accept maintenance tasks on it.
{ "domain": "codereview.stackexchange", "id": 45413, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, strings", "url": null }
c++, algorithm, recursion, c++20, constrained-templates Title: A recursive_find_if_all Template Function Implementation in C++ Question: This is a follow-up question for recursive_any_of and recursive_none_of Template Functions Implementation in C++. I am trying to follow the suggestion of G. Sliepen's answer to implement recursive_find_if_all template function in this post. The experimental implementation recursive_find_if_all Template Function Implementation // recursive_find_if_all template function implementation template<class T, class Proj = std::identity, class UnaryPredicate> requires(std::invocable<Proj, T>) && (std::invocable<UnaryPredicate, T>) constexpr auto recursive_find_if_all(T&& value, UnaryPredicate&& p, Proj&& proj = {}) { return std::invoke(p, std::invoke(proj, value)); } template<std::ranges::input_range T, class Proj = std::identity, class UnaryPredicate> constexpr auto recursive_find_if_all(T& inputRange, UnaryPredicate&& p, Proj&& proj = {}) { for(auto&& element : inputRange) { if(recursive_find_if_all(element, std::forward<UnaryPredicate>(p), std::forward<Proj>(proj))) return true; } return false; } Full Testing Code The full testing code: // recursive_find_if_all Template Function Implementation in C++ #include <algorithm> #include <array> #include <chrono> #include <concepts> #include <deque> #include <execution> #include <exception> //#include <experimental/ranges/algorithm> #include <functional> #include <iostream> #include <ranges> #include <string> #include <utility> #include <vector> // is_reservable concept template<class T> concept is_reservable = requires(T input) { input.reserve(1); }; // is_sized concept, https://codereview.stackexchange.com/a/283581/231235 template<class T> concept is_sized = requires(T x) { std::size(x); }; template<typename T> concept is_summable = requires(T x) { x + x; }; // recursive_unwrap_type_t struct implementation template<std::size_t, typename, typename...> struct recursive_unwrap_type { };
{ "domain": "codereview.stackexchange", "id": 45414, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, recursion, c++20, constrained-templates", "url": null }
c++, algorithm, recursion, c++20, constrained-templates template<class...Ts1, template<class...>class Container1, typename... Ts> struct recursive_unwrap_type<1, Container1<Ts1...>, Ts...> { using type = std::ranges::range_value_t<Container1<Ts1...>>; }; template<std::size_t unwrap_level, class...Ts1, template<class...>class Container1, typename... Ts> requires ( std::ranges::input_range<Container1<Ts1...>> && requires { typename recursive_unwrap_type< unwrap_level - 1, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges struct recursive_unwrap_type<unwrap_level, Container1<Ts1...>, Ts...> { using type = typename recursive_unwrap_type< unwrap_level - 1, std::ranges::range_value_t<Container1<Ts1...>> >::type; }; template<std::size_t unwrap_level, typename T1, typename... Ts> using recursive_unwrap_type_t = typename recursive_unwrap_type<unwrap_level, T1, Ts...>::type; // recursive_variadic_invoke_result_t implementation template<std::size_t, typename, typename, typename...> struct recursive_variadic_invoke_result { }; template<typename F, class...Ts1, template<class...>class Container1, typename... Ts> struct recursive_variadic_invoke_result<1, F, Container1<Ts1...>, Ts...> { using type = Container1<std::invoke_result_t<F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>...>>; };
{ "domain": "codereview.stackexchange", "id": 45414, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, recursion, c++20, constrained-templates", "url": null }
c++, algorithm, recursion, c++20, constrained-templates template<std::size_t unwrap_level, typename F, class...Ts1, template<class...>class Container1, typename... Ts> requires ( std::ranges::input_range<Container1<Ts1...>> && requires { typename recursive_variadic_invoke_result< unwrap_level - 1, F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges struct recursive_variadic_invoke_result<unwrap_level, F, Container1<Ts1...>, Ts...> { using type = Container1< typename recursive_variadic_invoke_result< unwrap_level - 1, F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>... >::type>; }; template<std::size_t unwrap_level, typename F, typename T1, typename... Ts> using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result<unwrap_level, F, T1, Ts...>::type; // recursive_array_invoke_result implementation template<std::size_t, typename, typename, typename...> struct recursive_array_invoke_result { }; template< typename F, template<class, std::size_t> class Container, typename T, std::size_t N> struct recursive_array_invoke_result<1, F, Container<T, N>> { using type = Container< std::invoke_result_t<F, std::ranges::range_value_t<Container<T, N>>>, N>; };
{ "domain": "codereview.stackexchange", "id": 45414, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, recursion, c++20, constrained-templates", "url": null }
c++, algorithm, recursion, c++20, constrained-templates template< std::size_t unwrap_level, typename F, template<class, std::size_t> class Container, typename T, std::size_t N> requires ( std::ranges::input_range<Container<T, N>> && requires { typename recursive_array_invoke_result< unwrap_level - 1, F, std::ranges::range_value_t<Container<T, N>>>::type; }) // The rest arguments are ranges struct recursive_array_invoke_result<unwrap_level, F, Container<T, N>> { using type = Container< typename recursive_array_invoke_result< unwrap_level - 1, F, std::ranges::range_value_t<Container<T, N>> >::type, N>; }; template< std::size_t unwrap_level, typename F, template<class, std::size_t> class Container, typename T, std::size_t N> using recursive_array_invoke_result_t = typename recursive_array_invoke_result<unwrap_level, F, Container<T, N>>::type; // recursive_array_unwrap_type struct implementation, https://stackoverflow.com/a/76347485/6667035 template<std::size_t, typename> struct recursive_array_unwrap_type { }; template<template<class, std::size_t> class Container, typename T, std::size_t N> struct recursive_array_unwrap_type<1, Container<T, N>> { using type = std::ranges::range_value_t<Container<T, N>>; };
{ "domain": "codereview.stackexchange", "id": 45414, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, recursion, c++20, constrained-templates", "url": null }
c++, algorithm, recursion, c++20, constrained-templates template<std::size_t unwrap_level, template<class, std::size_t> class Container, typename T, std::size_t N> requires ( std::ranges::input_range<Container<T, N>> && requires { typename recursive_array_unwrap_type< unwrap_level - 1, std::ranges::range_value_t<Container<T, N>>>::type; }) // The rest arguments are ranges struct recursive_array_unwrap_type<unwrap_level, Container<T, N>> { using type = typename recursive_array_unwrap_type< unwrap_level - 1, std::ranges::range_value_t<Container<T, N>> >::type; }; template<std::size_t unwrap_level, class Container> using recursive_array_unwrap_type_t = typename recursive_array_unwrap_type<unwrap_level, Container>::type; // https://codereview.stackexchange.com/a/253039/231235 template<template<class...> class Container = std::vector, std::size_t dim, class T> constexpr auto n_dim_container_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { return Container(times, n_dim_container_generator<Container, dim - 1, T>(input, times)); } } template<std::size_t dim, std::size_t times, class T> constexpr auto n_dim_array_generator(T input) { if constexpr (dim == 0) { return input; } else { std::array<decltype(n_dim_array_generator<dim - 1, times>(input)), times> output; for (size_t i = 0; i < times; i++) { output[i] = n_dim_array_generator<dim - 1, times>(input); } return output; } } // recursive_depth function implementation template<typename T> constexpr std::size_t recursive_depth() { return std::size_t{0}; } template<std::ranges::input_range Range> constexpr std::size_t recursive_depth() { return recursive_depth<std::ranges::range_value_t<Range>>() + std::size_t{1}; }
{ "domain": "codereview.stackexchange", "id": 45414, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, recursion, c++20, constrained-templates", "url": null }
c++, algorithm, recursion, c++20, constrained-templates // recursive_depth function implementation with target type template<typename T_Base, typename T> constexpr std::size_t recursive_depth() { return std::size_t{0}; } template<typename T_Base, std::ranges::input_range Range> requires (!std::same_as<Range, T_Base>) constexpr std::size_t recursive_depth() { return recursive_depth<T_Base, std::ranges::range_value_t<Range>>() + std::size_t{1}; } /* recursive_foreach_all template function performs specific function on input container exhaustively https://codereview.stackexchange.com/a/286525/231235 */ namespace impl { template<class F, class Proj = std::identity> struct recursive_for_each_state { F f; Proj proj; }; // recursive_foreach_all template function implementation template<class T, class State> requires (recursive_depth<T>() == 0) constexpr void recursive_foreach_all(T& value, State& state) { std::invoke(state.f, std::invoke(state.proj, value)); } template<class T, class State> requires (recursive_depth<T>() != 0) constexpr void recursive_foreach_all(T& inputRange, State& state) { for (auto& item: inputRange) impl::recursive_foreach_all(item, state); } // recursive_reverse_foreach_all template function implementation template<class T, class State> requires (recursive_depth<T>() == 0) constexpr void recursive_reverse_foreach_all(T& value, State& state) { std::invoke(state.f, std::invoke(state.proj, value)); } template<class T, class State> requires (recursive_depth<T>() != 0) constexpr void recursive_reverse_foreach_all(T& inputRange, State& state) { for (auto& item: inputRange | std::views::reverse) impl::recursive_reverse_foreach_all(item, state); } }
{ "domain": "codereview.stackexchange", "id": 45414, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, recursion, c++20, constrained-templates", "url": null }
c++, algorithm, recursion, c++20, constrained-templates template<class T, class Proj = std::identity, class F> constexpr auto recursive_foreach_all(T& inputRange, F f, Proj proj = {}) { impl::recursive_for_each_state state(std::move(f), std::move(proj)); impl::recursive_foreach_all(inputRange, state); return std::make_pair(inputRange.end(), std::move(state.f)); } template<class T, class Proj = std::identity, class F> constexpr auto recursive_reverse_foreach_all(T& inputRange, F f, Proj proj = {}) { impl::recursive_for_each_state state(std::move(f), std::move(proj)); impl::recursive_reverse_foreach_all(inputRange, state); return std::make_pair(inputRange.end(), std::move(state.f)); } template<class T, class I, class F> constexpr auto recursive_fold_left_all(const T& inputRange, I init, F f) { recursive_foreach_all(inputRange, [&](auto& value) { init = std::invoke(f, init, value); }); return init; } template<class T, class I, class F> constexpr auto recursive_fold_right_all(const T& inputRange, I init, F f) { recursive_reverse_foreach_all(inputRange, [&](auto& value) { init = std::invoke(f, value, init); }); return init; } // recursive_count_if template function implementation template<class T, std::invocable<T> Pred> requires (recursive_depth<T>() == 0) constexpr std::size_t recursive_count_if_all(const T& input, const Pred& predicate) { return predicate(input) ? std::size_t{1} : std::size_t{0}; } template<std::ranges::input_range Range, class Pred> requires (recursive_depth<Range>() != 0) constexpr auto recursive_count_if_all(const Range& input, const Pred& predicate) { return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto&& element) { return recursive_count_if_all(element, predicate); }); }
{ "domain": "codereview.stackexchange", "id": 45414, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, recursion, c++20, constrained-templates", "url": null }
c++, algorithm, recursion, c++20, constrained-templates template<std::size_t unwrap_level, class T, class Pred> requires(unwrap_level <= recursive_depth<T>()) constexpr auto recursive_count_if(const T& input, const Pred& predicate) { if constexpr (unwrap_level > 0) { return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto&& element) { return recursive_count_if<unwrap_level - 1>(element, predicate); }); } else { return predicate(input) ? 1 : 0; } } /* recursive_all_of template function implementation */ template<class T, class Proj = std::identity, class UnaryPredicate> requires(std::invocable<Proj, T>) && (std::invocable<UnaryPredicate, T>) constexpr auto recursive_all_of(T&& value, UnaryPredicate p, Proj proj = {}) { return std::invoke(p, std::invoke(proj, value)); } template<std::ranges::input_range T, class Proj = std::identity, class UnaryPredicate> constexpr auto recursive_all_of(T& inputRange, UnaryPredicate&& p, Proj proj = {}) { return std::ranges::all_of(inputRange, [&](auto&& range) { return recursive_all_of(range, std::forward<UnaryPredicate>(p), proj); }, proj); } // recursive_find_if_all template function implementation template<class T, class Proj = std::identity, class UnaryPredicate> requires(std::invocable<Proj, T>) && (std::invocable<UnaryPredicate, T>) constexpr auto recursive_find_if_all(T&& value, UnaryPredicate&& p, Proj&& proj = {}) { return std::invoke(p, std::invoke(proj, value)); } template<std::ranges::input_range T, class Proj = std::identity, class UnaryPredicate> constexpr auto recursive_find_if_all(T& inputRange, UnaryPredicate&& p, Proj&& proj = {}) { for(auto&& element : inputRange) { if(recursive_find_if_all(element, std::forward<UnaryPredicate>(p), std::forward<Proj>(proj))) return true; } return false; }
{ "domain": "codereview.stackexchange", "id": 45414, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, recursion, c++20, constrained-templates", "url": null }
c++, algorithm, recursion, c++20, constrained-templates // recursive_any_of template function implementation template<class T, class Proj = std::identity, class UnaryPredicate> constexpr auto recursive_any_of(T&& value, UnaryPredicate&& p, Proj&& proj = {}) { return recursive_find_if_all(value, p, proj); } // recursive_none_of template function implementation template<class T, class Proj = std::identity, class UnaryPredicate> constexpr auto recursive_none_of(T&& value, UnaryPredicate&& p, Proj&& proj = {}) { return !recursive_any_of(value, p, proj); } template<std::ranges::input_range T> constexpr auto recursive_print(const T& input, const int level = 0) { T output = input; std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl; std::transform(input.cbegin(), input.cend(), output.begin(), [level](auto&& x) { std::cout << std::string(level, ' ') << x << std::endl; return x; } ); return output; } template<std::ranges::input_range T> requires (std::ranges::input_range<std::ranges::range_value_t<T>>) constexpr T recursive_print(const T& input, const int level = 0) { T output = input; std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl; std::ranges::transform(std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output), [level](auto&& element) { return recursive_print(element, level + 1); } ); return output; } void recursive_find_if_all_tests() { std::cout << "***recursive_find_if_all_tests function***\n";
{ "domain": "codereview.stackexchange", "id": 45414, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, recursion, c++20, constrained-templates", "url": null }
c++, algorithm, recursion, c++20, constrained-templates auto test_vectors_1 = n_dim_container_generator<std::vector, 4, int>(1, 3); test_vectors_1[1][0][0][0] = 3; std::cout << "Play with test_vectors_1:\n"; if(recursive_find_if_all(test_vectors_1, [](int i) { return i == 1; })) std::cout << "1 is found in test_vectors_1\n"; if(recursive_find_if_all(test_vectors_1, [](int i) { return i == 2; })) std::cout << "2 is found in test_vectors_1\n"; if(recursive_find_if_all(test_vectors_1, [](int i) { return i == 3; })) std::cout << "3 is found in test_vectors_1\n"; std::cout << "Projection Tests\n"; if(recursive_find_if_all(test_vectors_1, [](int i) { return i == 1; }, [](int i) { return i + 1; })) std::cout << "1 is found in test_vectors_1 after projection\n"; if(recursive_find_if_all(test_vectors_1, [](int i) { return i == 2; }, [](int i) { return i + 1; })) std::cout << "2 is found in test_vectors_1 after projection\n"; } void recursive_any_of_tests() { std::cout << "***recursive_any_of_tests function***\n"; auto test_vectors_1 = n_dim_container_generator<std::vector, 4, int>(1, 3); test_vectors_1[0][0][0][0] = 3; std::cout << "Play with test_vectors_1:\n"; if (recursive_any_of(test_vectors_1, [](int i) { return i == 2; })) std::cout << "2 is one of the elements in test_vectors_1\n"; if (recursive_any_of(test_vectors_1, [](int i) { return i == 3; })) std::cout << "3 is one of the elements in test_vectors_1\n";
{ "domain": "codereview.stackexchange", "id": 45414, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, recursion, c++20, constrained-templates", "url": null }
c++, algorithm, recursion, c++20, constrained-templates std::cout << "Projection Tests\n"; if(recursive_any_of(test_vectors_1, [](int i) { return i == 1; }, [](int i) { return i + 1; })) std::cout << "1 is one of the elements in test_vectors_1 after projection\n"; if(recursive_any_of(test_vectors_1, [](int i) { return i == 2; }, [](int i) { return i + 1; })) std::cout << "2 is one of the elements in test_vectors_1 after projection\n"; } void recursive_none_of_tests() { std::cout << "***recursive_none_of_tests function***\n"; auto test_vectors_1 = n_dim_container_generator<std::vector, 4, int>(1, 3); test_vectors_1[0][0][0][0] = 3; std::cout << "Play with test_vectors_1:\n"; if (recursive_none_of(test_vectors_1, [](int i) { return i == 0; })) std::cout << "None of the elements in test_vectors_1 is 0\n"; std::cout << "Projection Tests\n"; if(recursive_none_of(test_vectors_1, [](int i) { return i == 0; }, [](int i) { return i + 1; })) std::cout << "None of the elements in test_vectors_1 is 0 after projection\n"; if(recursive_none_of(test_vectors_1, [](int i) { return i == 1; }, [](int i) { return i + 1; })) std::cout << "None of the elements in test_vectors_1 is 1 after projection\n"; if(recursive_none_of(test_vectors_1, [](int i) { return i == 2; }, [](int i) { return i + 1; })) std::cout << "None of the elements in test_vectors_1 is 2 after projection\n"; }
{ "domain": "codereview.stackexchange", "id": 45414, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, recursion, c++20, constrained-templates", "url": null }
c++, algorithm, recursion, c++20, constrained-templates int main() { auto start = std::chrono::system_clock::now(); recursive_find_if_all_tests(); recursive_any_of_tests(); recursive_none_of_tests(); auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::time_t end_time = std::chrono::system_clock::to_time_t(end); std::cout << "Computation finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << '\n'; return 0; } The output of the test code above: ***recursive_find_if_all_tests function*** Play with test_vectors_1: 1 is found in test_vectors_1 3 is found in test_vectors_1 Projection Tests 2 is found in test_vectors_1 after projection ***recursive_any_of_tests function*** Play with test_vectors_1: 3 is one of the elements in test_vectors_1 Projection Tests 2 is one of the elements in test_vectors_1 after projection ***recursive_none_of_tests function*** Play with test_vectors_1: None of the elements in test_vectors_1 is 0 Projection Tests None of the elements in test_vectors_1 is 0 after projection None of the elements in test_vectors_1 is 1 after projection Computation finished at Tue Jan 23 13:11:35 2024 elapsed time: 0.0013986 Godbolt link is here. All suggestions are welcome. The summary information: Which question it is a follow-up to? recursive_any_of and recursive_none_of Template Functions Implementation in C++ What changes has been made in the code since last question? I am trying to implement recursive_find_if_all template function in this post. Why a new review is being asked for? Please review the recursive_find_if_all template function. In this version, the techniques including early termination are performed.
{ "domain": "codereview.stackexchange", "id": 45414, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, recursion, c++20, constrained-templates", "url": null }
c++, algorithm, recursion, c++20, constrained-templates Answer: The problem seems so simple, and at first glance the implementation looks OK. However, looks can be deceiving; there are actually lots of issues with this code. Never std::forward() the same object multiple times You are calling std::forward() multiple times on the same p and proj. This will result in undefined behavior if p and/or proj are rvalues, as then it will be equivalent to std::moveing from them multiple times. Just omit std::forward(). Also note that std::ranges::find_if() takes the predicate and projection by value. You could do that too, but then you might be making lots of copies if the predicate and/or projection have state, which is inefficient and might not be what the caller expects. Implement recursive algorithms using their non-recursive counterparts You should be able to use std::ranges::find_if() to build your recursive version. In fact, most recursive algorithms you have written so far do or can use the following pattern for the recursing case: template<std::ranges::some_range R, class Pred, …> auto recursive_algorithm(R&& r, Pred p, …) { return std::non_recursive_algorithm(r, [&](auto& element) { return recursive_algorithm(element, p, …); }); } Some minor changes to the pattern are necessary depending on the exact algorithm you are implementing. So for finding, you could write: template<std::ranges::input_range T, class Proj = std::identity, class UnaryPredicate> constexpr auto recursive_find_if_all(T&& inputRange, UnaryPredicate&& p, Proj&& proj = {}) { return std::ranges::find_if(inputRange, [&](auto& element) { return recursive_find_if_all(element, p, proj); }) != std::ranges::end(inputRange); } The requires clause is incorrect You wrote: requires(std::invocable<Proj, T>) && (std::invocable<UnaryPredicate, T>)
{ "domain": "codereview.stackexchange", "id": 45414, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, recursion, c++20, constrained-templates", "url": null }
c++, algorithm, recursion, c++20, constrained-templates However, the predicate will not be applied directly to a T, but rather to the projection of a T. So you should instead do something like: requires(std::invocable<UnaryPredicate, std::invoke_result_t<Proj, T>>) However, that is not the only issue. Consider that the caller might not actually know what the value type of the innermost range is, for example because the caller might be some other generic algorithm you want to apply on top of recursive_find_if_all(). So they might use a generic lambda as a predicate: bool contains_zeroes(auto&& range) { return recursive_find_if_all(range, [](auto& value){ return value == 0; }); } The above algorithm will work with integers, floating point numbers, complex numbers and potentially lots of other types. But the problem is that the lambda accepts any type of value, so it will match range types as well. That means it will immediately invoke the non-recursing version of recursive_find_if_all(), which is very likely not what you want. Constraining the recursing version as well will help here. Other issues
{ "domain": "codereview.stackexchange", "id": 45414, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, recursion, c++20, constrained-templates", "url": null }
c++, algorithm, recursion, c++20, constrained-templates Your recursing version of recursive_find_if_all() takes inputRange by lvalue reference, whereas the non-recursing one takes it by forwarding reference. They should all take the range by forwarding reference (just like the STL algorithms do). The predicate does not have to return a bool, as long as it returns something that can be explicitly cast to a bool. Because you use auto return type for both recursing and non-recursing versions, it can be that for some inputs, the result type of recursive_find_if_all() will be a bool, but for other inputs it could be a different type, even if the exact same predicate is used. There is no requires clause on the recursing version. If you pass in an incorrect predicate or projection, then while eventually it will hit the requires clause of the non-recursing version, that will result in a very complicated error message. Putting one on the recursing version as well will result in a much better error message. Your test suite is evidently still not comprehensive enough, as it didn't catch some of the issues I've mentioned. Naming: recursive_find_if_all() makes it sounds like it tries to "find if all" items match the predicate. Maybe just recursive_find_if()?
{ "domain": "codereview.stackexchange", "id": 45414, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, recursion, c++20, constrained-templates", "url": null }
javascript, mysql, node.js, express.js Title: Consuming sharded database using node.js Question: I think the only big improvement that can be made is to check which shard to query based on the userIds of the followed users. One easy way is to check the last number of each userId (0,1,2,3,4,5,6,7,8,9) and then find which shard I need to query if I have 10. Besides that is there anything wrong? I am wondering if it makes sense to call the shards in a for loop, or there's a way to call it once and let it get handled by a library. const express = require('express'); const mysql = require('mysql2/promise'); const app = express(); const port = 3000; // Replace with your actual database connection details const shardConfigs = [ { host: 'shard1_host', user: 'shard1_user', password: 'shard1_password', database: 'shard1_database', }, { host: 'shard2_host', user: 'shard2_user', password: 'shard2_password', database: 'shard2_database', }, // Add configurations for other shards as needed ]; // Create connections for each shard const shardConnections = shardConfigs.map(config => mysql.createConnection(config)); app.get('/user/feed/:userId', async (req, res) => { try { const userId = req.params.userId; // Step 1: Identify Sharded Database Shard (Hash-based Strategy) const selectedShardIndex = userId % shardConfigs.length; const selectedShardConnection = shardConnections[selectedShardIndex]; // Step 2: Query User's Followings const followingQuery = 'SELECT followed_user_id FROM followers WHERE follower_user_id = ?'; const [followingRows] = await selectedShardConnection.execute(followingQuery, [userId]); const followingUsers = followingRows.map(row => row.followed_user_id);
{ "domain": "codereview.stackexchange", "id": 45415, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, mysql, node.js, express.js", "url": null }
javascript, mysql, node.js, express.js // Step 3: Retrieve Tweets from Followed Users const tweets = []; for (const shardConnection of shardConnections) { const tweetsQuery = 'SELECT * FROM tweets WHERE user_id IN (?) ORDER BY timestamp DESC'; const [shardTweets] = await shardConnection.execute(tweetsQuery, [followingUsers]); tweets.push(...shardTweets); } // Step 4: Sort and Combine Tweets const combinedTweets = tweets.sort((a, b) => b.timestamp - a.timestamp); // Step 5: Limit and Paginate // Add logic here to limit the number of tweets returned, implement pagination if needed // Step 6: Return the Feed to the User Interface const feedData = combinedTweets.map(tweet => ({ tweet_id: tweet.tweet_id, user_id: tweet.user_id, content: tweet.content, })); res.json({ feed: feedData }); } catch (error) { console.error(error); res.status(500).json({ error: 'Internal Server Error' }); } }); app.listen(port, () => { console.log(`Server is running at http://localhost:${port}`); }); Answer: You're using mysql.createConnection(config) inside a map function which is synchronous while mysql.createConnection is asynchronous and returns a Promise thus you might end up with a Promise object instead of a connection object in shardConnections. You should await these connections inside an async function before starting your server. async function initShardConnections() { for (let i = 0; i < shardConfigs.length; i++) { shardConnections[i] = await mysql.createConnection(shardConfigs[i]); } } // Call this function before starting your server initShardConnections().then(() => { app.listen(port, () => { console.log(`Server is running at http://localhost:${port}`); }); });
{ "domain": "codereview.stackexchange", "id": 45415, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, mysql, node.js, express.js", "url": null }
javascript, mysql, node.js, express.js Querying each shard in a loop is not the best way, as it does not utilize the potential for parallel queries. A better approach is to initiate all shard queries simultaneously using Promise.all and then combine the results thus your queries will run in parallel, reducing the overall response time. const tweetPromises = shardConnections.map(shardConnection => shardConnection.execute(tweetsQuery, [followingUsers]) ); const results = await Promise.all(tweetPromises); const tweets = results.flatMap(result => result[0]);
{ "domain": "codereview.stackexchange", "id": 45415, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, mysql, node.js, express.js", "url": null }
c++ Title: Code for functionality like "valid pointer or default" and "true or default" Question: Relatively new to C++, not sure if I'm doing everything right, any advice would be appreciated. The site does not allow me to post this question with that little actual text, so I am artificially extending it with this dummy text. Here's what I wrote: #include <iostream> template<typename T> class DefaultPointer { const T* value_pointer; const T default_value; public: DefaultPointer(const T* ptr, const T& def) : value_pointer(ptr), default_value(def) { } const T get() { if (value_pointer == nullptr) { return default_value; } return *value_pointer; } }; template<typename T> class Default { const T value; const T default_value; public: Default(const T& value, const T& def) : value(value), default_value(def) { } const T get() { if (!(bool)value) { return default_value; } return value; } }; int main() { const int test_value = 1; const int* const pointer = &test_value; std::cout << DefaultPointer<int>(pointer, 0).get(); } Answer: Here are some considerations: Use of const: In your DefaultPointer and Default classes, the get method does not modify any member variables, so it's good practice to mark it as const to indicate that calling this method won't change the object's state. For the member variables value_pointer and value, consider if you really want them to be const. This makes your objects immutable after they're constructed, which might be your intention. If you ever need to change the pointer or value after construction, you'll need to remove the const. Checking for null pointers and zero values:
{ "domain": "codereview.stackexchange", "id": 45416, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c++ Checking for null pointers and zero values: In Default, you check if (!(bool)value). This works for numeric types where 0 is implicitly convertible to false, but it might not be clear or applicable for all types T. Consider if there's a more explicit or type-safe way to handle this, depending on what types you expect T to be. Return Type Optimization: Returning by const T is unusual. Typically, you'd return by value (T) or by const T& if you're returning a reference to an existing object (to avoid copying). Returning by const T prevents the caller from modifying the returned value, which is unnecessary for built-in types and might inhibit move semantics for user-defined types. Error Handling: Consider what should happen if an invalid pointer is passed to DefaultPointer. Your current implementation gracefully handles nullptr, but what about dangling or uninitialized pointers? This might be beyond the scope of your current practice but is worth thinking about as you advance. Usage Example: Your main function demonstrates usage of DefaultPointer but not Default. It might be beneficial to include an example of how Default is intended to be used, especially considering its reliance on the boolean conversion of T. Other practices to keep in mind: If you're using C++11 or newer, you can use nullptr instead of NULL for null pointer constants. It's more type-safe and clear. Consider using smart pointers (std::unique_ptr, std::shared_ptr) if you plan to work with dynamically allocated memory. They help manage memory more safely and automatically.
{ "domain": "codereview.stackexchange", "id": 45416, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++", "url": null }
c, file, io Title: C- Reading and Parsing textfile Question: I'm relatively new to C programming and currently tackling exercises on Advent of Code. The challenge I'm working on involves calculating the sum of integers within each group from a file and identifying the top 3 groups based on their sums. Here's an example of the input format: group1 value 1 group1 value 2 group2 value 1 group3 value 1 group3 value 2 I've implemented the following code, where I iterate through the input character by character, calculating the sum for each row, and then tallying up the sums for each group. Additionally, I'm keeping track of whether a group is in the top 3. #include <stdio.h> #include <stdlib.h> #include <stdbool.h> void closeFile(FILE *file) { if (file != NULL) { fclose(file); } } void handleFileError(FILE *file, const char *errorMessage) { perror(errorMessage); closeFile(file); exit(EXIT_FAILURE); } void handleMemoryError(void *memory) { perror("Memory allocation error"); free(memory); exit(EXIT_FAILURE); } size_t readFile(const char *filename, char **buffer) { FILE *file = fopen(filename, "rb"); if (file == NULL) { handleFileError(file, "Error opening file"); } fseek(file, 0, SEEK_END); long fileSize = ftell(file); fseek(file, 0, SEEK_SET); *buffer = (char *)malloc(fileSize + 1); if (*buffer == NULL) { handleMemoryError(*buffer); } size_t bytesRead = fread(*buffer, 1, fileSize, file); if (bytesRead != fileSize) { handleFileError(file, "Error reading file"); } closeFile(file); (*buffer)[fileSize] = '\0'; return bytesRead; }
{ "domain": "codereview.stackexchange", "id": 45417, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, file, io", "url": null }
c, file, io closeFile(file); (*buffer)[fileSize] = '\0'; return bytesRead; } int main(int argc, char* argv[]) { char *buffer = NULL; size_t fsize = readFile(argv[1], &buffer); bool line_changed = false; int max1 = 0; int max2 = 0; int max3 = 0; int cum = 0; int line = 0; for (int i = 0; i < fsize; i++) { int j = buffer[i] - '0'; if(j>=0){ line_changed = false; line*=10; line+=j; }else if(!line_changed){ line_changed = true; cum += line; line = 0; }else{ line_changed = false; if(cum >= max1){ max3 = max2; max2 = max1; max1 = cum; }else if(cum>=max2){ max3 = max2; max2 = cum; }else if(cum >= max3){ max3 = cum; } cum=0; } } if(cum>=max1){ max2 = max1; max3 = max2; max1 = cum; }else if(cum>=max2){ max3 = max2; max2 = cum; }else if(cum >= max3){ max3 = cum; } printf("%i\n",max1); printf("%i\n",max1+max2+max3); free(buffer); return 0; } I would appreciate any suggestions for optimizing the code for readability and adhering to best practices. Answer: More functions please.... main does too much. Working over each individual elf shall be a function (returning the total calories it carries). Converting a line into a value shall also be a function (which BTW already exist in stdlib). ... but not too much. I don't see a value in closeFile. If fopen failed, you return immediately, and in the rest of the program you are guaranteed that file != NULL. Which means that closeFile is just an obscure call to fclose.
{ "domain": "codereview.stackexchange", "id": 45417, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, file, io", "url": null }
c, file, io There is no reason to read the entire file at once. Even if you insist on handling one character at a time, buffer[i] is no better than fgetc. The performance gain is infinitesimal, and is likely overshadowed by the overhead of memory allocation and three system calls in file size computation. And of course, there is no reason to handle one character at a time. It makes it very hard to track the logic. Instead, read the file line by line with fgets, and convert the entire line to an integer with strtol.
{ "domain": "codereview.stackexchange", "id": 45417, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, file, io", "url": null }
php, random, security Title: Cryptographically secure version of the core array_rand() function Question: I want a cryptographically secure version of array_rand(). Is this it? /** * retrieve a random key from an array, using a cryptographically secure rng. * - it does the same as array_rand(), except that this one use a cryptographically secure rng. * - relatively speaking, it should be significantly slower and more memory hungry than array_rand(), because it is creating a copy of all the keys of the array.. * * @param array $arr * @throws ValueError if array is empty * @return mixed */ function array_rand_cryptographically_secure(array $array) { if (count ( $array ) < 1) { throw new ValueError ( 'Argument #1 ($array) cannot be empty' ); } if (PHP_MAJOR_VERSION >= 8 && array_is_list ( $array )) { // optimization, this avoids creating a copy of all the keys return random_int ( 0, count ( $array ) - 1 ); } $keys = array_keys ( $array ); return $keys [random_int ( 0, count ( $keys ) - 1 )]; } Significant edit: I figured I can use array_is_list() to avoid copying the keys when given a list.
{ "domain": "codereview.stackexchange", "id": 45418, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, random, security", "url": null }
php, random, security Significant edit: I figured I can use array_is_list() to avoid copying the keys when given a list. Answer: array_is_list() is available from PHP8.1. You can check the PHP version major&minor version with version_compare() (version_compare(PHP_VERSION, '8.1', '>=')) or function_exists() -- the latter is more concise and explicit than the former. The $max key position is shared by both branches of the conditional logic, so you can count() just once. In other words, regardless of if you call array_keys(), the array's size will not change. With $max already declared, $keys becomes a single-use variable and is therefore omittable. I prefer to type hint whenever possible. Since array keys can only either be integers or strings, the return value can be typed. With PHP8, union types allow the explicit dual-typing of the return value as a string or an integer. Of course, if you are trying to make a function that works under PHP8, then disregard this point. Code: (Demo) function array_rand_cryptographically_secure(array $array): int|string { $max = count($array) - 1; if ($max < 0) { throw new ValueError('Argument #1 ($array) cannot be empty'); } if (function_exists('array_is_list') && array_is_list($array)) { // optimization, this avoids creating a copy of all the keys return random_int(0, $max); } return array_keys($array)[random_int(0, $max)]; } $tests = [ [5, 6, 7], ['a' => 1, 'b' => 2, 'c' => 3], ['zero', 4 => 'four', 9 => 'nine'] ]; foreach ($tests as $test) { echo array_rand_cryptographically_secure($test) . "\n"; } Alternatively, you can slice and preserve the original keys to avoid doubling the memory cost. (Demo) function array_rand_cryptographically_secure(array $array): int|string { $max = count($array) - 1; if ($max < 0) { throw new ValueError('Argument #1 ($array) cannot be empty'); } return key(array_slice($array, random_int(0, $max), 1, true)); }
{ "domain": "codereview.stackexchange", "id": 45418, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, random, security", "url": null }
php, random, security And finally, the most compact and perhaps hardest to read because of all of the nested function calls: (Demo) function array_rand_cryptographically_secure(array $array): int|string { if (!$array) { throw new ValueError ('Argument #1 ($array) cannot be empty'); } return key(array_slice($array, random_int(0, count($array) - 1), 1, true)); }
{ "domain": "codereview.stackexchange", "id": 45418, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, random, security", "url": null }
java, algorithm, bitwise, vectors, bitset Title: Bit vector in Java supporting O(1) rank() and O(log n) select() Question: Introduction I have this GitHub repository (version 1.0.0.). It implements a rank(i) operation in \$\Theta(1)\$ time, and select(i) operation in \$\Theta(\log n)\$ time. (This post has an continuation post, version 1.0.1.) Code com.github.coderodde.util.RankSelectBitVector.java:
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset /** * This class defines a packed bit vector that supports {@code rank()} operation * in {@code O(1)} time, and {@code select()} in {@code O(log n)} time. * * @version 1.0.0 * @since 1.0.0 */ public final class RankSelectBitVector { /** * Indicates whether some bits were changed since the previous building of * the index data structures. */ private boolean hasDirtyState = true; /** * The actual bit storage array. */ private final byte[] bytes; /** * The actual requested number of bits in this bit vector. Will be smaller * than the total capacity. */ private final int numberOfRequestedBits; /** * Denotes index of the most rightmost meaningful bit. Will be set to * {@code numberOfRequestedBits - 1}. */ private final int maximumBitIndex; /** * Caches the number of bits set to one (1). */ private int numberOfSetBits; /** * The block size in the {@code first} table. */ private int ell; /** * The block size in the {@code second} table. */ private int k; // The following three tables hold the index necessary for efficient rank // operation. According to internet, has space // O(sgrt(n) * log log n * log n. private int[] first; private int[] second; private int[][] third; /** * Constructs a new bit vector. * * @param numberOfRequestedBits the actual number of bits to support. */ public RankSelectBitVector(int numberOfRequestedBits) { checkNumberOfRequestedBits(numberOfRequestedBits); this.numberOfRequestedBits = numberOfRequestedBits; // Calculate the actual number of storage bytes: int numberOfBytes = numberOfRequestedBits / Byte.SIZE + (numberOfRequestedBits % Byte.SIZE != 0 ? 1 : 0);
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset (numberOfRequestedBits % Byte.SIZE != 0 ? 1 : 0); numberOfBytes++; // Padding tail byte in order to simplify the last // rank/select. bytes = new byte[numberOfBytes]; // Set the rightmost, valid index: this.maximumBitIndex = this.bytes.length * Byte.SIZE - 1; } @Override public String toString() { StringBuilder sb = new StringBuilder().append("[Bit vector, size = "); sb.append(getNumberOfSupportedBits()) .append(" bits, data = "); int bitNumber = 0; for (int i = 0; i < getNumberOfSupportedBits(); i++) { sb.append(readBitImpl(i) ? "1" : "0"); bitNumber++; if (bitNumber % 8 == 0) { sb.append(" "); } } return sb.append("]").toString(); } /** * Preprocesses the internal data structures in {@code O(n)}. */ public void buildIndices() { if (hasDirtyState == false) { // Nothing to do. return; } //// Deal with the 'first'. // n - total number of bit slots: int n = bytes.length * Byte.SIZE; // elll - the l value: this.ell = (int) Math.pow(Math.ceil(log2(n) / 2.0), 2.0); this.first = new int[n / ell + 1]; for (int i = ell; i < n; i++) { if (i % ell == 0) { int firstArraySlotIndex = i / ell; int startIndex = i - ell; int endIndex = i - 1; first[firstArraySlotIndex] = first[firstArraySlotIndex - 1] + bruteForceRank(startIndex, endIndex); } } //// Deal with the 'second'. this.k = (int) Math.ceil(log2(n) / 2.0);
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset //// Deal with the 'second'. this.k = (int) Math.ceil(log2(n) / 2.0); this.second = new int[n / k + 1]; for (int i = k; i < n; i++) { if (i % k == 0) { second[i/k] = bruteForceRank(ell * (i / ell), i - 1); } } //// Deal with the 'third': four Russians' technique: this.third = new int[(int) Math.pow(2.0, k - 1)][]; for (int selectorIndex = 0; selectorIndex < third.length; selectorIndex++) { third[selectorIndex] = new int[k - 1]; // third[selectorIndex][0] is always zero (0). third[selectorIndex][0] = (bitIsSet(selectorIndex, k - 2) ? 1 : 0); for (int j = 1; j < k - 1; j++) { third[selectorIndex][j] = third[selectorIndex][j - 1] + (bitIsSet(selectorIndex, k - j - 2) ? 1 : 0); } } hasDirtyState = false; } /** * Returns the number of bits that are set (have value of one (1)). * * @return the number of set bits. */ public int getNumberOfSetBits() { return numberOfSetBits; } /** * Returns the number of bits this bit vector supports. * * @return the number of bits supported. */ public int getNumberOfSupportedBits() { return numberOfRequestedBits; } /** * Sets the {@code index}th bit to one (1). * * @param index the index of the target bit. */ public void writeBitOn(int index) { writeBit(index, true); } /** * Sets the {@code index}th bit to zero (0). * * @param index the index of the target bit. */ public void writeBitOff(int index) { writeBit(index, false); } /** * Writes the {@code index}th bit to {@code on}. *
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset } /** * Writes the {@code index}th bit to {@code on}. * * @param index the index of the target bit. * @param on the selector of the bit: if {@code true}, the bit will be * set to one, otherwise set zero. */ public void writeBit(int index, boolean on) { checkBitAccessIndex(index); writeBitImpl(index, on); } /** * Reads the {@code index}th bit where indexation starts from zero (0). * * @param index the bit index. * @return {@code true} if and only if the {@code index}th bit is set. */ public boolean readBit(int index) { checkBitAccessIndex(index); return readBitImpl(index); } /** * Returns the rank of {@code index}, i.e., the number of set bits in the * subvector {@code vector[1..index]}. Runs in {@code O((log n)^2)} time. * * @param index the target index. * @return the rank for the input target. */ public int rankFirst(int index) { checkBitIndexForRank(index); makeSureStateIsCompiled(); int startIndex = ell * (index / ell); int endIndex = index - 1; return first[index / ell] + bruteForceRank(startIndex, endIndex); } /** * Returns the {@code index}th rank. Runs in {@code O(log n)} time. * * @param index the target index. * @return the rank of the input index. */ public int rankSecond(int index) { checkBitIndexForRank(index); makeSureStateIsCompiled(); int startIndex = k * (index / k); int endIndex = index - 1; return first[index / ell] + second[index / k] + bruteForceRank(startIndex, endIndex); } /** * Returns the {@code index}th rank. Runs in {@code O(1)} time. * * @param index the target index.
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset * * @param index the target index. * @return the rank of the input index. */ public int rankThird(int index) { checkBitIndexForRank(index); makeSureStateIsCompiled(); int f = first[index / ell]; int s = second[index / k]; int thirdEntryIndex = index % k - 1; if (thirdEntryIndex == -1) { return f + s; } int selectorIndex = extractBitVector(index) .toInteger(k - 1); return f + s + third[selectorIndex][thirdEntryIndex]; } /** * Returns the index of the {@code index}th 1-bit. Relies on * {@link #rankFirst(int)}, which runs in {@code O((log n)^2)}, which yields * {@code O((log n)^3)} running time for the {@code selectFirst}. * * @param bitIndex the target index. * @return the index of the {@code index}th 1-bit. */ public int selectFirst(int bitIndex) { checkBitIndexForSelect(bitIndex); return selectImplFirst(bitIndex, 0, getNumberOfSupportedBits()); } /** * Returns the index of the {@code index}th 1-bit. Relies on * {@link #rankSecond(int)}, which runs in {@code O(log n)}, which yields * {@code O((log n)^2)} running time for the {@code selectSecond}. * * @param bitIndex the target index. * @return the index of the {@code index}th 1-bit. */ public int selectSecond(int bitIndex) { checkBitIndexForSelect(bitIndex); return selectImplSecond(bitIndex, 0, getNumberOfSupportedBits()); } /** * Returns the index of the {@code index}th 1-bit. Relies on * {@link #rankThird(int)}, which runs in {@code O(1)}, which yields * {@code O(log n)} running time for the {@code selectThird}. * * @param bitIndex the target index. * @return the index of the {@code index}th 1-bit. */
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset * @return the index of the {@code index}th 1-bit. */ public int selectThird(int bitIndex) { checkBitIndexForSelect(bitIndex); return selectImplThird(bitIndex, 0, getNumberOfSupportedBits()); } private int selectImplFirst(int bitIndex, int rangeStartIndex, int rangeLength) { if (rangeLength == 1) { return rangeStartIndex; } int halfRangeLength = rangeLength / 2; int r = rankFirst(halfRangeLength + rangeStartIndex); if (r >= bitIndex) { return selectImplFirst(bitIndex, rangeStartIndex, halfRangeLength); } else { return selectImplFirst(bitIndex, rangeStartIndex + halfRangeLength, rangeLength - halfRangeLength); } } private int selectImplSecond(int bitIndex, int rangeStartIndex, int rangeLength) { if (rangeLength == 1) { return rangeStartIndex; } int halfRangeLength = rangeLength / 2; int r = rankSecond(halfRangeLength + rangeStartIndex); if (r >= bitIndex) { return selectImplSecond(bitIndex, rangeStartIndex, halfRangeLength); } else { return selectImplSecond(bitIndex, rangeStartIndex + halfRangeLength, rangeLength - halfRangeLength); } } private int selectImplThird(int bitIndex, int rangeStartIndex, int rangeLength) { if (rangeLength == 1) { return rangeStartIndex; }
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset if (rangeLength == 1) { return rangeStartIndex; } int halfRangeLength = rangeLength / 2; int r = rankThird(halfRangeLength + rangeStartIndex); if (r >= bitIndex) { return selectImplThird(bitIndex, rangeStartIndex, halfRangeLength); } else { return selectImplThird(bitIndex, rangeStartIndex + halfRangeLength, rangeLength - halfRangeLength); } } /** * The delegate for manipulating bits. * * @param index the index of the target bit. * @param on the flag deciding the value of the bit in question. */ private void writeBitImpl(int index, boolean on) { boolean previousBitValue = readBit(index); if (on) { if (previousBitValue == false) { hasDirtyState = true; numberOfSetBits++; } turnBitOn(index); } else { if (previousBitValue == true) { hasDirtyState = true; numberOfSetBits--; } turnBitOff(index); } } /** * Implements the actual reading of a bit. * * @param index the index of the target bit to read. * @return the value of the target bit. */ boolean readBitImpl(int index) { int byteIndex = index / Byte.SIZE; int targetByteBitIndex = index % Byte.SIZE; byte targetByte = bytes[byteIndex]; return (targetByte & (1 << targetByteBitIndex)) != 0; } /** * Makes sure that the state of the internal data structures is up to date. */ private void makeSureStateIsCompiled() { if (hasDirtyState) { buildIndices(); hasDirtyState = false; } }
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset buildIndices(); hasDirtyState = false; } } /** * Turns the {@code index}th bit on. Indexation is zero-based. * * @param index the target bit index. */ private void turnBitOn(int index) { int byteIndex = index / Byte.SIZE; int bitIndex = index % Byte.SIZE; byte mask = 1; mask <<= bitIndex; bytes[byteIndex] |= mask; } /** * Turns the {@code index}th bit off. Indexation is zero-based. * * @param index the target bit index. */ private void turnBitOff(int index) { int byteIndex = index / Byte.SIZE; int bitIndex = index % Byte.SIZE; byte mask = 1; mask <<= bitIndex; bytes[byteIndex] &= ~mask; } private void checkBitIndexForSelect(int selectionIndex) { if (selectionIndex < 0) { throw new IndexOutOfBoundsException( String.format( "The input selection index is negative: " + "(%d). Must be within range [1..%d].\n", selectionIndex, numberOfSetBits)); } if (selectionIndex == 0) { throw new IndexOutOfBoundsException( String.format( "The input selection index is zero (0). " + "Must be within range [1..%d].\n", numberOfSetBits)); } if (selectionIndex > numberOfSetBits) { throw new IndexOutOfBoundsException( String.format( "The input selection index is too large (%d). " + "Must be within range [1..%d].\n", selectionIndex, numberOfSetBits)); } } private void checkBitIndexForRank(int index) {
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset } } private void checkBitIndexForRank(int index) { if (index < 0) { throw new IndexOutOfBoundsException( String.format("Negative bit index: %d.", index)); } if (index > numberOfRequestedBits) { throw new IndexOutOfBoundsException( String.format( "Too large bit index (%d), number of bits " + "supported is %d.", index, numberOfRequestedBits)); } } private void checkBitAccessIndex(int accessIndex) { if (accessIndex < 0) { throw new IndexOutOfBoundsException( String.format( "Negative bit access index: %d.", accessIndex)); } if (accessIndex >= getNumberOfSupportedBits()) { throw new IndexOutOfBoundsException( String.format( "Too large bit access index (%d), number of bits " + "supported is %d.", accessIndex, getNumberOfSupportedBits())); } } /** * Returns {@code true} if and only if the {@code bitIndex}th bit in * {@code value} is set. * * @param value the value of which to inspect the bit. * @param bitIndex the bit index. * @return {@code true} if and only if the specified bit is set. */ private boolean bitIsSet(int value, int bitIndex) { return (value & (1 << bitIndex)) != 0; } int toInteger(int numberOfBitsToRead) { int integer = 0; for (int i = 0; i < numberOfBitsToRead; i++) { boolean bit = readBitImpl(i); if (bit == true) { integer |= 1 << i; } }
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset if (bit == true) { integer |= 1 << i; } } return integer; } private RankSelectBitVector extractBitVector(int i) { int startIndex = k * (i / k); int endIndex = Math.min(k * (i / k + 1) - 2, maximumBitIndex); int extractedBitVectorLength = endIndex - startIndex + 1; RankSelectBitVector extractedBitVector = new RankSelectBitVector(extractedBitVectorLength); for (int index = extractedBitVectorLength - 1, j = startIndex; j <= endIndex; j++, index--) { extractedBitVector.writeBitImpl(index, this.readBitImpl(j)); } return extractedBitVector; } private int bruteForceRank(int startIndex, int endIndex) { int rank = 0; for (int i = startIndex; i <= endIndex; i++) { if (readBitImpl(i)) { rank++; } } return rank; } private void checkNumberOfRequestedBits(int numberOfRequestedBits) { if (numberOfRequestedBits == 0) { throw new IllegalArgumentException("Requested zero (0) bits."); } if (numberOfRequestedBits < 0) { throw new IllegalArgumentException( String.format( "Requested negative number of bits (%d).\n", numberOfRequestedBits)); } } private static double log2(double v) { return Math.log(v) / Math.log(2.0); } }
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset com.github.coderodde.util.RankSelectBitVectorBenchmark.java: package com.github.coderodde.util.benchmark; import com.github.coderodde.util.RankSelectBitVector; import java.util.Random;
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset public final class RankSelectBitVectorBenchmark { /** * The number of bits in the benchmark bit vector. */ private static final int BIT_VECTOR_LENGTH = 4_000_000; public static void main(String[] args) { long seed = parseSeed(args); System.out.printf("Seed = %d\n", seed); Random random = new Random(seed); long st = System.currentTimeMillis(); RankSelectBitVector rankSelectBitVector = createRandomBitVector(random); System.out.printf("Built the bit vector in %d milliseconds.\n", System.currentTimeMillis() - st); st = System.currentTimeMillis(); // st - start time. rankSelectBitVector.buildIndices(); System.out.printf("Preprocessed the bit vector in %d milliseconds.\n", System.currentTimeMillis() - st); System.out.println("--- Benchmarking rank operation ---"); benchmarkRanks(rankSelectBitVector); System.out.println("--- Benchmarking select operation ---"); benchmarkSelects(rankSelectBitVector); } private static RankSelectBitVector createRandomBitVector(Random random) { RankSelectBitVector rankSelectBitVector = new RankSelectBitVector(BIT_VECTOR_LENGTH); for (int bitIndex = 0; bitIndex != rankSelectBitVector.getNumberOfSupportedBits(); bitIndex++) { if (random.nextBoolean()) { rankSelectBitVector.writeBitOn(bitIndex); } } return rankSelectBitVector; } private static boolean rankArraysEqual(int[] rankArray1, int[] rankArray2) { if (rankArray1.length != rankArray2.length) { throw new IllegalArgumentException("Rank array length mismatch."); }
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset throw new IllegalArgumentException("Rank array length mismatch."); } int n = Math.max(rankArray1.length, rankArray2.length); for (int i = 0; i != n; i++) { int rank1 = rankArray1[i]; int rank2 = rankArray2[i]; if (rank1 != rank2) { System.err.printf( "ERROR: Mismatch at index = %d, " + "rank1 = %d, rank2 = %d.\n", i, rank1, rank2); return false; } } return true; } private static void benchmarkRanks(RankSelectBitVector rankSelectBitVector) { int numberOfBits = rankSelectBitVector.getNumberOfSupportedBits(); int[] answers1 = new int[numberOfBits]; int[] answers2 = new int[numberOfBits]; int[] answers3 = new int[numberOfBits]; long st = System.currentTimeMillis(); // st - start time. for (int i = 0; i != numberOfBits; i++) { answers1[i] = rankSelectBitVector.rankFirst(i); } long answersDuration1 = System.currentTimeMillis() - st; System.out.printf( "rankFirst() ran for %d milliseconds.\n", answersDuration1); st = System.currentTimeMillis(); for (int i = 0; i != numberOfBits; i++) { answers2[i] = rankSelectBitVector.rankSecond(i); } long answersDuration2 = System.currentTimeMillis() - st; System.out.printf( "rankSecond() ran for %d milliseconds.\n", answersDuration2); st = System.currentTimeMillis(); for (int i = 0; i != numberOfBits; i++) { answers3[i] = rankSelectBitVector.rankThird(i); }
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset answers3[i] = rankSelectBitVector.rankThird(i); } long answersDuration3 = System.currentTimeMillis() - st; System.out.printf( "rankThird() ran for %d milliseconds.\n", answersDuration3); if (!rankArraysEqual(answers1, answers2)) { System.err.println("Failed on rankFirst vs. rankSecond."); return; } if (!rankArraysEqual(answers1, answers3)) { System.err.println("Failed on rankFirst vs. rankThird."); } } private static void benchmarkSelects(RankSelectBitVector rankSelectBitVector) { int numberOfSetBits = rankSelectBitVector.getNumberOfSetBits(); int[] answers1 = new int[numberOfSetBits + 1]; int[] answers2 = new int[numberOfSetBits + 1]; int[] answers3 = new int[numberOfSetBits + 1]; long st = System.currentTimeMillis(); for (int i = 1; i <= numberOfSetBits; i++) { answers1[i] = rankSelectBitVector.selectFirst(i); } long answersDuration1 = System.currentTimeMillis() - st; System.out.printf( "selectFirst() ran for %d milliseconds.\n", answersDuration1); st = System.currentTimeMillis(); for (int i = 1; i <= numberOfSetBits; i++) { answers2[i] = rankSelectBitVector.selectSecond(i); } long answersDuration2 = System.currentTimeMillis() - st; System.out.printf( "selectSecond() ran for %d milliseconds.\n", answersDuration2); st = System.currentTimeMillis(); for (int i = 1; i <= numberOfSetBits; i++) { answers3[i] = rankSelectBitVector.selectThird(i); } long answersDuration3 = System.currentTimeMillis() - st;
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset } long answersDuration3 = System.currentTimeMillis() - st; System.out.printf( "selectThird() ran for %d milliseconds.\n", answersDuration3); if (!rankArraysEqual(answers1, answers2)) { System.err.println("Failed on selectFirst vs. selectSecond."); return; } if (!rankArraysEqual(answers1, answers3)) { System.err.println("Failed on selectFirst vs. selectThird."); } } private static long parseSeed(String[] args) { if (args.length == 0) { return System.currentTimeMillis(); } try { return Long.parseLong(args[0]); } catch (NumberFormatException ex) { System.err.printf( "WARNING: Could not parse '%s' as an long value.", args[0]); return System.currentTimeMillis(); } } }
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset com.github.coderodde.util.RankSelectBitVectorTest.java: package com.github.coderodde.util; import java.util.Random; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Test;
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset public final class RankSelectBitVectorTest { @Test public void lastBitRank() { RankSelectBitVector bv = new RankSelectBitVector(8); bv.writeBitOn(2); bv.writeBitOn(6); bv.writeBitOn(7); assertEquals(3, bv.rankFirst(8)); assertEquals(3, bv.rankSecond(8)); assertEquals(3, bv.rankThird(8)); } @Test public void smallSelect() { RankSelectBitVector bv = new RankSelectBitVector(8); bv.writeBitOn(2); bv.writeBitOn(4); bv.writeBitOn(5); bv.writeBitOn(7); // 00101101 // select(1) = 2 // select(2) = 4 // select(3) = 5 // select(4) = 7 assertEquals(2, bv.selectFirst(1)); assertEquals(4, bv.selectFirst(2)); assertEquals(5, bv.selectFirst(3)); assertEquals(7, bv.selectFirst(4)); } @Test public void debugTest1() { // 00101101 RankSelectBitVector bv = new RankSelectBitVector(8); bv.writeBitOn(2); bv.writeBitOn(4); bv.writeBitOn(5); bv.writeBitOn(7); assertEquals(0, bv.rankThird(0)); assertEquals(0, bv.rankThird(1)); assertEquals(0, bv.rankThird(2)); assertEquals(1, bv.rankThird(3)); assertEquals(1, bv.rankThird(4)); assertEquals(2, bv.rankThird(5)); assertEquals(3, bv.rankThird(6)); assertEquals(3, bv.rankThird(7)); assertEquals(4, bv.rankThird(8)); assertEquals(2, bv.selectFirst(1)); assertEquals(4, bv.selectFirst(2)); assertEquals(5, bv.selectFirst(3)); assertEquals(7, bv.selectFirst(4)); } @Test public void debugTest2() { // 00101101 10101101 RankSelectBitVector bv = new RankSelectBitVector(16); bv.writeBitOn(2); bv.writeBitOn(4); bv.writeBitOn(5); bv.writeBitOn(7);
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset bv.writeBitOn(4); bv.writeBitOn(5); bv.writeBitOn(7); bv.writeBitOn(8); bv.writeBitOn(10); bv.writeBitOn(12); bv.writeBitOn(13); bv.writeBitOn(15); assertEquals(0, bv.rankThird(0)); assertEquals(0, bv.rankThird(1)); assertEquals(0, bv.rankThird(2)); assertEquals(1, bv.rankThird(3)); assertEquals(1, bv.rankThird(4)); assertEquals(2, bv.rankThird(5)); assertEquals(3, bv.rankThird(6)); assertEquals(3, bv.rankThird(7)); assertEquals(4, bv.rankThird(8)); assertEquals(5, bv.rankThird(9)); assertEquals(5, bv.rankThird(10)); assertEquals(6, bv.rankThird(11)); assertEquals(6, bv.rankThird(12)); assertEquals(7, bv.rankThird(13)); assertEquals(8, bv.rankThird(14)); assertEquals(8, bv.rankThird(15)); assertEquals(9, bv.rankThird(16)); assertEquals(2, bv.selectFirst(1)); assertEquals(4, bv.selectFirst(2)); assertEquals(5, bv.selectFirst(3)); assertEquals(7, bv.selectFirst(4)); assertEquals(8, bv.selectFirst(5)); assertEquals(10, bv.selectFirst(6)); assertEquals(12, bv.selectFirst(7)); assertEquals(13, bv.selectFirst(8)); assertEquals(15, bv.selectFirst(9)); } @Test public void debugTest3() { // 00101101 10101101 00010010 RankSelectBitVector bv = new RankSelectBitVector(24); bv.writeBitOn(2); bv.writeBitOn(4); bv.writeBitOn(5); bv.writeBitOn(7); bv.writeBitOn(8); bv.writeBitOn(10); bv.writeBitOn(12); bv.writeBitOn(13); bv.writeBitOn(15); bv.writeBitOn(19); bv.writeBitOn(22); assertEquals(0, bv.rankThird(0)); assertEquals(0, bv.rankThird(1)); assertEquals(0, bv.rankThird(2));
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset assertEquals(0, bv.rankThird(1)); assertEquals(0, bv.rankThird(2)); assertEquals(1, bv.rankThird(3)); assertEquals(1, bv.rankThird(4)); assertEquals(2, bv.rankThird(5)); assertEquals(3, bv.rankThird(6)); assertEquals(3, bv.rankThird(7)); assertEquals(4, bv.rankThird(8)); assertEquals(5, bv.rankThird(9)); assertEquals(5, bv.rankThird(10)); assertEquals(6, bv.rankThird(11)); assertEquals(6, bv.rankThird(12)); assertEquals(7, bv.rankThird(13)); assertEquals(8, bv.rankThird(14)); assertEquals(8, bv.rankThird(15)); assertEquals(9, bv.rankThird(16)); // 00010010 assertEquals(9, bv.rankThird(17)); assertEquals(9, bv.rankThird(18)); assertEquals(9, bv.rankThird(19)); assertEquals(10, bv.rankThird(20)); assertEquals(10, bv.rankThird(21)); assertEquals(10, bv.rankThird(22)); assertEquals(11, bv.rankThird(23)); assertEquals(11, bv.rankThird(24)); // select(): assertEquals(2, bv.selectFirst(1)); assertEquals(4, bv.selectFirst(2)); assertEquals(5, bv.selectFirst(3)); assertEquals(7, bv.selectFirst(4)); assertEquals(8, bv.selectFirst(5)); assertEquals(10, bv.selectFirst(6)); assertEquals(12, bv.selectFirst(7)); assertEquals(13, bv.selectFirst(8)); assertEquals(15, bv.selectFirst(9)); assertEquals(19, bv.selectFirst(10)); assertEquals(22, bv.selectFirst(11)); } @Test public void bruteForceTest() { long seed = System.currentTimeMillis(); seed = 1706163778488L; Random random = new Random(seed); System.out.println("-- bruteForceTest, seed = " + seed); RankSelectBitVector bv = getRandomBitVector(random); BruteForceBitVector referenceBv = copy(bv);
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset BruteForceBitVector referenceBv = copy(bv); bv.buildIndices(); int numberOfOneBits = bv.rankThird(bv.getNumberOfSupportedBits()); for (int i = 0; i < bv.getNumberOfSupportedBits(); i++) { int actualRank = referenceBv.rank(i); int rank1 = bv.rankFirst(i); int rank2 = bv.rankSecond(i); int rank3 = bv.rankThird(i); int selectIndex = random.nextInt(numberOfOneBits) + 1; int actualSelect = referenceBv.select(selectIndex); int select1 = bv.selectFirst(selectIndex); if (select1 != actualSelect) { System.out.printf( "ERROR: i = %d, actualSelect = %d, select1 = %d.\n", i, actualSelect, select1); }
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset if (rank3 != actualRank) { System.out.printf( "ERROR: i = %d, actual rank = %d, rank1 = %d, " + "rank2 = %d, rank3 = %d.\n", i, actualRank, rank1, rank2, rank3); } assertEquals(actualRank, rank1); assertEquals(actualRank, rank2); assertEquals(actualRank, rank3); assertEquals(actualSelect, select1); } } private static RankSelectBitVector getRandomBitVector(Random random) { RankSelectBitVector bv = new RankSelectBitVector(5973); for (int i = 0; i < bv.getNumberOfSupportedBits(); i++) { if (random.nextDouble() < 0.3) { bv.writeBitOn(i); } } return bv; } private static BruteForceBitVector copy(RankSelectBitVector bv) { BruteForceBitVector referenceBv = new BruteForceBitVector(bv.getNumberOfSupportedBits()); for (int i = 0; i < bv.getNumberOfSupportedBits(); i++) { if (bv.readBit(i)) { referenceBv.writeBitOn(i); } } return referenceBv; } @Test public void toInteger() { RankSelectBitVector bitVector = new RankSelectBitVector(31); assertEquals(0, bitVector.toInteger(20)); bitVector.writeBit(1, true); assertEquals(2, bitVector.toInteger(20)); bitVector.writeBit(2, true); assertEquals(6, bitVector.toInteger(20)); bitVector.writeBit(4, true); assertEquals(22, bitVector.toInteger(20)); } @Test public void readWriteBit() { RankSelectBitVector bitVector = new RankSelectBitVector(30);
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset RankSelectBitVector bitVector = new RankSelectBitVector(30); bitVector.writeBit(12, true); assertTrue(bitVector.readBit(12)); bitVector.writeBit(12, false); assertFalse(bitVector.readBit(12)); assertFalse(bitVector.readBit(13)); } // @Test public void bruteForceBitVectorSelect() { BruteForceBitVector bv = new BruteForceBitVector(8); bv.writeBitOn(2); bv.writeBitOn(4); bv.writeBitOn(6); bv.writeBitOn(7); assertEquals(2, bv.select(1)); assertEquals(4, bv.select(2)); assertEquals(6, bv.select(3)); assertEquals(7, bv.select(4)); } @Test public void countSetBits() { RankSelectBitVector bv = new RankSelectBitVector(11); assertEquals(0, bv.getNumberOfSetBits()); bv.writeBitOn(10); assertEquals(1, bv.getNumberOfSetBits()); bv.writeBitOn(5); assertEquals(2, bv.getNumberOfSetBits()); bv.writeBitOff(10); assertEquals(1, bv.getNumberOfSetBits()); bv.writeBitOff(5); assertEquals(0, bv.getNumberOfSetBits()); } }
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
java, algorithm, bitwise, vectors, bitset (The missing class BruteForceBitVector is here.) Typical benchmark demo output Seed = 1706175245835 Built the bit vector in 74 milliseconds. Preprocessed the bit vector in 117 milliseconds. --- Benchmarking rank operation --- rankFirst() ran for 623 milliseconds. rankSecond() ran for 110 milliseconds. rankThird() ran for 625 milliseconds. --- Benchmarking select operation --- selectFirst() ran for 7593 milliseconds. selectSecond() ran for 1399 milliseconds. selectThird() ran for 6006 milliseconds. Critique request I would like to hear about the following issues: Efficiency. rankThird(int) in particular. Unit tests. Did I cover all the possible corner cases? Anything else? Answer: Under this model you cannot do a bit-by-bit extractBitVector and preserve the desired time complexity. You should be able to extract a contiguous group of bits by masking out some bits and stitching together (a constant number of) parts (this would be cheaper if the backing storage was an array of words instead of bytes). Going beyond that set of arithmetic operations, you can use Long.bitCount to efficiently count up to 64 bits (this should compile to either a popcnt instruction or at worst an log bits-step bithack if popcnt is not available, so it's not equivalent to looping over the bits). You can use that in bruteForceRank. You can also use Integer.numberOfLeadingZeros to compute an integer base-2 logarithm without a scary floating point logarithm. Going even further beyond that set of operations, since Java 19 there is Long.expand, which you can use to implement the word-level select from A Fast x86 Implementation of Select (it's not really x86-specific): Transcribed into Java (not tested): static int PTSelect(long x, int j) { long i = 1L << j; long p = Long.expand(i, x); return Long.numberOfTrailingZeros(p); } That would reduce the amount of recursion that the full select needs to do.
{ "domain": "codereview.stackexchange", "id": 45419, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, bitwise, vectors, bitset", "url": null }
python, performance Title: Tokenize a file Question: Objective: The goal of this script is to tokenize and print out all the words from the provided bible.txt file. Constraints: It should differentiate between 'U.K' and 'UK.' when removing extra symbols from the word. It should exclude duplicates. It should exclude words that contain digits. Existing code: #!/usr/bin/env python3 from sys import stdin import spacy def spacy_wordlist() -> None: nlp = spacy.load("en_core_web_sm") seen = set() for line in stdin: doc = (word for word in nlp(line.strip()) if word.is_alpha) for token in doc: if token.text not in seen: seen.add(token.text) print(token.text) if __name__ == "__main__": spacy_wordlist() Results: $ neofetch --stdout OS: Linux Mint 21.2 x86_64 Host: VMware Virtual Platform None Kernel: 5.15.0-76-generic CPU: Intel i5-8350U (2) @ 1.896GHz GPU: 00:0f.0 VMware SVGA II Adapter Memory: 716MiB / 1929MiB $ wc bible.txt 99809 821115 4432263 bible.txt $ time ./wordlist.py < bible.txt ... .. . real 33m31.760s user 33m9.423s sys 0m9.407s The execution time was considerably slow, prompting a review for optimization. Review goal: How can I reduce the execution time?
{ "domain": "codereview.stackexchange", "id": 45420, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance", "url": null }
python, performance Answer: right tool for the job You called nlp(line.strip()) to tokenize the input text. Using the power of spacy here is not appropriate. It can do many things, and you're barely taking advantage of any of them. No need to pay the cost for what we don't use. Please see the enclosed code below. I downcase all words, and otherwise conform almost exactly to the token results your original code was producing. Running time with spacy 3.7.2 on my laptop is about 8 minutes (you had reported three or four times that, unsure why, unless you're not yet using cPython 3.11). Elapsed time without spacy is about 12 seconds, a 40x speedup. Coding my very simple algorithm in Rust would doubtless give sub-second results. edge cases I downcased everything, including proper nouns. I ignored your "distinguish 'U.K' versus 'UK.'" requirement. So write a regex to notice such things, and invoke the expensive spacy tokenizer just on matching lines, preferring the cheap tokenizer for the majority of all lines scanned. At the moment the code would emit the pair "u", "k", versus just "uk" It's worth noting that I turn . period into SPACE -- you might possibly prefer to delete them instead. I turn - dash into SPACE, to correctly parse e.g. "standard-bearer" as two words, same as spacy does. In the sentence, "it was his wont to take morning walks", spacy parses "wont" in a peculiar way. It emits two tokens, "wo" & "nt", as though parsing a "won't" contraction. And "cannot" seems to be a stopword for similar reasons ("can" & "not"). modern locutions I stopped worrying about mismatches at the end of the real corpus. Two to five millennia ago very few people spoke of filespecs or URLs; "10.zip" and the Gutenberg web address get tokenized differently from spacy's behavior, which I decided was just fine. Similarly for lawyer references to e.g. paragraph F. These things could be finessed if it's important when scanning some other corpus. verification This code produces a pair of debugging log files.
{ "domain": "codereview.stackexchange", "id": 45420, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance", "url": null }
python, performance some other corpus. verification This code produces a pair of debugging log files. They are convenient for monitoring progress. But even better, they are formatted for convenient diffing, so we can verify the simple tokenizer's results are nearly identical to the reference results produced by spacy. tokenizing algorithm It's pretty simple. Accept a lowercase line of text, which conveniently makes a sentence's initial "The ..." look like an embedded "... and the ...". Use str.translate() to rapidly turn punctuation into SPACE characters. Given that the example corpus always separates sentences with . period + SPACE, it might possibly make more sense to delete periods, mapping e.g. "U.K" --> "uk" The words are now space-delimited, so it's straightforward to updeliver them, filtering out undesired words like chapter:verse annotations. The only other value-add spacy was offering at this point was normalizing possessives, e.g. "brother's" --> "brother". The English language certainly has its irregularities, but fortunately the rule for stripping possessives is trivially implemented. And then we're done! proper nouns If identifying person and place names is important to your use case, you might scan the text for capitalized names that don't start a sentence: "word Name". Then re-scan, and carefully preserve such capitalized words, even when they begin a sentence. If a name is seldom used, and it appears only at start of sentence, then we might need a POS-tagger, or go back to the full spacy parse that you had been doing. While we're on that topic, handing spacy one line at a time works, but it's a little weird. Sending in a sentence or paragraph would be more natural, and would reveal more about each word's part-of-speech. Simply scanning for the blank line that separates paragraphs / verses would be the most convenient approach for chunking up the text. One advantage of the current line-oriented approach is that lines are typically smaller than sentences,
{ "domain": "codereview.stackexchange", "id": 45420, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance", "url": null }
python, performance lines are typically smaller than sentences, and after we've seen a few hundred unique words it will be commonly the case that a given line is comprised entirely of seen words. So we might do a cheap parse to identify each "boring" line, and only do an expensive spacy call on lines containing novel words. Life is full of engineering tradeoffs.
{ "domain": "codereview.stackexchange", "id": 45420, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance", "url": null }
python, performance #! /usr/bin/env _TYPER_STANDARD_TRACEBACK=1 python from collections import Counter from operator import itemgetter from pathlib import Path from pprint import pp from typing import Generator, TextIO from spacy.language import Language from spacy.tokens.token import Token import spacy import spacy.tokens import typer punctuation = str.maketrans( '.,;:!?"()[]{}-', " ", ) def _get_simple_words(line: str) -> Generator[str, None, None]: for word in line.translate(punctuation).split(): # strip possessives if word.endswith("'"): word = word[:-1] if word.endswith("'s"): word = word[:-2] if word.isalpha(): yield word def _get_spacy_tokens(nlp: Language, line: str) -> Generator[Token, None, None]: yield from (word for word in nlp(line.strip()) if word.is_alpha) def spacy_wordlist( fin: TextIO, simp_out: TextIO, spcy_out: TextIO, ) -> None: nlp = spacy.load("en_core_web_sm") simp_seen = {"cannot"} spcy_seen = set() cnt: Counter[str] = Counter() dups = 0 for line_num, line in enumerate(fin): line = line.lower() simp_out.write(f"\n{1 + line_num}\n\n") spcy_out.write(f"\n{1 + line_num}\n\n") for word in _get_simple_words(line): if word not in simp_seen: simp_seen.add(word) simp_out.write(f"{word}\n") for token in _get_spacy_tokens(nlp, line): cnt[token.text] += 1 if token.text in spcy_seen: dups += 1 else: spcy_seen.add(token.text) spcy_out.write(f"{token}\n") cnt = Counter({k: v for k, v in cnt.items() if v >= 3}) pp(sorted(cnt.items(), key=itemgetter(1))) print(len(spcy_seen), dups)
{ "domain": "codereview.stackexchange", "id": 45420, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance", "url": null }
python, performance def main(in_file: Path) -> None: with open(in_file) as fin: temp = Path("/tmp") simp_txt = temp / "bible_simple.txt" spcy_txt = temp / "bible_spacy.txt" with open(simp_txt, "w") as simp_out, open(spcy_txt, "w") as spcy_out: spacy_wordlist(fin, simp_out, spcy_out) if __name__ == "__main__": typer.run(main)
{ "domain": "codereview.stackexchange", "id": 45420, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance", "url": null }
go Title: A very simple secrets cache Question: This package is a part of a web application which is an internal company tool. This web application may need access to a number of secretes stored in hashicorp vault. The secrets rarely change, although in case they occasionally do there is a UI button to invalidate the secrets cache so it could be reloaded. I felt that sync.Map is an overkill here, so I implemented a very simple cache behind sync.RWMutex: in all likelihood, each particular Vault path will ever only need to be loaded once, and it is unlikely that more than a few dozen paths will need to be read in total. On the other hand the application will be requesting secrets as part of it's normal work all the time, it will just be the same secrets over and over. There are three files here. One is the cache, another to deal with Vault token refresh (the web app authenticates against Vault with an approle). And the remaining file implements the function the web application call to get the secrets. The application is similar to assets management, it is used by less than half a dozen people responsible for it, so if there are any concurrency issues, I'm not likely to notice, yet I'd like not to make obvious mistakes. I'm an experienced programmer, but I'm fairly inexperienced in Go, so while the focus of my question is thread safety and the cache implementation, I welcome any and all feedback, including one on Go best pattern and practices and styling. cache.go: package vault import ( "sync" ) var cache = make(map[string]map[string]interface{}) var cacheLock sync.RWMutex func getCached(key string) (map[string]interface{}, bool) { cacheLock.RLock() defer cacheLock.RUnlock() res, ok := cache[key] return res, ok } func writeCache(key string, value map[string]interface{}) { cacheLock.Lock() defer cacheLock.Unlock() cache[key] = value }
{ "domain": "codereview.stackexchange", "id": 45421, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go", "url": null }
go // May ocasionally be requested from web UI func ResetCache() { cacheLock.Lock() defer cacheLock.Unlock() cache = make(map[string]map[string]interface{}) } token.go: package vault import ( "fmt" "sync" vault "github.com/hashicorp/vault/api" ) var token string var tokenLock sync.RWMutex func getToken() string { tokenLock.RLock() defer tokenLock.RUnlock() return token } func refreshToken(c *vault.Logical) (string, error) { tokenLock.Lock() defer tokenLock.Unlock() secret, err := c.Write("auth/approle/login", map[string]interface{}{ "role_id": config.RoleId, "secret_id": config.SecretId, }) if err != nil { return "", fmt.Errorf("error logging into vault approle: %v", err) } token = secret.Auth.ClientToken return token, nil } client.go package vault import ( "fmt" vault "github.com/hashicorp/vault/api" ) type VaultConfig struct { Url string RoleId string SecretId string } var config VaultConfig // This is called on the application start up func Init(url, roleId, secretId string) { config = VaultConfig{ Url: url, RoleId: roleId, SecretId: secretId, } } // This is the main package function. Give a path in vault and a key name under the path get the value func Get(path, key string) (string, error) { data, ok := getCached(path) if !ok { var err error data, err = readFromVault(path) if err != nil { return "", err } writeCache(path, data) } if result, ok := data[key]; ok { r, ok := result.(string) if !ok { // I beleive this can never happen (unless vault api changes) panic("vault value is not a string") } return r, nil } else { return "", fmt.Errorf("failed to find key '%v' at '%v' in vault", key, path) } }
{ "domain": "codereview.stackexchange", "id": 45421, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go", "url": null }
go func readFromVault(path string) (map[string]interface{}, error) { client, err := vault.NewClient(&vault.Config{ Address: config.Url, }) if err != nil { return nil, fmt.Errorf("error creating vault client for %s: %v", config.Url, err) } c := client.Logical() client.SetToken(getToken()) l, err := c.Read(path) if err != nil { if re, ok := err.(*vault.ResponseError); !ok || re.StatusCode != 403 { return nil, fmt.Errorf("failed to read path '%v' in vault: %v", path, err) } // If that was 403 it could be because of the invalid/expired token token, err := refreshToken(c) if err != nil { return nil, err } client.SetToken(token) l, err = c.Read(path) if err != nil { return nil, fmt.Errorf("failed to read path '%v' in vault: %v", path, err) } } result, ok := l.Data["data"].(map[string]interface{}) if !ok { // I beleive this can never happen (unless vault api changes) panic(fmt.Sprintf("vault data dictionary is of unexpected type '%T'", l.Data["data"])) } return result, nil } Answer: First up: whenever you're wondering if your code is safe for concurrent use, your first port of call really ought to be writing unit tests, marking them with t.Parallel() so all your tests can run in parallel (duh), and perhaps write a single test function that spawns a couple of routines that read and write to your cache. Run those tests with race detection enabled: $ go test -race ./your/package The race detector does a very good job at finding potential data races in your code. Anyway, let's look at your code:
{ "domain": "codereview.stackexchange", "id": 45421, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go", "url": null }
go The first thing that looks odd to me is that your vault package relies on 2 global variables, that are otherwise not linked. You seem to be storing some arbitrary set of cached values under a key, all stored as a map[string]interface{}. Your functions aren't exported (except for the ResetCache one), which means all code in the vault package should use the mutex to interact with this cached variable. Assuming you're doing that, the vault package should be fine WRT concurrency, but it's easy to imagine that someone forgets acquiring a lock, or messing other things up (deleting a line accidentally), and just like that, the entire package is rendered unsafe. When it comes to concurrency, the go standard library offers a type sync.Map, which you could use instead, but this is essentially a wrapper around a map[string]interface{}, rather than your map[string]map[string]interface{}. I would instead opt for a struct to keep the mutex and map together. This still requires anyone writing code in the package to use the mutex, but because it's a dedicated type, the code is more self-documenting, and essentially tells you that the mutex and map belong together: package vault type cache struct { data map[string]map[string]any // any is short for interface{} rmu *sync.RWMutex } Note that the RWMutex is a pointer here. That's because adding methods can be done with a pointer receiver, or a value receiver. If the mutex is not a pointer, then value receivers will be using a copy of the mutex, rendering the interface unsafe once again: func NewCache() *cache { return &cache{ data: map[string]map[string]any{}, // no need for make rmu: &sync.RWMutex{}, } } func (c *cache) Reset() { c.rmu.Lock() defer c.rmu.Unlock() c.data = map[string]map[string]any{} } func (c cache) Get(k string) (map[string]any, bool) { c.rmu.RLock() defer c.rmu.RUnlock() return c.data[k] }
{ "domain": "codereview.stackexchange", "id": 45421, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go", "url": null }
go Now imagine rmu is not a pointer. The Get call will receive a copy of the mutex, and a copy of the map, but a map is a reference type, so effecitvely it is shared should the Get function and Reset be called concurrently. Just like that, you'd have a data race, hence: the mutex has to be a pointer: a copy to a memory address after all points to the same object in memory. Another thing to consider is that a package such as this can prove useful in a lot of different environments. Sometimes, you'd want to cache data that otherwise require a query to some type of database. You could add a cache object such as this where you store all objects using their ID. In that case, the restriction that you have of requiring data to be stored under a key as a map[string]any is very much an obstacle to its utility. Perhaps this is a decent use-case for a type that uses generics: type cache[K comparable, V any] struct { data map[K]V rmu *sync.Mutex } func New[K comparable, V any]() *cache[K, V] { return &cache{ data: map[K]V{}, rmu: &sync.RWMutex{}, } } If you now need a cache that stores map[string]any values using string keys, you'd create the instance like so: mapCache := New[string, map[string]any]() To cache DB objects that use a uint64 as ID (like a SERIAL INT or something), you can do that just as easily: userCache := New[uint64, *entities.User]() That does require your methods to be changed accordingly, but that's all very easy to do: func (c *cache[K, V]) Get(key K) (V, bool) { c.rmu.RLock() defer c.rmu.RUnlock() return c.data[key] } With this implementation, using our 2 instances from earlier we can say that: data, ok := mapCache("foo") // returns map[string]any, bool user, ok := userCache(123) // return *entities.User, bool
{ "domain": "codereview.stackexchange", "id": 45421, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go", "url": null }
go Overall, this makes the cache type a lot more flexible, and allows it to be used with any type of key, and any type of data. If the flexibility in terms of data you want to cache is not that important to you, I still maintain that supporting different key types makes a lot of sense. Clearly, you're wanting to have K-V store that is grouped at the top level. Say you're wanting to use this cache object in your entire project, but you want each package to make it easy to access the data that is relevant to it. You would then create a namespace type in a shared package: package namespace type Domain uint32 const ( Database Domain = iota Requests Authenticaion // etc... ) This is essentially how you'd create an enum in golang. We create a Domain type (which is ~uint32), and declare a bunch of iota constants of this type (this means the compiler will ensure all of the values will have distinct values). Now our cache constructor would look like this: type cache[K comparable] struct { data map[K]map[string]any rmu *sync.RWMutex } func New[K comparable]() *cache[K] { return &cache{ data: map[K]map[string]any{}, rmu: &sync.RWMutex{}, } } you'd then create the cache instance like this: cache := New[namespace.Domain]() Each package would then be able to get the cache values that are relevant to it like this: vals, ok := cache.Get(namespace.Database) Another thing that doesn't sit well with me is in fact your ResetCache implementation. Let's say the data in the cache looks something like this: { "foo": {"bar": 123, "foobar": true}, "volatile": {"TTL": 123, "abc": "some value"}, }
{ "domain": "codereview.stackexchange", "id": 45421, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go", "url": null }
go Your cache implementation either treats all values as valid, or none. I'd argue that, if you're caching data in a map[string]map[string]any, you really would want to allow specific keys in the cache to be cleared/reset without it impacting the rest of the cache. Again: looking at the example of using this type of caching for querying data: you'd want to mark the cache as stale when you've executed an update on some or all of the records, but if you've updated a product catalog, you naturally want to mark the entities.Product cache as stale, but the entities.User data is still valid. I'd therefore argue that you probably want at least 2 methods to invalidate the cache: func (c *cache[K, V]) ResetAll() { c.rmu.Lock() defer c.rmu.Unlock() c.data = map[K]V{} } // ResetKeys reset one or more cache entries by key func (c *cache[K, V]) ResetKeys(keys ...K) { c.rmu.Lock() defer c.rmu.Unlock() for _, k := range keys { delete(c.data, k) } } Now the writeCache function looks fine to me, although if you want your cache implementation to be more broadly usable, having a CAS option would be nice: func (c *cache[K, V]) CAS(key K, val V) bool { c.rmu.Lock() defer c.rmu.Unlock() if _, ok := c.data[key]; ok { return false // can't set the value, it's already set } c.data[key] = val return true // value was added to the cache } Now for the token file: broadly speaking, you could just create a type with a string field + a mutex, but a string is a simple value, but it's worth considering storing the token in a atomic.Value instead. If overall you're spending most of the time reading the value, it might be more efficient than having the overhead of dealing with an RWMutex. You can find more on the atomic package here In your client.go file, the main difference will be that this: client.SetToken(getToken())
{ "domain": "codereview.stackexchange", "id": 45421, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go", "url": null }
go will instead look more like this: // assume the token is stored like this: var tokenV atomic.Value tokenV.Store(tokenStr) token := tokenV.Load().(string) // get the token value client.SetToken(token) When refreshing the token, I'd probably pass in the expired token as an argument, so you can (atomically) check if the token has since been refreshed in another routine, but the key thing here would be to not just call Swap, but instead use the old value, get the new one and perform a CompareAndSwap: func refreshToken(old string) (string, bool) { // get the new token ok := tokenV.CompareAndSwap(old, newToken) ret := tokenV.Load().(string) return ret, ok // returns the new token and true if you refershed the token, false if the token had already been refreshed } Depending on how you'll be using the token (I'm assuming the vast majority of access to the data will be simply reading the value), I suspect using an atomic value will outperform the mutex stuff, and there's only 1 variable to contend with. The overall interface that you'll want to expose will look something like this: package token var value atomic.Value func init() { value.Set("") } func Get() string { s := value.Load().(string) // optionally use the ok flag to see if the type assertion worked, but this is a small package, and value is not exported, so should be fine return s } func Refresh(c *vault.Logical, old string) (string, bool) { // same as before, perform the request ok := value.CompareAndSwap(old, newToken) s := value.Load().(string) return s, ok }
{ "domain": "codereview.stackexchange", "id": 45421, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go", "url": null }
go You may have noticed that I've renamed the functions from ResetCache to Reset[All|Keys], GetCached to Get, and similarly I renamed GetToken and RefreshToken to Get and Refresh. The reason for this is to avoid something referred to as stutter. As I explained above: the cache component is a "general purpose" package in essence. Its job it to take values, make them available on request as a simple map lookup. This package doesn't need to know about the token being a thing. It doesn't need to have access to the package, thus it shouldn't be imported. The token package is its own thing. It just exists to make a token string accessible in a concurrent-safe way, and it exports the interface that allows packages that import it to do just that. Therefore, I would expect the token.go and cache.go files to live in their own packages, which appropriately would be named token and cache respectively. If you had a function called RefreshToken in a package called token, your code could end up looking something like this: currentToken := token.GetToken() client.SetToken(currentToken) // if you need to refresh the token: newToken, ok := token.RefreshToken(currentToken) // etc... As you can see token.GetToken() is not only more to type, it doesn't communicate more than the more readable/brief: token.Get(). The same applies to this cache package: valCache := cache.New[string, map[string]any]() data, ok := valCache.Get("foo") Is just as communicative as this: valCache := cache.NewCache[string, map[string]any]() data, ok := valCache.GetCached("foo")
{ "domain": "codereview.stackexchange", "id": 45421, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go", "url": null }
go It's quite important to not loose track of the way your packages will be used. We write packages to encapsulate or abstract away the intricacies that we don't want to deal with when writing logic. Should the user care that, when refreshing the token, they need to acquire a lock on said token, or that they should acquire a read lock on the token when getting that string? Of course not. In a package, we wrap that stuff in functions, which we can test, and thus ensure that the locks are correctly acquired and released. The code that uses our package only cares about Get() and Refresh(), nothing else. Anything that makes a package feel clunky or counter-intuitive quickly (and I do mean surprisingly quickly) an obstacle, and eventually an excuse to circumnavigate your carefully crafted package. It's very common in even a medium-sized codebase to find a number of functions strewn about the place that look like this: func max(a, b uint64) uint64 { if a > b { return a } return b } Then somewhere else you'll find something like this: type Int interface { ~int | ~uint | ~int8 | ~uint8 | ~int32 | ~uint32 | ~int64 | ~uint64 } func Max[T Int](a, b T) T { if a > b { return a } return b } only to stumble across some kind of utils or types package in that project that contains something like: type Numeric interface { constraints.Integer | constraints.Float } func NumMax[T Numeric](a, b T) T { if a > b { return a } return b } func NumMin[T Numeric](a, b T) T { if a < b { return a } return b }
{ "domain": "codereview.stackexchange", "id": 45421, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go", "url": null }
go func NumMin[T Numeric](a, b T) T { if a < b { return a } return b } Clearly, the last 2 functions can replace the first 2, so why did someone add their own max function? It's possible that it was just a convenience thing (the programmer didn't know about the NumMax being a thing), but in this particular case (and full disclosure: this is a real thing I've seen while working on a large project): when you have over 100k lines of code, it's very likely a max function like this already exists somewhere, so what do you, as a responsible person do? You look in the most obvious places, and do a quick search for func Max, only to discover that your search comes up empty. You shrug and think that it must not be as common a thing to need as you initially thought, so you just write it in the package you need, and call it a day. All this to say: names matter a lot. I'll leave it at that for now. I've been fighting the urge to bring this up, because you mentioned you're an experienced programmer, and I do think that considering thread safety (although in go we call it "safe for concurrent use", because routines may or may not be executed on different threads) is a hallmark of experience. That being said, to address concurrency concerns in their entirety, I really ought to add that, even though your cache implementation (through the functions you've shared) is safe for concurrent access, the values you're returning are still a map[string]any. Once you get those maps from the cache, you're still just dealing with a map which can cause data-races when iterating over a map that is being written to concurrently.
{ "domain": "codereview.stackexchange", "id": 45421, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go", "url": null }
python, python-3.x, programming-challenge, community-challenge Title: Finding the position in a triangle for the given challenge Question: The LAMBCHOP doomsday device takes up much of the interior of Commander Lambda's space station, and as a result the prison blocks have an unusual layout. They are stacked in a triangular shape, and the bunny prisoners are given numerical IDs starting from the corner, as follows: | 7 | 4 8 | 2 5 9 | 1 3 6 10 Each cell can be represented as points (x, y), with x being the distance from the vertical wall, and y being the height from the ground. For example, the bunny prisoner at (1, 1) has ID 1, the bunny prisoner at (3, 2) has ID 9, and the bunny prisoner at (2,3) has ID 8. This pattern of numbering continues indefinitely (Commander Lambda has been taking a LOT of prisoners). Write a function answer(x, y) which returns the prisoner ID of the bunny at location (x, y). Each value of x and y will be at least 1 and no greater than 100,000. Since the prisoner ID can be very large, return your answer as a string representation of the number. Here is my solution: y = int(input()) x = int(input()) sum_in_x = 1 for i in range(x): sum_in_x = sum_in_x + range(x)[i] in_sum =i + 2 sum_in_y = sum_in_x for j in range(y - 1): sum_in_y = sum_in_y + in_sum in_sum += 1 print(sum_in_y) It works and generates the needed solutions, but I am trying to understand if there are better ways of doing this. Answer: Your current algorithm is very inefficient. I would use the following algorithmic approach: def answer(x, y): y_diff = y - 1 corner = x + y_diff id = corner * (corner + 1) // 2 id -= y_diff return str(id)
{ "domain": "codereview.stackexchange", "id": 45422, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, programming-challenge, community-challenge", "url": null }
python, python-3.x, programming-challenge, community-challenge This method takes advantage of basic algebra. It uses the sum of the arithmetic progression of x to calculate the id of the bottom right corner, and then subtracts the difference of the input coordinate from the bottom right corner. The reason it take the y difference is because moving 45 degrees diagonally down right is equivalent to moving down (y-1) units and moving right (y-1) units. Is is much more efficient than your current method: instead of an increasing numbering of iterations through range, it does one multiplication. Benchmark Testing your code compared to mine, mine runs about 10,000 to 100,000 times faster for random values of x and y between 1 and 100000. This is a very significant performance difference. Additionally, in benchmarking, I discovered a slight bug in your current implementation. I didn't analyze your implementation deeply to understand it, but it seems that your current implementation returns an output corresponding to the reversed inputs (so for example, if I input (3, 2), the output is correct for (2, 3).) I suspect this may have been missed in your personal testing because the input is reversed of traditional coordinate order, i.e. you ask for y coordinate input before you ask for x coordinate input. I fixed this in my testing by switching all occurrences of x (and related variables) with y and vice versa. Some notes Write a function answer(x, y) which returns the prisoner ID of the bunny at location (x, y). So it seems your answer should be in the form: def answer(x, y): # ... algorithm return str(output) Also, use consistent spacing: in_sum =i + 2 to in_sum = i + 2 And take advantage of +=: sum_in_x = sum_in_x + range(x)[i] to sum_in_x += range(x)[i] sum_in_y = sum_in_y + in_sum to sum_in_y += in_sum
{ "domain": "codereview.stackexchange", "id": 45422, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, programming-challenge, community-challenge", "url": null }
python, file, serialization, tkinter, text-editor Title: A little Python hex editor Question: First off I'm quite new to Python, there will be a lot of messy/overcomplicated code, that's why I'm posting on this site. This code is written in Python (2.7) using the Tkinter library. Questions To allow for viewing/editing large files, I am loading the file and saving it to a variable, then displaying only the text that can be seen. Is this the best way of going about this? I have chosen to use a class here, because there are a lot of global variables. I also want to allow for scalability, so is this a good choice? If I came back to this in a year or so, would I be able to understand what is going on? Any and all criticism to do with formatting and Pythonicness is welcome. Code class Window(): def __init__(self): """imports and define global vars""" import binascii, Tkinter, tkFileDialog self.binascii = binascii self.Tkinter = Tkinter self.tkFileDialog = tkFileDialog self.root = self.Tkinter.Tk() self.lineNumber = 0 self.fileName = "" self.lines = [] self.width = 47 self.height = 20 self.lastLine = 0.0 self.rawData = "" self.defaultFiles = ( ("Hexadecimal Files", "*.hex"), ("Windows Executables", "*.exe"), ("Linux Binaries", "*.elf"), ("all files", "*.*") )
{ "domain": "codereview.stackexchange", "id": 45423, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file, serialization, tkinter, text-editor", "url": null }
python, file, serialization, tkinter, text-editor def resize(self, event = None): """called when the window is resized. Re-calculates the chars on each row""" self.width = self.mainText.winfo_width() / 8 self.height = self.mainText.winfo_height() / 16 if not self.width / 3 == 0: self.data = self.binascii.hexlify(self.rawData)[2:] dataSave = self.data lines = [] chars = self.width - (self.width / 3) while len(self.data) > 0: if len(self.data) >= chars: lines.append(self.data[:chars]) self.data = self.data[chars:] else: lines.append(self.data) self.data = "" self.data = dataSave self.lines = lines self.mainText.delete("1.0","end") self.mainText.insert("1.0", self.getBlock(self.lineNumber)) def openFile(self, filename): """Opens a file and displays the contents""" self.fileName = filename with open(filename,"rb") as f: rawData = chr(0) + f.read() self.rawData = rawData self.data = self.binascii.hexlify(rawData)[2:] dataSave = self.data lines = [] chars = self.width - (self.width / 3) print self.width while len(self.data) > 0: if len(self.data) >= chars: lines.append(self.data[:chars]) self.data = self.data[chars:] else: lines.append(self.data) self.data = "" self.data = dataSave self.lines = lines self.mainText.delete("1.0","end") self.mainText.insert("1.0", self.getBlock(0)) self.lineNumber = 0 def saveFile(self, filename, data = None): """saves the 'lines' variable (keeps track of the data) to a file""" if data is None: data = "".join(self.lines)
{ "domain": "codereview.stackexchange", "id": 45423, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file, serialization, tkinter, text-editor", "url": null }
python, file, serialization, tkinter, text-editor if data is None: data = "".join(self.lines) with open(filename, "wb") as f: f.write(self.binascii.unhexlify(data)) def saveAll(self, event = None): """saves a file (for binding a key to)""" self.setBlock(self.mainText.get("1.0","end"),self.lineNumber) self.saveFile(self.fileName) def saveClose(self, event = None): """Saves and closes (for binding a key to""" self.saveAll() self.root.destroy()
{ "domain": "codereview.stackexchange", "id": 45423, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file, serialization, tkinter, text-editor", "url": null }
python, file, serialization, tkinter, text-editor def saveAsWindow(self, event = None): """Opens the 'save as' popup""" f = self.tkFileDialog.asksaveasfilename(filetypes = self.defaultFiles) if f is None or f is "": return else: self.saveFile(f) self.fileName = f def openWindow(self, event = None): """Opens the 'open' popup""" f = self.tkFileDialog.askopenfilename(filetypes = self.defaultFiles) if f is None or f is "": return else: self.openFile(f)
{ "domain": "codereview.stackexchange", "id": 45423, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file, serialization, tkinter, text-editor", "url": null }
python, file, serialization, tkinter, text-editor def q(self, event = None): """quits (for binding a key to""" self.root.destroy() def neatify(self,data): """adds a space every 2 chars (splitss into bytes)""" out = "" for line in data: count = 0 for char in line: if count == 2: count = 0 out += " " + char else: out += char count += 1 out += "\n" return out def getBlock(self, lineNum): """gets a block of text with the line number corresponding to the top line""" self.formattedData = self.neatify(self.lines[lineNum:lineNum+self.height]) return self.formattedData def setBlock(self, data, lineNum): """sets a block (same as getBlock but sets)""" rawData = data.replace(" ","").split("\n") data = [] for line in rawData: if not line == "": data.append(line) if len(data) < self.height: extra = len(data) else: extra = self.height for i in range(lineNum,lineNum + extra): self.lines[i] = data[i - lineNum] def scrollTextUp(self, event = None): """Some may argue 'scrollTextDown' but this is what happens when you press the up arrow""" if not self.lineNumber <= 0: self.setBlock(self.mainText.get("1.0","end"),self.lineNumber) self.lineNumber -= 1 self.mainText.delete("1.0","end") self.mainText.insert("1.0", self.getBlock(self.lineNumber)) def scrollTextDown(self, event = None): """same as above except the opposite""" if not self.lineNumber >= len(self.lines) - self.height: self.setBlock(self.mainText.get("1.0","end"),self.lineNumber) self.lineNumber += 1
{ "domain": "codereview.stackexchange", "id": 45423, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file, serialization, tkinter, text-editor", "url": null }
python, file, serialization, tkinter, text-editor self.lineNumber += 1 self.mainText.delete("1.0","end") self.mainText.insert("1.0", self.getBlock(self.lineNumber))
{ "domain": "codereview.stackexchange", "id": 45423, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file, serialization, tkinter, text-editor", "url": null }
python, file, serialization, tkinter, text-editor def scroll(self, event = None, direction = None): """calls the correct scroll function""" if self.mainText.index("insert").split(".")[0] == str(self.height + 1): self.scrollTextDown() elif self.mainText.index("insert").split(".")[0] == "1": cursorPos = self.mainText.index("insert") self.scrollTextUp() self.mainText.mark_set("insert", cursorPos) def defineWidgets(self): """defines the widgets""" self.menu = self.Tkinter.Menu(self.root) self.filemenu = self.Tkinter.Menu(self.menu, tearoff = 0) self.filemenu.add_command(label = "Save", command = self.saveAll, accelerator = "Ctrl-s") self.filemenu.add_command(label = "Save as...", command = self.saveAsWindow, accelerator = "Ctrl-S") self.filemenu.add_command(label = "Open...", command = self.openWindow, accelerator = "Ctrl-o") self.filemenu.add_separator() self.filemenu.add_command(label = "Quit", command = self.saveClose, accelerator = "Ctrl-q") self.filemenu.add_command(label = "Quit without saving", command = self.root.destroy, accelerator = "Ctrl-Q") self.menu.add_cascade(label = "File", menu = self.filemenu) self.mainText = self.Tkinter.Text(self.root, width = 47, height = 20) def initWidgets(self): """initialises the widgets. Also key bindings etc""" self.mainText.pack(fill = "both", expand = 1) self.mainText.insert("1.0", self.getBlock(0)) self.root.config(menu = self.menu)
{ "domain": "codereview.stackexchange", "id": 45423, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file, serialization, tkinter, text-editor", "url": null }
python, file, serialization, tkinter, text-editor self.root.config(menu = self.menu) #up and down bound to the scroll function to check if the text should scroll self.root.bind("<Down>", self.scroll) self.root.bind("<Up>", self.scroll) self.root.bind("<Control-s>", self.saveAll) self.root.bind("<Control-o>", self.openWindow) self.root.bind("<Control-S>", self.saveAsWindow) self.root.bind("<Control-q>", self.saveClose) self.root.bind("<Control-Q>", self.q) self.root.bind("<Configure>", self.resize) self.root.protocol('WM_DELETE_WINDOW', self.saveClose) win = Window() win.defineWidgets() win.initWidgets() win.root.mainloop() Answer: Style PEP8 is the de-facto standard style guide for Python and adhering to it will make your code look like Python code to others: variable and method names should be snake_case; imports should come at the top of the file ordered standard lib modules first and third party modules later; arguments with default value should be defined without a space around the = sign. You should also put the top-level code under an if __name__ == '__main__' guard to ease testing and reusability. Also: this print in the middle of the code feels like debugging information, you should remove it; Tkinter is usually imported as tk; some of the docstrings are just repeating the method names and are not usefull, besides their formatting feels weird. See PEP257 for hindsights.
{ "domain": "codereview.stackexchange", "id": 45423, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file, serialization, tkinter, text-editor", "url": null }
python, file, serialization, tkinter, text-editor Code organization You have several place where code is duplicated and could benefit from refactoring, such as opening a file — resizing the window, scrolling up — scrolling down, saving the current content of mainText into memory… You also have the defineWidgets and initWidgets functions that need to be called by the users of your class before doing anything with it. You should avoid such situation by calling them yourself in your constructor. I would also try to organize the method of your class by logical groups so it is easier to follow. Widget-related stuff, file-content related stuff, popup-related stuff, and view-window related stuff can be a good hierarchy. Processing file content In two places, you need to create groups of data of a certain length (when you open a file/resize the window and in neatify). There is a neat itertools recipe for that: grouper. If you adapt it to work only with characters, it can become: def character_grouper(iterable, n): """Group consecutive n values of iterable into tuples. Pad the last tuple with '' if need be. >>> list(character_grouper('This is a test', 3)) [('T', 'h', 'i'), ('s', ' ', 'i'), ('s', ' ', 'a'), (' ', 't', 'e'), ('s', 't', '')] """ args = [iter(iterable)] * n return itertools.izip_longest(*args, fillvalue='') Proposed improvements from binascii import hexlify, unhexlify from itertools import izip_longest import Tkinter as tk import tkFileDialog as tk_file_dialog DEFAULT_FILE_TYPES = ( ("Hexadecimal Files", "*.hex"), ("Windows Executables", "*.exe"), ("Linux Binaries", "*.elf"), ("all files", "*.*") ) def character_grouper(iterable, n): """Group consecutive n values of iterable into tuples. Pad the last tuple with '' if need be.
{ "domain": "codereview.stackexchange", "id": 45423, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file, serialization, tkinter, text-editor", "url": null }
python, file, serialization, tkinter, text-editor Pad the last tuple with '' if need be. >>> list(character_grouper('This is a test', 3)) [('T', 'h', 'i'), ('s', ' ', 'i'), ('s', ' ', 'a'), (' ', 't', 'e'), ('s', 't', '')] """ args = [iter(iterable)] * n return izip_longest(*args, fillvalue='') class Window(): def __init__(self, width=47, height=20): """Create an editor window. Editor will allow you to select a file to inspect and modify its content as hexadecimal values. """ self.root = tk.Tk() self.width = width self.height = height self.filename = "" self.raw_data = "" self.lines = [] self.line_number = 0 self.create_widgets() def run(self): """Start the Tkinter main loop on this window and wait for its destruction""" self.root.mainloop() def create_widgets(self): self.menu = tk.Menu(self.root) self.filemenu = tk.Menu(self.menu, tearoff=0) self.filemenu.add_command(label="Save", command=self.save_file, accelerator="Ctrl-s") self.filemenu.add_command(label="Save as...", command=self.saveas_window, accelerator="Ctrl-S") self.filemenu.add_command(label="Open...", command=self.open_window, accelerator="Ctrl-o") self.filemenu.add_separator() self.filemenu.add_command(label="Quit", command=self.save_and_close, accelerator="Ctrl-q") self.filemenu.add_command(label="Quit without saving", command=self.root.destroy, accelerator="Ctrl-Q") self.menu.add_cascade(label="File", menu=self.filemenu) self.main_text = tk.Text(self.root, width=self.width, height=self.height) self.main_text.pack(fill="both", expand=1) self.main_text.insert("1.0", self.format_current_buffer())
{ "domain": "codereview.stackexchange", "id": 45423, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file, serialization, tkinter, text-editor", "url": null }
python, file, serialization, tkinter, text-editor self.root.config(menu=self.menu) self.root.bind("<Down>", self.scroll) self.root.bind("<Up>", self.scroll) self.root.bind("<Control-s>", self.save_file) self.root.bind("<Control-o>", self.open_window) self.root.bind("<Control-S>", self.saveas_window) self.root.bind("<Control-q>", self.save_and_close) self.root.bind("<Control-Q>", self.close) self.root.bind("<Configure>", self.resize) self.root.protocol('WM_DELETE_WINDOW', self.save_and_close) def resize(self, event=None): """Update the amount of characters on each row when the window is resized""" self.width = self.main_text.winfo_width() / 8 self.height = self.main_text.winfo_height() / 16 if self.width / 3 != 0: self._preprocess_raw_data() def open_file(self, filename): """Open a file and display the content""" self.filename = filename with open(filename, "rb") as f: self.raw_data = chr(0) + f.read() self.line_number = 0 self._preprocess_raw_data() def _preprocess_raw_data(self): """Convert the content of a file to a list of lines suitable for the current width. """ data = hexlify(self.raw_data)[2:] chars = self.width - (self.width / 3) self.lines = [ "".join(line) for line in character_grouper(data, chars) ] self.main_text.delete("1.0", "end") self.main_text.insert("1.0", self.format_current_buffer()) def save_file(self, event=None): """Save the current modifications into the current file""" self.update_current_buffer() with open(self.filename, "wb") as f: f.write(unhexlify("".join(self.lines))) def save_and_close(self, event=None): self.save_file() self.close() def close(self, event=None): self.root.destroy()
{ "domain": "codereview.stackexchange", "id": 45423, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file, serialization, tkinter, text-editor", "url": null }
python, file, serialization, tkinter, text-editor def close(self, event=None): self.root.destroy() def saveas_window(self, event=None): """Open the 'save as' popup""" f = tk_file_dialog.asksaveasfilename(filetypes=DEFAULT_FILE_TYPES) if f: self.filename = f self.save_file() def open_window(self, event=None): """Open the 'open' popup""" f = tk_file_dialog.askopenfilename(filetypes=DEFAULT_FILE_TYPES) if f: self.open_file(f) def format_current_buffer(self): """Create the text to display in the main text area. Each line of the current view window ("height" lines from current line) is formatted by inserting a space every two characters. """ content = self.lines[self.line_number:self.line_number + self.height] return "\n".join(" ".join(map("".join, character_grouper(line, 2))) for line in content) def update_current_buffer(self): """Save the modification made in the main text area into memory""" content = self.main_text.get("1.0", "end").replace(" ", "").split("\n") for i, line in enumerate(filter(bool, content)): self.lines[i + self.line_number] = line def scroll(self, event=None, direction=None): """Scroll up or down depending on the current position""" cursor_position = self.main_text.index("insert") current_line = int(cursor_position.split(".")[0]) if current_line == self.height + 1: line_movement = 1 elif current_line == 1: line_movement = -1 else: return if 0 < self.line_number < len(self.lines) - self.height: self.update_current_buffer() self.line_number += line_movement self.main_text.delete("1.0", "end") self.main_text.insert("1.0", self.format_current_buffer()) self.main_text.mark_set("insert", cursor_position) if __name__ == '__main__': Window().run()
{ "domain": "codereview.stackexchange", "id": 45423, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file, serialization, tkinter, text-editor", "url": null }
python, file, serialization, tkinter, text-editor if __name__ == '__main__': Window().run() Side note If you are new to Python, then I highly recommend to use Python 3 instead of Python 2 whose support is reaching end of life. You will benefit from the latest modules and features.
{ "domain": "codereview.stackexchange", "id": 45423, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, file, serialization, tkinter, text-editor", "url": null }
c#, entity-framework Title: EF save method that has three conditions Question: I created this save method that has two conditions. One condition is checking if coordinatorsId is not 0 and another one is checking if Subject is not empty string. Is there a better way to do the two conditions? I have come up with the below for the SaveRequest entity. I am looking for advice on ways to improve this. I am using EntityFramework version=6.4.4 public ResultStatus SaveRequest(List<int> RequestIds,int DictionaryId, string Subject, int coordinatorsId) { ResultStatus resultStatus = new ResultStatus(); using (var db = new Entities()) { using (DbContextTransaction dbTran = db.Database.BeginTransaction()) { try { foreach (var RequestId in RequestIds) { var efRequest = db.Requests.Where(x => x.RequestId == RequestId).FirstOrDefault(); if (DictionaryId != 0) { efRequest.DictionaryId= DictionaryId; } if (Subject != ""){ efRequest.Subject = Subject; } if (coordinatorsId != 0) { efRequest.coordinatorsId = coordinatorsId ; } db.SaveChanges(); } dbTran.Commit(); resultStatus.ResultCode = Convert.ToInt32(Enums.Result.Code.Success); resultStatus.Message = "Successfully Saved."; } catch (Exception ex) { resultStatus.ResultCode = Convert.ToInt32(Enums.Result.Code.Error); resultStatus.Message = ex.ToString(); dbTran.Rollback(); } } return resultStatus; } }
{ "domain": "codereview.stackexchange", "id": 45424, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, entity-framework", "url": null }
c#, entity-framework Answer: Let's start with proper names. Parameters and local variables must have camelCase style, properties must have PascalCase. When working with a database, the most important thing is to reduce the number of queries to it. Therefore, it may make sense to do some checks at the beginning of the method: if (requestIds.Count == 0) return resultStatus; if (dictionaryId == 0 && subject == "" && coordinatorsId == 0) return resultStatus; You receive one value from the database in a loop. This is very inefficient. It is much more profitable to get a set of values at once with one query. var requests = db.Requests.Where(x => requestIds.Contains(x.RequestId)).ToList(); foreach (var request in requests) { if (dictionaryId != 0) request.DictionaryId = dictionaryId; if (subject != "") request.Subject = subject; if (coordinatorsId != 0) request.CoordinatorsId = coordinatorsId; } db.SaveChanges();
{ "domain": "codereview.stackexchange", "id": 45424, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, entity-framework", "url": null }
java, beginner, game, console Title: Text based Java game "Battle Arena" Question: This is my first java program. I'm coming from a python background. This is a text based combat arena game. Are there any ways I could better implement the overall code structure? How might I improve the math of the attack() function? It prompts the user for a hero name, then generates hero and enemy objects of the character class with randomly generated Health, Defense, and Strength stats between 1-100 and prompts user for an option. 1 initiates battle 2 quits Selection 1 starts an attack iteration where: The game rolls for each character (random 1-6) to determine who strikes first and resolves the attack results, prints updated stats and returns to prompt the two options. Something slightly interesting happens when they tie the initiative roll. When a character's health is reduced below 1, the victor is announced and the game quits. Some announcer text is printed depending on different outcomes for interest. Game.java import java.util.Scanner; import java.io.*; public class Game { public class Character { int health; int defense; int strength; String cname; int init; public Character(String name) { health = getRandom(100, 1); defense = getRandom(100, 1); strength = getRandom(100, 1); cname = name; init = 0; } } static int getRandom(int max, int min) { int num = 1 + (int)(Math.random() * ((max - min) + 1)); return num; } static void cls() { System.out.print("\033[H\033[2J"); System.out.flush(); } static String printWelcome() { cls(); System.out.println("Welcome to the arena!"); Scanner scanObj = new Scanner(System.in); System.out.println("Enter your hero\'s name:"); String heroName = scanObj.nextLine(); cls(); return heroName; }
{ "domain": "codereview.stackexchange", "id": 45425, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, game, console", "url": null }
java, beginner, game, console static void printStats(Character c) { Console cnsl = System.console(); String fmt = "%1$-10s %2$-1s%n"; System.out.println("\n" + c.cname + "\'s Stats:\n---------------"); cnsl.format(fmt, "Health:", c.health); cnsl.format(fmt, "Defense:", c.defense); cnsl.format(fmt, "Strength:", c.strength); } static void clash(Character h, Character e) { System.out.println("\n" + e.cname + " took a cheapshot!\n(Croud gasps)\nBut " + h.cname + " blocked it in the nick of time!\n(Croud Chears)\n"); doBattle(h, e); } static Character roll(Character h, Character e) { h.init = getRandom(6, 1); e.init = getRandom(6, 1); if (h.init > e.init) { return h; } else if (h.init < e.init) { return e; } else { clash(h, e); return e; } } static void attack(Character a, Character d) { int apts; String aname = a.cname; String dname = d.cname; if (d.defense > a.strength) { apts = 1; d.defense = d.defense - ((d.defense % a.strength) + 1); System.out.println("\n" + dname + " blocked " + aname + "\'s attack and took no damage!\n(Croud chears)\n"); } else { apts = a.strength - d.defense; d.health = d.health - apts; System.out.println("\n" + aname + " strikes " + dname + " for " + apts + " points of damage!\n(Croud boos)\n"); } if (d.health < 1) { d.health = 0; } } static void doBattle(Character h, Character e) { Character goesFirst = roll(h, e); System.out.println(goesFirst.cname + " takes initiative!\n"); Character defender; if (h.cname == goesFirst.cname) { defender = e; } else { defender = h; } attack(goesFirst, defender); // System.out.println(defender.cname); }
{ "domain": "codereview.stackexchange", "id": 45425, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, game, console", "url": null }
java, beginner, game, console static int getOption() { Scanner scanObj = new Scanner(System.in); System.out.println("\nEnter option: (1 to battle, 2 to escape!)"); int option = scanObj.nextInt(); return option; } public static void main(String[] args) { Game myGame = new Game(); Game.Character hero = myGame.new Character(printWelcome()); Game.Character enemy = myGame.new Character("Spock"); System.out.println("\nAvast, " + hero.cname + "! Go forth!"); // printStats(hero); // printStats(enemy); while (hero.health > 0 && enemy.health > 0) { printStats(hero); printStats(enemy); int option = getOption(); cls(); if (option == 1) { doBattle(hero, enemy); } else if (option == 2) { System.out.println("YOU COWARD!"); System.exit(0); } else { System.out.println("Invalid Option"); } } printStats(hero); printStats(enemy); if (hero.health < 1) { System.out.println(enemy.cname + " defeated " + hero.cname + "!\n(Cround boos aggressively)\nSomeone from the croud yelled \"YOU SUCK!\"\n"); } else { System.out.println(hero.cname + " utterly smote " + enemy.cname + "!\n(Croud ROARS)\n"); } } }
{ "domain": "codereview.stackexchange", "id": 45425, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, game, console", "url": null }
java, beginner, game, console Answer: Make as many of the properties of Character to be final as possible. init (which should be named initiative) should not be a property at all. Delete getRandom. Pass in an instance of Random for testability, and call its nextInt. Make Character a static inner class - it won't be able to access properties of Game, and that's a good thing - it's better to pass them in explicitly when needed. Avoid static abuse on your outer functions. Most of your Game methods should be instance methods with access to the member variables they need. cls (clearing the screen) is an anti-feature. The user can clear the screen when they want through their own terminal controls. Don't \' escape apostrophes when that isn't needed. There is no need for Console in this application. Make more use of printf instead of string concatenation. Don't abbreviate variables like h (hero) and e (enemy) to single letters; spell them out. Various spelling issues like croud (should be crowd); enable spellcheck. Make your verb tenses agree - they should all be in present tense, instead of a mix of past and present tense. clash calling doBattle is recursion, which is not a good idea; you almost certainly shouldn't be recursing here. Don't nextInt for your option. Since it's only used in a simple comparison, leave it as a string; it removes the potential for an exception and simplifies validation. Whenever possible, construct your console formatting so that it produces logically-related paragraphs. Also, prefer accepting terminal input on the same line as the prompt. Suggested package com.stackexchange; import java.util.Optional; import java.util.Random; import java.util.Scanner;
{ "domain": "codereview.stackexchange", "id": 45425, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, game, console", "url": null }