text
stringlengths
1
2.12k
source
dict
python, beginner if split_1_choice not in ['hit', 'stand']: print('Please type one of the accepted words.') # split 1 stand elif split_1_choice == 'stand': split_1_result = 'stand' split_flag_1 = False sleep(.25) system('clear') print(f'\nThe dealer is showing:\n' f'{dealer_hand[0]}') hand = player_split_1 print('\nSplit 1 hand:') hand = player_split_1 print_cards(hand) print('\n') hand = player_split_2 print('Split 2 hand:') print_cards(hand) # split 1 hit elif split_1_choice == 'hit': sleep(.25) system('clear') card_draw = draw() player_split_1.append(card_draw[0]) split_total_1 += card_draw[1] print(f'\nThe dealer is showing:\n' f'{dealer_hand[0]}') hand = player_split_1 print('\nSplit 1 hand:') hand = player_split_1 print_cards(hand) print('\n') hand = player_split_2 print('Split 2 hand:') print_cards(hand) # split 2 action prompt elif split_total_2 < 21 and split_flag_2 == True: split_2_choice = input(f'\n\nWould you like to Hit, or Stand on split 2?: ').lower() sleep(.25) system('clear')
{ "domain": "codereview.stackexchange", "id": 44645, "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, beginner", "url": null }
python, beginner if split_2_choice not in ['hit', 'stand']: print('Please type one of the accepted words.') # split 2 stand elif split_2_choice == 'stand': split_2_result = 'stand' split_flag_2 = False player_flag = False sleep(.25) system('clear') # split 2 hit elif split_2_choice == 'hit': sleep(.25) system('clear') card_draw = draw() player_split_2.append(card_draw[0]) split_total_2 += card_draw[1] print(f'\nThe dealer is showing:\n' f'{dealer_hand[0]}') hand = player_split_1 print('\nSplit 1 hand:') hand = player_split_1 print_cards(hand) print('\n') hand = player_split_2 print('Split 2 hand:') print_cards(hand) # player action prompt after first round elif player_total < 21 and len(player_hand) >= 3: player_choice = input(f'Would you like to Hit, or Stand?: ').lower() sleep(.25) system('clear') if player_choice not in ['hit', 'stand']: print('Please type one of the accepted words.') # player stand elif player_choice == 'stand': player_result = 'stand' player_flag = False sleep(.25) system('clear') # player hit elif player_choice == 'hit': sleep(.25) system('clear') card_draw = draw() player_hand.append(card_draw[0]) player_total += card_draw[1] hand = player_hand print('\nYour hand:\n') print_cards(hand) print('\n\n')
{ "domain": "codereview.stackexchange", "id": 44645, "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, beginner", "url": null }
python, beginner # if split 1 is over 21, check for aces, if found reduce total by 10 so ace equals 1 elif split_total_1 > 21 and split_flag_1 == True: for card in player_split_1: if card == 'A': # changes list item A to x so the same ace doesn't get flagged more than once player_split_1[player_split_1.index(card)] = 'x' split_total_1 -= 10 break if split_total_1 > 21: split_1_result = "bust" split_flag_1 = False sleep(.25) system('clear') # # if split 2 is over 21, check for aces, if found reduce total by 10 so ace equals 1 elif split_total_2 > 21 and split_flag_2 == True: for card in player_split_2: if card == 'A': # # changes list item A to x so the same ace doesn't get flagged more than once player_split_2[player_split_2.index(card)] = 'x' split_total_2 -= 10 break if split_total_2 > 21: split_2_result = "bust" split_flag_2 = False player_flag = False sleep(.25) system('clear') # # if player hand is over 21, check for aces, if found reduce total by 10 so ace equals 1 elif player_total > 21 and split_flag_1 == False: for card in player_hand: if card == 'A': # # changes list item A to x so the same ace doesn't get flagged more than once player_hand[player_hand.index(card)] = 'x' player_total -= 10 break if player_total > 21: player_result = "bust" player_flag = False sleep(.25) system('clear')
{ "domain": "codereview.stackexchange", "id": 44645, "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, beginner", "url": null }
python, beginner # returns removed aces to hands for ace in player_hand: if ace == 'x': player_hand[player_hand.index(ace)] = 'A' for ace in dealer_hand: if ace == 'x': dealer_hand[dealer_hand.index(ace)] = 'A' for ace in player_split_1: if ace == 'x': player_split_1[player_split_1.index(ace)] = 'A' for ace in player_split_2: if ace == 'x': player_split_2[player_split_2.index(ace)] = 'A' # prints dealer hand print('Dealer hand:') hand = dealer_hand print_cards(hand) # compares cards if there was a split if split_total_1 > 0: print('\nSplit 1 hand:') hand = player_split_1 print_cards(hand) if split_1_result == 'blackjack': player_wallet += 15 print('\n\nBlackJack!') elif split_1_result == 'bust': print('\nYou busted, better luck next time.\n') elif dealer_result == 'bust': print('\nThe dealer busted.\n\n' 'Congratulations! You won $5!') player_wallet += 5 elif split_total_1 == dealer_total: player_wallet += 5 print('Draw. You initial bet back.') elif split_total_1 > dealer_total: player_wallet += 10 print(f'Congratulations! You won $5!') else: print('\nYou lost, better luck netxt time.\n') print('\nSplit 2 hand:') hand = player_split_2 print_cards(hand)
{ "domain": "codereview.stackexchange", "id": 44645, "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, beginner", "url": null }
python, beginner print('\nSplit 2 hand:') hand = player_split_2 print_cards(hand) if split_2_result == 'blackjack': player_wallet += 15 print('\n\nBlackJack!') elif split_2_result == 'bust': print('\nYou busted, better luck next time.\n') elif dealer_result == 'bust': print(dealer_total) print('\nThe dealer busted.\n\n' 'Congratulations! You won $5!') player_wallet += 10 elif split_total_1 == dealer_total: player_wallet += 5 print('Draw. You initial bet back.') elif split_total_2 > dealer_total: player_wallet += 10 print(f'Congratulations! You won $5!') else: print('\nYou lost, better luck netxt time.\n')
{ "domain": "codereview.stackexchange", "id": 44645, "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, beginner", "url": null }
python, beginner # compares player hand if no split else: print('\nYour hand:') hand = player_hand print_cards(hand) if player_result == 'blackjack': player_wallet += 15 print('\n\nBlackJack!') elif player_result == 'bust': print('\n\nYou busted, better luck next time.\n') elif dealer_result == 'bust': if player_result == 'double': print('\nThe dealer busted.\n\n' 'Congratulations! You won $10!') player_wallet += 20 else: print('\nThe dealer busted.\n\n' 'Congratulations! You won $5!') player_wallet += 10 elif player_result == 'double' and player_total > dealer_total: print('\n\nCongratulations! You won $10\n') player_wallet += 20 elif split_total_1 == dealer_total: if player_result == 'double': player_wallet += 10 print('Draw. You initial bet back.') else: player_wallet += 5 print('Draw. You initial bet back.') elif player_total > dealer_total: player_wallet += 10 print(f'\n\nCongratulations! You won $5!') else: print('\n\nYou lost, better luck netxt time.\n') # print balance print(f'Your balance is:\n' f'${player_wallet}') # prompt player to play again play_again = input(f'\nWould you like to keep playing? Type yes or no: ').lower() while True: if play_again not in ['yes', 'no']: print('Please type yes or no.') break elif play_again == 'yes': sleep(.25) system('clear') blackjack(player_wallet) blackjack(player_wallet) library import random
{ "domain": "codereview.stackexchange", "id": 44645, "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, beginner", "url": null }
python, beginner blackjack(player_wallet) library import random cards = { '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10, 'A': 11 } def draw(): draw_card = random.choice(list(cards.items())) return draw_card def print_cards(hand): for card in range(len(hand)): print(hand[card], end=" ") Answer: PEP-8 PEP-8 is the standard style recommendation for Python. In it, it includes things like how many blank lines, how much indentation, recommendations for variable naming and casing. There are linters (Flake8, Pylint and others) which check your code against PEP-8 and issue useful warnings. In your case there are several simple and obvious things. This flags things like: tmp.py:251:50: E712 comparison to True should be 'if cond is True:' or 'if cond:' tmp.py:340:49: E712 comparison to False should be 'if cond is False:' or 'if not cond:' tmp.py:391:19: F541 f-string is missing placeholders tmp.py:31:0: C0103: Constant name "player_wallet" doesn't conform to UPPER_CASE naming style (invalid-name) Small things, but things which make a big difference to someone approaching your code for the first time, as well as how to fix them. Style In Python (and most other languages), we don't tend to use if split_flag_2 == True #or if split_flag_2 == False We can simply say if split_flag_2 #or if not split_flag_2 If we want to be explicit about the type if split_flag_2 is True but it's not terribly common that we need to do that. Library Let's just take a quick look at your "library" first before we get started since it's smaller. I won't go fully into classes since you've said you're not using them yet, but you might want to take a quick look at dataclass for storing your cards, it would look like: from dataclasses import dataclass @dataclass class Card: face: str val: int
{ "domain": "codereview.stackexchange", "id": 44645, "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, beginner", "url": null }
python, beginner @dataclass class Card: face: str val: int cards = (Card('2', 2), Card('3', 3), ... Card('K', 10), Card('A', 11)) ACE = cards[-1] ACE.face # => 'A' ACE.val # => 11 It's just a neat way of encapsulating these data like a tuple with names (there is also collections.namedtuple), this also means your draw would just become: def draw(): return random.choice(cards) In Python it's usual to just loop over the elements of a list rather than iterating through the range and then the elements. def print_cards(hand): for card in hand: print(card, end=" ") if we need the index, we can do def print_cards(hand): for ind, card in enumerate(hand): print(f"{ind}: {card}", end=" ") Structure Your problem isn't so much your use of if-elif, but more the fact that you have one huge, monolithic function. As we tackle this, we're going to break this down into smaller functions. Look at the warnings given by our linter tmp.py:33:0: R0912: Too many branches (89/12) (too-many-branches) tmp.py:33:0: R0915: Too many statements (346/50) (too-many-statements) Phew! That's a lot. Let's take a look at the function and see what it does: Blackjack: Give free money if bankrupt Dealer AI Dealer's removed aces Display dealer cards Player drawing Get Player input (multiple times) Split Double Stand Hit Check hand bust/validity Player and dealer removed aces Reveal hands Compares hands (winners) Update balance Ask to play again (recurse) Clear screen That's a lot of responsibilities for one little function. Each of these could (and mostly should) be their own functions. Main Let's first of all look at what sorts of things we might want in the core loop. The core loop to me goes like this: Ask to play Take bets (free money?) Play round Update balance Clear screen That's simple enough to do, we extract those bits from the blackjack function into a new main. def main(): player_wallet = 1000
{ "domain": "codereview.stackexchange", "id": 44645, "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, beginner", "url": null }
python, beginner while True: # print balance system('clear') print(f'Your balance is:\n ${player_wallet}') blackjack(player_wallet) # prompt player to play again while True: play_again = input('\nWould you like to keep playing? Type yes or no: ').lower() if play_again == 'no': return if play_again == 'yes': break print('Please type yes or no.') # deposits money if player hits $0 if player_wallet <= 0: print("Looks like you're a little short, have $100") player_wallet += 100 Now, we could make this take arguments to initialise the wallet and things, but we'll just leave it here for now. Another advantage to this is that we can import this code into something else and use it elsewhere. To this end we should also use a "main guard": if __name__ == "__main__": ... which only runs if the code is called directly as python blackjack.py Dealer AI Let's now go back to the top and look at our dealer AI. (After breaking it off into its own function). dealer_flag seems to be just whether the dealer is over 17. So why not make it that? The dealer drawing their card is always a sequence of 3 things: get card increment total add card to hand We can make that a function. def draw_to_hand(hand, total): face, value = draw() out_hand = hand + [face] out_total = total + value return out_hand, out_total
{ "domain": "codereview.stackexchange", "id": 44645, "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, beginner", "url": null }
python, beginner now this doesn't matter if this is our dealer's hand or our player's hand. Convenient! (N.B. when you learn classes, this is probably a method on a Hand). Realistically, I probably wouldn't do it this way, and I would make computing the total a function on hands. What's the difference between a "21" result and a "stand" result with total 21? I think we can remove the distinction. If we want to draw 2 cards on turn 0, we can move that outside the loop, dealer_hand will never be 0 outside of this. Likewise, blackjack will never occur outside of round 1, we can move that outside too. Since we always draw to 17, we can just loop over that and if we go over, but have aces, we go back down under 17 and then draw back to 17. When we're searching for aces we can check if there is an ace, then use index to find it. if 'A' in dealer_hand: dealer_hand[dealer_hand.index('A')] = 'x' dealer_total -= 10 To return the aces, we could use a list comprehension: dealer_hand = [card if card != 'x' else 'A' for card in dealer_hand] or dealer_hand = [card.sub('x','A') for card in dealer_hand] Throughout all of this, I'm thinking that you might just want hand to be a string (which you can think of as a list of chars if that helps) which has convenient methods for doing a lot of the things you're wanting to do. (find, sub) still has in checking and is iterable. But there we are, we've refactored our dealer: def dealer_turn(): # creates empty list for dealer hand, sets flag for while loop and sets dealer total to 0 dealer_hand = [] dealer_total = 0 # draws cards for dealer and returns result dealer_hand, dealer_total = draw_to_hand(dealer_hand, dealer_total) dealer_hand, dealer_total = draw_to_hand(dealer_hand, dealer_total) if dealer_total == 21: dealer_result = "blackjack" return dealer_hand, dealer_total, dealer_result while dealer_total < 17: dealer_hand, dealer_total = draw_to_hand(dealer_hand, dealer_total)
{ "domain": "codereview.stackexchange", "id": 44645, "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, beginner", "url": null }
python, beginner if dealer_total > 21 and 'A' in dealer_hand: dealer_hand[dealer_hand.index('A')] = 'x' dealer_total -= 10 # Could do # dealer_result = 'stand' if dealer_total <= 21 else 'bust' if dealer_total <= 21: dealer_result = 'stand' elif dealer_total > 21: dealer_result = "bust" # returns dealers removed aces dealer_hand = [card if card != 'x' else 'A' for card in dealer_hand] return dealer_hand, dealer_total, dealer_result Victory checking Before I take a look at handling the player's turn, I'm going to zoop down to the bottom and look at comparing our victories. You have special cases for each kind of victory, so we're going to split it off into a function, which compares hands, results and totals. def check_victory(player, dealer): # Remember how earlier we returned a tuple so we can unpack (again, nicer as a namedtuple or dataclass) player_hand, player_total, player_result = player dealer_hand, dealer_total, dealer_result = dealer ... So this means, that we can pass either both the split hands, or the player's hand to the same function and work out who has won. This also avoids typos (like you have in your victory check) print('\nSplit 2 hand:') hand = player_split_2 print_cards(hand) if split_2_result == 'blackjack': ... elif split_total_1 == dealer_total: # <---- TOTAL 1 So what are the possible results? Blackjack -> wallet += 2*bet Win w/ Double -> wallet += 2*bet Win -> wallet += bet Push -> wallet += 0 Lose -> wallet -= bet Lose w/ Double -> wallet -= 2*bet N.B. This is the only place where the wallet really changes, we don't have to keep track of it beyond here we can just add or subtract here. The check_victory function might return the multiplier on your bet (-2, -1, 0, 1, 2) and increment the wallet based on that.
{ "domain": "codereview.stackexchange", "id": 44645, "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, beginner", "url": null }
python, beginner EDIT: Couple of notes inspired by ggorlen in the comments Enum aside Here, I suggested using: (-2, -1, 0, 1, 2) as scaling factors. Strictly this is not the best coding practice and would be called "magic numbers". Realistically, what we'd want here is an "enumeration" which is a consistent way of grouping constant values to names, but again these are classes and I'm trying to avoid those. The same goes for <x>_result and anywhere where you have an anonymous string or int whose value is one of a set and needs to be checked elsewhere. The advantage of enums is that they check for typos (asking for an undefined property is an error, checking against a misspelled string is fine), can be renamed/renumbered (and updated everywhere across the code) and they are self-documenting as coherent groups and support full docstrings. Side effects For better code in general we want to avoid things like printing or using global (external to the function) variables unless we have to, we call these things "side-effect"s, and a function which avoids side-effects "pure". Side effects include: Modifying files, or printing to screen Affecting or relying on variables from outside your function Using global Calling things like system time Using random numbers (sequences of random numbers rely on a consistent state to generate the next one) The reasons for wanting pure functions are manifold: The function clutters the screen and you can't disable the print without modifying the internals. I have my own variable with the same name as the global one which alters how the function behaves unpredictably They only depend on the arguments which go in, so they can be run wherever whenever and give the same answer for the same inputs which makes testing/debugging easier. (Advanced) They can be vectorised/parallelised trivially
{ "domain": "codereview.stackexchange", "id": 44645, "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, beginner", "url": null }
python, beginner In the example below, I have left the prints in the check_victory function, but they would probably be better handled by a separate print_victory function. See what you can do! So we can use your existing victory checks but rather than copy-pasting, we can call the function. This means that your entire check_victory block becomes: for rnd, res in enumerate(player): print(f'\nSplit {rnd} hand:') print_cards(res[0]) check_victory(res, dealer) I advise you to make the player's hand/total/result a list/tuple so you can iterate over them and avoid repeating yourself. Player Turn I'm going to leave the refactoring of player_turn as a task for you using what I've shown here. Use functions, break things down, avoid repeating yourself. A structure might look like: def player_turn(init_cards=None): if init_cards is None: player_hand, player_total = draw_to_hand(...) player_hand, player_total = draw_to_hand(...) ... if 'split': return (player_turn(player_hand[0]), player_turn(player_hand[1])) ... return ((player_hand_a, player_total_a, player_result_a),) Summary Overall, your problem isn't using if-elif but not breaking down your functions to do ONE job well (this is called the Single Responsibility Principle or SRP) and don't repeat yourself (or DRY). from os import system def draw_to_hand(hand, total): face, value = draw() out_hand = hand + [face] out_total = total + value return out_hand, out_total def dealer_turn(): # creates empty list for dealer hand, sets flag for while loop and sets dealer total to 0 dealer_hand = [] dealer_total = 0 # draws cards for dealer and returns result dealer_hand, dealer_total = draw_to_hand(dealer_hand, dealer_total) dealer_hand, dealer_total = draw_to_hand(dealer_hand, dealer_total) if dealer_total == 21: dealer_result = "blackjack" return
{ "domain": "codereview.stackexchange", "id": 44645, "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, beginner", "url": null }
python, beginner if dealer_total == 21: dealer_result = "blackjack" return while dealer_total < 17: dealer_hand, dealer_total = draw_to_hand(dealer_hand, dealer_total) if dealer_total > 21 and 'A' in dealer_hand: dealer_hand[dealer_hand.index('A')] = 'x' dealer_total -= 10 if 17 <= dealer_total <= 21: dealer_result = 'stand' elif dealer_total > 21: dealer_result = "bust" # returns dealers removed aces dealer_hand = [card if card != 'x' else 'A' for card in dealer_hand] return dealer_hand, dealer_total, dealer_result def check_victory(player, dealer): player_hand, player_total, player_result = player dealer_hand, dealer_total, dealer_result = dealer if player_result == 'blackjack': print('\n\nBlackJack!') return 2 elif player_result == 'bust': print('\nYou busted, better luck next time.\n') return -1 elif dealer_result == 'bust': print(dealer_total) print('\nThe dealer busted.\n\n' 'Congratulations! You won $5!') return 1 if player_result != 'double' else 2 elif player_total == dealer_total: print('Draw. You initial bet back.') return 0 elif player_total > dealer_total: print('Congratulations! You won $5!') return 1 if player_result != 'double' else 2 else: print('\nYou lost, better luck netxt time.\n') return -1 def player_turn(): ... if 'split': ... return ((player_hand_a, player_total_a, player_result_a), (player_hand_b, player_total_b, player_result_b)) else: ... return ((player_hand_a, player_total_a, player_result_a),) def blackjack(player_wallet): dealer = dealer_turn() # Would be nicer as a namedtuple, dataclass or class print(f'\nThe dealer is showing:\n' f'{dealer[0][0]}') player = player_turn()
{ "domain": "codereview.stackexchange", "id": 44645, "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, beginner", "url": null }
python, beginner player = player_turn() # prints dealer hand print('Dealer hand:') print_cards(dealer[0]) for rnd, res in enumerate(player): print(f'\nSplit {rnd} hand:') print_cards(res[0]) check_victory(res, dealer) def main(): player_wallet = 1000 while True: # print balance print(f'Your balance is:\n ${player_wallet}') blackjack(player_wallet) # prompt player to play again while True: play_again = input('\nWould you like to keep playing? Type yes or no: ').lower() if play_again == 'no': return if play_again == 'yes': break print('Please type yes or no.') system('clear') # deposits money if player hits $0 if player_wallet <= 0: print("Looks like you're a little short, have $100") player_wallet += 100 if __name__ == "__main__": main()
{ "domain": "codereview.stackexchange", "id": 44645, "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, beginner", "url": null }
c#, game, design-patterns, unity3d, strategy-pattern Title: Strategy Pattern Inside State Pattern Question: I'm making a fps game where I created a hierarchical state machine; the problem is the two types of movement (standing movement and crouching movement). They are very similar; the only difference is the velocity variable to apply the movement speed, so I decided to apply the strategy pattern and came up with this solution: using UnityEngine; using static PlayerStateMachine; public abstract class MovementState : MovementType { protected readonly PlayerCharacterController _playerCharacterController; protected readonly PlayerInputsManager _playerInputsManager; protected readonly PlayerStateParameters _playerStateParameters; protected readonly Transform _playerCameraTransform; protected Vector3 _playerDesiredDirectionVelocity; public MovementState(PlayerCharacterController playerCharacterController, PlayerInputsManager playerInputsManager, PlayerStateParameters playerStateParameters, Transform playerCameraTransform) { _playerInputsManager = playerInputsManager; _playerCharacterController = playerCharacterController; _playerCameraTransform = playerCameraTransform; _playerStateParameters = playerStateParameters; } } public abstract class MovementType { public abstract void Move(); } public class StandingMovement : MovementState { public StandingMovement(PlayerCharacterController playerCharacterController, PlayerInputsManager playerInputsManager, PlayerStateParameters playerStateParameters, Transform playerCameraTransform) : base(playerCharacterController, playerInputsManager, playerStateParameters, playerCameraTransform) { }
{ "domain": "codereview.stackexchange", "id": 44646, "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#, game, design-patterns, unity3d, strategy-pattern", "url": null }
c#, game, design-patterns, unity3d, strategy-pattern } public override void Move() { _playerDesiredDirectionVelocity = (_playerCameraTransform.forward * _playerInputsManager.PlayerMovementInputValue.z + _playerCameraTransform.right * _playerInputsManager.PlayerMovementInputValue.x).normalized * _playerStateParameters.PlayerStandingMovementSpeed; _playerCharacterController.ChangePlayerMovementDirection(_playerDesiredDirectionVelocity); } } public class CrouchedMovement : MovementState { public CrouchedMovement(PlayerCharacterController playerCharacterController, PlayerInputsManager playerInputsManager, PlayerStateParameters playerStateParameters, Transform playerCameraTransform) : base(playerCharacterController, playerInputsManager, playerStateParameters, playerCameraTransform) { } public override void Move() { _playerDesiredDirectionVelocity = (_playerCameraTransform.forward * _playerInputsManager.PlayerMovementInputValue.z + _playerCameraTransform.right * _playerInputsManager.PlayerMovementInputValue.x).normalized * _playerStateParameters.PlayerCrouchedMovementSpeed; _playerCharacterController.ChangePlayerMovementDirection(_playerDesiredDirectionVelocity); } } Then, inside the movement states I just Tick like this: using System; using System.Collections.Generic; using UnityEngine; public class PlayerStandingMovingState : State { private readonly PlayerStandingRootState _playerStateMachine; private readonly PlayerTransitionsFactory _playerTransitionsFactory; private readonly MovementType _movementType; protected override HashSet<(State, Func<bool>)> StateTransitions { get; set; }
{ "domain": "codereview.stackexchange", "id": 44646, "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#, game, design-patterns, unity3d, strategy-pattern", "url": null }
c#, game, design-patterns, unity3d, strategy-pattern protected override HashSet<(State, Func<bool>)> StateTransitions { get; set; } public PlayerStandingMovingState(PlayerStandingRootState playerStateMachine, PlayerCharacterController playerCharacterController, PlayerInputsManager playerInputsManager, PlayerStateMachine.PlayerStateParameters playerStateParameters, PlayerTransitionsFactory playerTransitionsFactory, Transform playerCameraTransform) { _playerStateMachine = playerStateMachine; _playerTransitionsFactory = playerTransitionsFactory; _movementType = new StandingMovement(playerCharacterController, playerInputsManager, playerStateParameters, playerCameraTransform); } public override void InitializeState() { base.InitializeState(); AddTransition(_playerStateMachine.PlayerIdleState, _playerTransitionsFactory.PlayerIsNotMoving); } public override void Tick() { _movementType.Move(); } } (Crouched Movement State on The Crouched Root State) using System; using System.Collections.Generic; using UnityEngine; public class PlayerCrouchedMovingState : State { private readonly PlayerCrouchedRootState _playerStateMachine; private readonly PlayerTransitionsFactory _playerTransitionsFactory; private readonly MovementType _movementType; protected override HashSet<(State, Func<bool>)> StateTransitions { get; set; } public PlayerCrouchedMovingState(PlayerCrouchedRootState playerCrouchedRootState, PlayerCharacterController playerCharacterController, PlayerInputsManager playerInputsManager, PlayerStateMachine.PlayerStateParameters playerStateParameters, PlayerTransitionsFactory playerTransitionsFactory, Transform playerCameraTransform) { _playerStateMachine = playerCrouchedRootState; _playerTransitionsFactory = playerTransitionsFactory; _movementType = new CrouchedMovement(playerCharacterController, playerInputsManager, playerStateParameters, playerCameraTransform); }
{ "domain": "codereview.stackexchange", "id": 44646, "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#, game, design-patterns, unity3d, strategy-pattern", "url": null }
c#, game, design-patterns, unity3d, strategy-pattern public override void InitializeState() { base.InitializeState(); AddTransition(_playerStateMachine.PlayerCrouchedIdleState, _playerTransitionsFactory.PlayerIsNotMoving); } public override void Tick() { _movementType.Move(); } } I would like to know if I`m correctly implementing the strategy pattern using the state pattern, as well as if you guys have any tips to improve the code architecture. If you guys want to see the full project and the full state machine code I'll leave the link to my project, it's public repository: https://github.com/ThomasAllenSilva/Asylum-Horror Thanks Answer: Ideally you would create an intermediate abstract class PlayerMovingState between State and the different other player moving states, so that you could pull up all the common members up to it. The private members would have to be protected instead. public abstract class PlayerMovingState : State { protected readonly PlayerMovingState _playerStateMachine; protected readonly PlayerTransitionsFactory _playerTransitionsFactory; protected readonly MovementType _movementType; public PlayerMovingState(PlayerMovingState playerStateMachine, PlayerTransitionsFactory playerTransitionsFactory, MovementType movementType) { _playerStateMachine = playerStateMachine; _playerTransitionsFactory = playerTransitionsFactory; _movementType = movementType; } public override void Tick() { _movementType?.Move(); } } Also, it is not clear to me why you override the StateTransitions HashSet. It could be implemented in State right away (even if State is abstract): // In class State public HashSet<(State, Func<bool>)> StateTransitions { get; } = new HashSet<(State, Func<bool>)>();
{ "domain": "codereview.stackexchange", "id": 44646, "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#, game, design-patterns, unity3d, strategy-pattern", "url": null }
c#, game, design-patterns, unity3d, strategy-pattern Then e.g. PlayerCrouchedMovingState becomes public class PlayerCrouchedMovingState : PlayerMovingState { public PlayerCrouchedMovingState( PlayerCrouchedRootState playerCrouchedRootState, PlayerCharacterController playerCharacterController, PlayerInputsManager playerInputsManager, PlayerStateParameters playerStateParameters, PlayerTransitionsFactory playerTransitionsFactory, Transform playerCameraTransform ) : base( playerCrouchedRootState, playerTransitionsFactory, new CrouchedMovement(playerCharacterController, playerInputsManager, playerStateParameters, playerCameraTransform) ) { } public override void InitializeState() { base.InitializeState(); AddTransition(_playerStateMachine.PlayerCrouchedIdleState, _playerTransitionsFactory.PlayerIsNotMoving); } }
{ "domain": "codereview.stackexchange", "id": 44646, "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#, game, design-patterns, unity3d, strategy-pattern", "url": null }
javascript, hash-map, cryptography Title: SHA-256 Hash with a short string length in javascript Question: I think I've found a way to somewhat "compress" the length of a SHA-256 hash. I am doing some addition, so I wanted to know whether an approach like this is secure or not. const digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; function stringToInt(string) { const base = digits.length; let result = 0; for (let i = 0; i < string.length; i++) { result = result * base + digits.indexOf(string.charAt(i)); } return result } function intToString(int) { const base = digits.length; let result = ''; while (0 < int) { result = digits.charAt(int % base) + result; int = Math.floor(int / base); } return result || '0' } function sha_256(value) { function hexToBytes(hex) { let bytes = []; for (let c = 0; c < hex.length; c += 2) bytes.push(parseInt(hex.substr(c, 2), 16)); return bytes; } let str = ""; let bits = hexToBytes(sha256(value) /* returns a hex string */ ) for (let i = 0; i < bits.length; i += 8) { const a = bits[i]; const b = bits[i + 1]; const c = bits[i + 2]; const d = bits[i + 3]; const e = bits[i + 4]; const f = bits[i + 5]; const g = bits[i + 6]; const h = bits[i + 7]; console.log(a, b, c, d, e, f, g, h) } return str } ``` Answer: Using 62 characters seems an odd choice: const digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; Prefer base64url. For one thing, the various divide and modulo base operations become simple bit shifts when length of digits is 2^6. For another, it becomes easier to predict how encoded message length relates to original length. result = result * base + digits.indexOf(string.charAt(i)); The repeated indexOf O(N) linear scan seems tedious. Prefer to use a hash map which gives the answer in O(1) constant time.
{ "domain": "codereview.stackexchange", "id": 44647, "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, hash-map, cryptography", "url": null }
javascript, hash-map, cryptography while (0 < int) { Clearly this is identical to an int > 0 expression. Except that the Gentle Reader can pronounce the latter as "while int positive". As written it seems a little contorted to make sense of it. const a = ... const h = bits[i + 7]; I don't get it. Why introduce a bunch of temp vars? Just console.log eight expressions and be done with it. Or iterate through a loop eight times. This sha_256 function seems to be doing at least two things, computing a hash and sending it to the console. The single responsibility principle suggests breaking this out into two functions. This submission is crying out for a couple of simple unit tests. It's sooo easy. Just add one or two, so we can see what an encode / decode roundtrip looks like. wanted to know whether an approach like this is secure
{ "domain": "codereview.stackexchange", "id": 44647, "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, hash-map, cryptography", "url": null }
javascript, hash-map, cryptography wanted to know whether an approach like this is secure That depends on your use case, which you did not describe. The good news is you're starting with a cryptographic hash function so an attacker cannot induce collisions as easily as he might with a simple checksum. Let's assume the input value is somewhat long and has > 256 bits of entropy. Then any approach like the current one, which truncates the sha256 result, will be less secure against collisions compared with with an approach that preserves all 256 bits. Many practical use cases would require fewer than 256 bits of entropy. Suppose our analysis of traffic volume suggests the risk of collision would be acceptable when using just 128 bits. Is using the first half of the sha256 hash a secure approach? Yes, it is. As is the use of any similar subset, such as the last half. This is all subject to the obvious caveat that we chose to reduce the security parameter. In general, if you want N < 256 bits of entropy, reporting the N-bit prefix of a sha256() result is secure. The most efficient way to send the bits is as raw binary via an 8-bit clean channel. If that's not available, for example because we need to put them in an URL, then we must do some sort of channel encoding as seen in the present source code. Notice that this will necessarily expand the message, which is the opposite of "compression" that you mentioned. To send a 24-bit message as hex we could send six ASCII characters, or as Base64 we could send four characters. If the message is initial prefix of sha256() output, then we have "truncated" the hash, trading bandwidth for security. This code achieves its design goals. We might wish to slightly adjust the design. A small amount of refactoring is indicated. I would be happy to delegate or accept maintenance tasks on this codebase.
{ "domain": "codereview.stackexchange", "id": 44647, "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, hash-map, cryptography", "url": null }
c++, object-oriented, socket, wrapper Title: OO simple network time server with changes from a previous code inspection and added Windows support Question: I put up my SNTP Server code for review here: SNTPv4 server based on rfc 4330 in C++ a fortnight ago and since then I have made changes as per code review comments and also added support for Windows, mostly just by adding the winsock startup and shutdown functions and I also made the Makefile work for Windows in addition to Linux. For the Makefile to work on Windows you need to install GNU make for Windows and assuming you already have Visual Studio installed, run the Native Tools Command Prompt for Visual Studio to setup the required env variables. I only tested with 64 bit building on Windows. Is creating a Makefile to work under Windows a fools errand? Is the code clear? How could it be improved? Very interested to hear any feedback on the code. Address.hpp: /* C++ wrapper for C socket API sockaddr_in */ #ifndef ADDRESS_HPP_ #define ADDRESS_HPP_ #include <string> #include <cstdint> #include <iosfwd> #ifdef _WIN32 #include <winsock2.h> // Windows sockets v2 #include <ws2tcpip.h> // WinSock2 Extension, eg inet_pton, inet_ntop, sockaddr_in6 #elif __linux__ || __unix__ #include <arpa/inet.h> #else #error Unsupported platform #endif class Address { public: //! construct from sockaddr_in explicit Address(const sockaddr_in& sock_address); //! construct from 32 bit unsigned integer and a port Address(const std::uint32_t ipv4_address, const unsigned short port); //! construct from IP address string and port, use * for INADDR_ANY Address(const char* dotted_decimal, const unsigned short port); //! retrieve socket API sockaddr_in const sockaddr_in* get() const; //! get size of sockaddr_in std::size_t size() const; //! get IP address as string std::string get_ip() const; friend std::ostream& operator<<(std::ostream& os, const Address& address); private: sockaddr_in sock_addr_; };
{ "domain": "codereview.stackexchange", "id": 44648, "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++, object-oriented, socket, wrapper", "url": null }
c++, object-oriented, socket, wrapper private: sockaddr_in sock_addr_; }; //! debug print address std::ostream& operator<<(std::ostream& os, const Address& address); #endif // ADDRESS_HPP_ Address.cpp: #include "address.hpp" #include <iostream> #include <iomanip> #include <cstring> #include <stdexcept> std::ostream& operator<<(std::ostream& os, const Address& address) { os << "Address family : AF_INET (Internetwork IPv4)\n"; os << "Port : " << ntohs(address.sock_addr_.sin_port) << '\n'; os << "IP address : " << address.get_ip() << '\n'; return os; } Address::Address(const sockaddr_in& sock_address) : sock_addr_{ sock_address } {} // use * for INADDR_ANY Address::Address(const char* dotted_decimal, const unsigned short port) : sock_addr_({}) { if (!dotted_decimal || std::strlen(dotted_decimal) == 0 || std::strcmp(dotted_decimal, "*") == 0) { sock_addr_.sin_addr.s_addr = INADDR_ANY; // bind to all interfaces } else { if (inet_pton(AF_INET, dotted_decimal, &sock_addr_.sin_addr) != 1) { throw std::invalid_argument("invalid IPv4 address"); } } sock_addr_.sin_family = PF_INET; sock_addr_.sin_port = htons(port); } Address::Address(const uint32_t ipv4_address, const unsigned short port) : sock_addr_{} { sock_addr_.sin_family = PF_INET; sock_addr_.sin_addr.s_addr = ipv4_address; sock_addr_.sin_port = htons(port); } const sockaddr_in* Address::get() const { return &sock_addr_; } size_t Address::size() const { return sizeof sock_addr_; } std::string Address::get_ip() const { char buffer[64]; const char* ipv4 = inet_ntop(PF_INET, &sock_addr_.sin_addr, buffer, 64); return ipv4 ? ipv4 : ""; } udp_server.hpp: /* Basic implementation of UDP socket server using select User provides callback function to handle client requests */ #ifndef UDP_SERVER__ #define UDP_SERVER__ #ifdef _WIN32 #ifdef _WIN64 typedef __int64 ssize_t; #else typedef int ssize_t; #endif #endif #include <functional> #include <vector> #include <cstdint>
{ "domain": "codereview.stackexchange", "id": 44648, "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++, object-oriented, socket, wrapper", "url": null }
c++, object-oriented, socket, wrapper #include <functional> #include <vector> #include <cstdint> #include "address.hpp" //! callback signature for user provided function for handling request data from clients using client_request_callback = std::function<void(const char*, const size_t, const Address&)>; class udp_server { public: //! construct with port, callback for custom data handler and receive buffer size udp_server(uint16_t port, client_request_callback request_callback, size_t buffer_size = 4096); //! destructor virtual ~udp_server(); //! call run to start server void run(); //! send returns number of bytes successfully sent ssize_t send(const char* data, const size_t length, const Address& address); private: uint16_t port_; client_request_callback rq_callback_; //const size_t buffer_size_; std::vector<char> buffer_; int s_; }; #endif // UDP_SERVER__ udp_server.cpp: #ifdef _WIN32 #include <winsock2.h> // Windows sockets v2 #include <ws2tcpip.h> // WinSock2 Extension, eg inet_pton, inet_ntop, sockaddr_in6 namespace { int close(int fd) { return closesocket(fd); } } #ifdef _WIN64 typedef __int64 ssize_t; #else typedef int ssize_t; #endif #elif __linux__ || __unix__ #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #include <arpa/inet.h> #else #error Unsupported platform #endif #include <iostream> #include <cerrno> #include <cstring> #include <cstdint> #include <cstdlib> // std::exit() #include "udp-server.hpp" namespace { void bailout(const char* msg) { std::perror(msg); std::exit(1); } } udp_server::udp_server(uint16_t port, client_request_callback request_callback, size_t buffer_size) : port_(port), rq_callback_(request_callback ), buffer_(buffer_size), s_(-1) { std::clog << "udp_server will bind to port: " << port_ << std::endl; } udp_server::~udp_server() { if (s_ != -1) { close(s_); } #ifdef _WIN32 WSACleanup(); #endif } //! start server void udp_server::run() {
{ "domain": "codereview.stackexchange", "id": 44648, "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++, object-oriented, socket, wrapper", "url": null }
c++, object-oriented, socket, wrapper //! start server void udp_server::run() { #ifdef _WIN32 WSADATA w = { 0 }; int error = WSAStartup(0x0202, &w); if (error || w.wVersion != 0x0202) { // there was an error throw "Could not initialise Winsock2\n"; } #endif // create server socket s_ = socket(PF_INET, SOCK_DGRAM, 0); if (s_ == -1) { bailout("socket error"); } // bind the server address to the socket sockaddr_in server_addr = {}; // AF_INET server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port_); server_addr.sin_addr.s_addr = INADDR_ANY; socklen_t len_inet = sizeof server_addr; int r = bind(s_, reinterpret_cast<sockaddr*>(&server_addr), len_inet); if ( r == -1) { bailout("bind error"); } // express interest in socket s for read events fd_set rx_set; // read set FD_ZERO(&rx_set); // init int maxfds = s_ + 1; // start the server loop for (;;) { FD_SET(s_, &rx_set); // block until socket activity int n = select(maxfds, &rx_set, NULL, NULL, NULL); if (n == -1) { bailout("select error"); } else if ( !n ) { // select timeout continue; } // if udp socket is readable receive the message. if (FD_ISSET(s_, &rx_set)) { sockaddr_in sock_address {}; socklen_t len_client = sizeof sock_address; // retrieve data received ssize_t recbytes = recvfrom(s_, buffer_.data(), buffer_.size(), 0, reinterpret_cast<sockaddr*>(&sock_address), &len_client); if (recbytes <= 0) { std::cerr << "recvfrom returned: " << recbytes << std::endl; continue; } // Create an address from client_address and pass to callback function with data Address client_address(sock_address); rq_callback_(buffer_.data(), recbytes, client_address); FD_CLR(s_, &rx_set); } } // for loop }
{ "domain": "codereview.stackexchange", "id": 44648, "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++, object-oriented, socket, wrapper", "url": null }
c++, object-oriented, socket, wrapper FD_CLR(s_, &rx_set); } } // for loop } //! returns number of bytes successfully sent ssize_t udp_server::send(const char* data, const size_t length, const Address& address) { return sendto(s_, data, length, 0, (const sockaddr*)address.get(), static_cast<int>(address.size())); } ntp-server.hpp: /* Basic implementation of v4 SNTP server as per: https://www.rfc-editor.org/rfc/rfc4330 Uses udp_server for low level UDP socket communication Separation of socket and ntp handling via passing a callback function to udp server */ #ifndef NTP_SERVER_HPP_ #define NTP_SERVER_HPP_ #include "udp-server.hpp" #include <cstdint> class ntp_server { public: //! initialise ntp_server with server port, defaults to well known NTP port 123 explicit ntp_server(std::uint16_t port = 123); //! start NTP server void run(); //! callback to handle data received from NTP client void read_callback(const char* data, const std::size_t length, const Address& address); private: udp_server udp_server_; }; #endif // NTP_SERVER_HPP_ ntp-server.cpp: #include "ntp-server.hpp" #include <cstdio> #include <cstring> // memcpy #include <iostream> #include <iomanip> #ifdef _WIN32 int gettimeofday(struct timeval* tp, struct timezone* tzp) { // Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's // This magic number is the number of 100 nanosecond intervals since January 1, 1601 (UTC) // until 00:00:00 January 1, 1970 static const std::uint64_t EPOCH = ((std::uint64_t)116444736000000000ULL); SYSTEMTIME system_time; FILETIME file_time; std::uint64_t time; GetSystemTime(&system_time); SystemTimeToFileTime(&system_time, &file_time); time = ((std::uint64_t)file_time.dwLowDateTime); time += ((std::uint64_t)file_time.dwHighDateTime) << 32;
{ "domain": "codereview.stackexchange", "id": 44648, "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++, object-oriented, socket, wrapper", "url": null }
c++, object-oriented, socket, wrapper tp->tv_sec = (long)((time - EPOCH) / 10000000L); tp->tv_usec = (long)(system_time.wMilliseconds * 1000); return 0; } #else #include <sys/time.h> // gettimeofday #endif namespace { /* unix epoch is 1970-01-01 00:00:00 +0000 (UTC) but start of ntp time is 1900-01-01 00:00:00 UTC, so adjust with difference */ const std::uint32_t NTP_UTIME_DIFF = 2208988800U; /* 1970 - 1900 */ const std::uint64_t NTP_SCALE_FRAC = 4294967296; const std::size_t ntp_msg_size{48}; // utility function to print an array in hex template<typename T> void printhex (T* buf, std::size_t len) { auto previous_flags = std::clog.flags(); for (std::size_t i = 0; i < len; i++) { std::clog << std::hex << std::setfill('0') << std::setw(2) << (buf[i] & 0xFF) << ' '; } std::clog.setf(previous_flags); } /* get timestamp for NTP in LOCAL ENDIAN, in/out arg is a uint32_t[2] array with most significant 32 bit part no. seconds since 1900-01-01 00:00:00 and least significant 32 bit part fractional seconds */ void gettime64(std::uint32_t ts[]) { struct timeval tv; gettimeofday(&tv, NULL); if (tv.tv_sec > 0xFFFFFFFF) { std::clog << "timeval time_t seconds value > 0xFFFFFFFF, (" << tv.tv_sec << ") and will overflow\n"; } ts[0] = static_cast<uint32_t>(tv.tv_sec) + NTP_UTIME_DIFF; // ntp seconds if ((NTP_SCALE_FRAC * tv.tv_usec) / 1000000UL > 0xFFFFFFFF) { std::clog << "timeval fractional seconds value > 0xFFFFFFFF, (" << tv.tv_sec << ") and will overflow\n"; } ts[1] = static_cast<uint32_t>((NTP_SCALE_FRAC * tv.tv_usec) / 1000000UL); //ntp usecs } /* get timestamp for NTP in LOCAL ENDIAN, returns uint64_t with most significant 32 bit part no. seconds since 1900-01-01 00:00:00 and least significant 32 bit part fractional seconds */ uint64_t gettime64() { uint32_t ts[2]; gettime64(ts); uint64_t tmp = ts[0]; return (tmp << 32) + ts[1]; }
{ "domain": "codereview.stackexchange", "id": 44648, "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++, object-oriented, socket, wrapper", "url": null }
c++, object-oriented, socket, wrapper // helper to populate an array at start_index with uint32_t void populate_32bit_value(unsigned char* buffer, int start_index, std::uint32_t value) { std::uint32_t* p32 = reinterpret_cast<std::uint32_t*>(&buffer[start_index]); *p32 = value; } /* create the NTP response message to be sent to client Args: recv_buf - array received from NTP client (should be 48 bytes in length) recv_time - array containing time NTP request received send_buf - byte array to be sent to client */ void make_reply(const unsigned char recv_buf[], std::uint32_t recv_time[], unsigned char* send_buf) { /* LI VN Mode Leap Indicator = 0 Version Number = 4 (SNTPv4) Mode = 4 = server 0x24 == LI=0, version=4 (SNTPv4), mode=4 (server) 00 100 100 */ send_buf[0] = 0x24; /* Stratum = 1 (primary reference). A stratum 1 level NTP server is synchronised by a reference clock, eg in UK the Anthorn Radio Station in Cumbria. (Not true - next project work out how to sync up with radio signal. Typically in a real world scenario, subsidiary ntp servers at lower levels of stratum would sync with a stratum ntp server. */ send_buf[1] = 0x1; // Poll Interval - - we set to max allowable poll interval send_buf[2] = 0x11; // 17 == 2^17 (exponent) // Precision send_buf[3] = 0xFA; // 0xFA == -6 - 2^(-6) == mains clock frequency // *** below are 32 bit values /* Root Delay - total roundtrip delay to primary ref source in seconds set to zero - simplification */ populate_32bit_value(send_buf, 4, htonl(0));
{ "domain": "codereview.stackexchange", "id": 44648, "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++, object-oriented, socket, wrapper", "url": null }
c++, object-oriented, socket, wrapper /* Root Dispersion - max error due to clock freq tolerance in secs, svr sets set to zero (simplification) */ populate_32bit_value(send_buf, 8, htonl(0)); /* Reference Identifier - reference source, LOCL means uncalibrated local clock We must send in network byte order (we assume we built svr little endian) */ std::uint32_t refid ( 0x4c4f434c ); // LOCL in ASCII populate_32bit_value(send_buf, 12, htonl(refid)); // *** below are 64 bit values /* Reference Timestamp - time system clock was last set or corrected investigate - if we assume client is requesting every poll interval 2^17 - just simulate what time was back then 2^17 = 131072 */ std::uint64_t ntp_now = gettime64(); std::uint32_t p32_seconds_before = htonl(static_cast<uint32_t>(ntp_now >> 32) - 131072); std::uint32_t p32_frac_seconds_before = htonl(ntp_now & 0xFFFFFFFF); populate_32bit_value(send_buf, 16, p32_seconds_before); populate_32bit_value(send_buf, 20, p32_frac_seconds_before); /* Originate Timestamp: This is the time at which the request departed the client for the server, in 64-bit timestamp format. We can copy value from client request */ std::memcpy(&send_buf[24], &recv_buf[40], 8); // Receive Timestamp - get from time rq received by server std::uint32_t* p32 = reinterpret_cast<uint32_t*>(&send_buf[32]); *p32++ = htonl(recv_time[0]); // seconds part *p32++ = htonl(recv_time[1]); // fraction of seconds part // Transmit Timestamp - re-use ntp_now time obtained above populate_32bit_value(send_buf, 40, htonl(static_cast<uint32_t>(ntp_now >> 32))); populate_32bit_value(send_buf, 44, htonl(ntp_now & 0xFFFFFFFF)); } } // unnamed namespace
{ "domain": "codereview.stackexchange", "id": 44648, "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++, object-oriented, socket, wrapper", "url": null }
c++, object-oriented, socket, wrapper } // unnamed namespace // is there any way to do this and not have to use bind. It is a little ugly ntp_server::ntp_server(std::uint16_t port) : udp_server_(port, std::bind(&ntp_server::read_callback, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), ntp_msg_size) { } void ntp_server::run() { udp_server_.run(); } void ntp_server::read_callback(const char* data, const std::size_t length, const Address& address) { std::uint32_t recv_time[2]; gettime64(recv_time); std::clog << "new data in\n"; printhex(data, length); std::clog << '\n'; std::clog << "Client address:\n" << address << std::endl; unsigned char send_buf[ntp_msg_size] {}; make_reply(reinterpret_cast<const unsigned char*>(data), recv_time, send_buf); ssize_t ret; if ( (ret = udp_server_.send(reinterpret_cast<const char*>(send_buf), ntp_msg_size, address)) != ntp_msg_size) { std::cerr << "Error sending response to client: " << ret; perror("sendto"); } std::clog << "data sent:\n"; printhex(send_buf, ntp_msg_size); std::clog << std::endl; } main.cpp: #include <iostream> #include "ntp-server.hpp" int main() { std::clog << "Starting SNTPv4 Server\n"; ntp_server server(123); server.run(); } Makefile: ifeq ($(OS),Windows_NT) UNAME := Windows CXX=cl.exe CXXFLAGS=-EHs -nologo -std:c++17 RM=rd /s /q MKDIR_P=mkdir LINKER=link.exe LIBS=ws2_32.lib LFLAGS=-MACHINE:X64 -nologo -SUBSYSTEM:CONSOLE OBJSFX=.obj OUTCC=-Fo$@ OUTLINK=-out:$@ DBGCFLAGS = -DDEBUG -W4 -MTd -TP -Od RELCFLAGS = -DNDEBUG -W4 -MT -TP -O2 EXE = ntpserver.exe else UNAME := $(shell uname -s) CXX=g++ CXXFLAGS=-Wall -std=c++17 -Wextra -Wconversion MKDIR_P=mkdir -p LINKER=g++ RM=rm -rf OBJSFX=.o OUTCC=-o $@ OUTLINK=-o $@ DBGCFLAGS = -DDEBUG -g RELCFLAGS = -DNDEBUG EXE = ntpserver endif
{ "domain": "codereview.stackexchange", "id": 44648, "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++, object-oriented, socket, wrapper", "url": null }
c++, object-oriented, socket, wrapper SOURCES = main.cpp udp-server.cpp ntp-server.cpp address.cpp OBJS = $(SOURCES:.cpp=$(OBJSFX)) # Debug build settings DBGDIR = debug DBGEXE = $(DBGDIR)/$(EXE) DBGOBJS = $(addprefix $(DBGDIR)/, $(OBJS)) # Release build settings RELDIR = release RELEXE = $(RELDIR)/$(EXE) RELOBJS = $(addprefix $(RELDIR)/, $(OBJS)) .PHONY: all clean debug prep release remake # Default build all: prep release # Debug rules debug: $(DBGEXE) $(DBGEXE): $(DBGOBJS) $(LINKER) $(LFLAGS) $^ $(LIBS) $(OUTLINK) $(DBGDIR)/%$(OBJSFX): %.cpp $(CXX) -c $(CXXFLAGS) $(DBGCFLAGS) $< $(OUTCC) # Release rules release: $(RELEXE) $(RELEXE): $(RELOBJS) $(LINKER) $(LFLAGS) $^ $(LIBS) $(OUTLINK) $(RELDIR)/%$(OBJSFX): %.cpp $(CXX) -c $(CXXFLAGS) $(RELCFLAGS) $< $(OUTCC) # Other rules prep: @$(MKDIR_P) $(DBGDIR) $(RELDIR) remake: clean all clean: $(RM) debug release Answer: Answers to your questions Is creating a Makefile to work under Windows a fools errand? No, it can work fine under Windows. However, installing GNU make on Windows might be an annoying step for some. Also, your Makefile still makes assumptions about what compilers are available on what platforms. What if you want to use Clang on Linux, or GCC on Windows? What if you want to cross-compile a Windows binary on Linux? Consider using a modern build system like Meson or CMake. These abstract away the low-level platform details. They are also a bit easier to install for Windows users. Is the code clear?
{ "domain": "codereview.stackexchange", "id": 44648, "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++, object-oriented, socket, wrapper", "url": null }
c++, object-oriented, socket, wrapper Is the code clear? It doesn't look very nice. Maybe that is a consequence of it being networking code and dealing with low-level protocol bits. See below for ways to improve things. Documentation I see you are writing Doyxgen-like comments in the header files. However, they are quite terse and are missing a lot of detail. Make sure you document every class member, the class itself, and for functions you should document all the parameters and the return value as well. Consider running Doxygen on your code, and enabling warnings and errors, and fixing the ones it reports. Don't declare friends twice I see that you declared operator<<() for Address twice, once as a friend inside class Address, once outside. You should only need the friend declaration. Naming things Make sure names of classes, functions and variables are precise; they should convey what they represent accurately. Ideally, we shouldn't need to read the documentation to know what they are doing. For example, in Address there is get() and get_ip(). Both actually return an IP address. From the name however it is completely unclear that get_ip() returns a human-readable string. In udp_server, there is a member variable s_. What does this do? It's not even documented so I have to find where it is used and read the code to determine what it is. There is also the issue of consistency: why is Address spelled with a capital, but udp_server and ntp_server are in lower case? Why is there sock_address but sock_addr_? Avoid unnecessary abbreviations, but if you do abbreviate, always do it in the same way. Here is a list of recommended name change: get() -> sockaddr() (also see below) size() -> socklen() get_ip() -> to_string() sock_addr_ -> socket_address_ rq_callback_ -> request_callback_ s_ -> socket_fd_ r -> result n -> number_fds_set, n_fds_set, or just reuse result. recvbytes -> received_bytes or n_received
{ "domain": "codereview.stackexchange", "id": 44648, "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++, object-oriented, socket, wrapper", "url": null }
c++, object-oriented, socket, wrapper Return appropriate types You have get() and size() member functions for Address, but the main use is in passing the result to socket functions that expect a struct sockaddr* and socklen_t. So it might be better to return the latter types instead. The names of those functions could be changed to reflect that. Then the code using it becomes much cleaner: ssize_t udp_server::send(const char* data, const size_t length, const Address& address) { return sendto(socket_fd_, data, length, 0, address.sockaddr(), address.socklen()); }
{ "domain": "codereview.stackexchange", "id": 44648, "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++, object-oriented, socket, wrapper", "url": null }
c++, object-oriented, socket, wrapper Don't make the destructor of udp_server virtual Since nothing is inheriting from udp_server, there is no need to make its destructor virtual. Consider using getaddrinfo() and getnameinfo() The more modern way of converting address to text and back is to use getaddrinfo() and getnameinfo(). These functions are much more capable than inet_pton() and inet_ntop(), and as an added benefit they support IPv6 as well. I strongly recommend you move over to them. Use C++'s time functions Since you are already using POSIX and BSD network functions it is easy to start using other C functions as well. However, prefer using standard C++ functions where possible. For time, there is std::chrono. The equivalent of gettimeofday() is std::chrono::system_clock::now(). (C++20 introduced more clocks, maybe one of them is even better suited for NTP.) As a benefit, the C++ functions are cross-platform, so there is no need to reimplement gettimeofday() on Windows. Building a message make_reply() doesn't look nice at all. There are direct array accesses, calls to populate_32bit_value() and std::memcpy(), and writes via pointers. You have hardcoded offsets in several places. There is also the issue of byte swapping 64-bit values that doesn't have a nice function. Basically, this is a mess! There are two alternatives I would recommend: Use a struct An NTP replay has a well-defined format. Create a struct that represents this format. For example: struct ntp_reply { std::uint8_t li_vn_mode; std::uint8_t stratum; std::uint8_t poll_interval; std::uint8_t precision; uint32_t root_delay; … uint64_t transmit_timestamp; }; That way you can fill in the struct in a very clean way: ntp_reply make_reply(…) { ntp_reply reply; reply.li_vn_mode = 0x24; reply.stratum = 1; … reply.transmit_timestamp = hton64(ntp_now); return reply; }
{ "domain": "codereview.stackexchange", "id": 44648, "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++, object-oriented, socket, wrapper", "url": null }
c++, object-oriented, socket, wrapper return reply; } Build a buffer in a consistent way The other option is to build a buffer in a consistent way. For example, you could use a std::vector<std::uint8_t> to be the buffer, and have a function with overloads for the various types to append to this buffer: template<typename T> append(std::vector<sdt::uint8_t>& buffer, T value) { auto offset = buffer.size(); buffer.resize(offset + sizeof value); std::memcpy(&buffer[offset], &value, sizeof value); } std::vector<std::uint8_t> make_reply(…) { std::vector<std::uint8_t> reply; append(reply, std::uint8_t(0x24)); append(reply, std::uint8_t(1)); … append(reply, hton64(ntp_now)); return reply; } Create a function to byteswap 64-bit values Create your own hton64() to change the endianness of 64-bit values. This cleans up to code that needs to call it significantly, and avoids potential mistakes. Use std::uint64_t for 64-bit values Instead of storing 64-bit values in an array of 32-bit integers, just use std::uint64_t. Avoiding std::bind() // is there any way to do this and not have to use bind. It is a little ugly You could consider using a lambda expressions instead: ntp_server::ntp_server(std::uint16_t port) : udp_server_(port, [this](auto&&... args){ read_callback(std::forward<decltype(args)>(args)...); }, ntp_msg_size) { } Slighly more compact, but using std::forward and decltype to make sure the arguments are passed correctly is a little ugly as well. Note that you can make the std::bind() call shorter by writing: using std::placeholders; ntp_server::ntp_server(std::uint16_t port) : udp_server_(port, std::bind(&ntp_server::read_callback, this, _1, _2, _3), ntp_msg_size) { }
{ "domain": "codereview.stackexchange", "id": 44648, "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++, object-oriented, socket, wrapper", "url": null }
c#, .net, assertions Title: My own ThrowHelper extension methods Question: I really like ArgumentNullException.ThrowIf(...) and ArgumentException.ThrowIfNullOrEmpty(...) and there are upcoming ones in .NET 8, so until then I created a ThrowHelper on my own. Could you please review it and tell me your opinion? Can something be improved? public static class Assertions { public static void ThrowIfNull<T>([NotNull] T? value, string? paramName = null, string message = "Parameter cannot be null.") where T : class { if (value == null) { ThrowArgumentNullException(paramName, message); } } public static void ThrowIfNullOrEmpty(string value, string? paramName = null, string message = "String cannot be empty.") { if (string.IsNullOrEmpty(value)) { ThrowArgumentException(paramName, message); } } public static void ThrowIfNullOrEmpty<T>([NotNull] ICollection<T>? collection, string? paramName = null, string message = "Collection must have elements.") { if (collection == null || !collection.Any()) { ThrowArgumentException(paramName, message); } } public static void ThrowIfNullOrEmpty<T>([NotNull] T[]? array, string? paramName = null, string message = "Array must have elements.") { if (array == null || array.Length == 0) { ThrowArgumentException(paramName, message); } } public static void ThrowIfNullOrWhiteSpace(string value, string? paramName = null, string message = "String cannot be empty or whitespace.") { if (string.IsNullOrWhiteSpace(value)) { ThrowArgumentException(paramName, message); } }
{ "domain": "codereview.stackexchange", "id": 44649, "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#, .net, assertions", "url": null }
c#, .net, assertions public static void ThrowIfOutOfRange<T>(T value, T minValue, T maxValue, string? paramName = null, string message = "Value must be within the specified range.") where T : IComparable<T> { if (value.CompareTo(minValue) < 0 || value.CompareTo(maxValue) > 0) { ThrowArgumentOutOfRangeException(paramName, message); } } public static void ThrowIfLessThan<T>(T value, T threshold, string? paramName = null, string message = "Value must be greater than or equal to the threshold.") where T : IComparable<T> { if (value.CompareTo(threshold) < 0) { ThrowArgumentOutOfRangeException(paramName, message); } } public static void ThrowIfLessThanOrEqualTo<T>(T value, T threshold, string? paramName = null, string message = "Value must be greater than the threshold.") where T : IComparable<T> { if (value.CompareTo(threshold) <= 0) { ThrowArgumentOutOfRangeException(paramName, message); } } public static void ThrowIfGreaterThan<T>(T value, T threshold, string? paramName = null, string message = "Value must be less than the threshold.") where T : IComparable<T> { if (value.CompareTo(threshold) > 0) { ThrowArgumentOutOfRangeException(paramName, message); } } public static void ThrowIfGreaterThanOrEqualTo<T>(T value, T threshold, string? paramName = null, string message = "Value must be less than or equal to the threshold.") where T : IComparable<T> { if (value.CompareTo(threshold) >= 0) { ThrowArgumentOutOfRangeException(paramName, message); } } public static void ThrowIfEqual<T>(T value, T target, string? paramName = null, string message = "Parameter cannot be equal to its default value.") { if (EqualityComparer<T>.Default.Equals(value, target)) { ThrowArgumentException(paramName, message); } }
{ "domain": "codereview.stackexchange", "id": 44649, "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#, .net, assertions", "url": null }
c#, .net, assertions [DoesNotReturn] private static void ThrowArgumentException(string? paramName, string message) => throw new ArgumentException(message, paramName); [DoesNotReturn] private static void ThrowArgumentOutOfRangeException(string? paramName, string message) => throw new ArgumentOutOfRangeException(paramName, message); [DoesNotReturn] private static void ThrowArgumentNullException(string? paramName, string message) => throw new ArgumentNullException(paramName, message); } Modifications based on slepic's comment using System.Diagnostics.CodeAnalysis; namespace GridBot.Api.Extensions; public static class Assertions { public static void ThrowIfNull<T>([NotNull] T? argument, string? paramName = null, string message = "Parameter cannot be null.") where T : class { if (argument == null) { ThrowArgumentNullException(paramName, message); } } public static void ThrowIfNullOrEmpty(string argument, string? paramName = null, string message = "String cannot be empty.") { if (string.IsNullOrEmpty(argument)) { ThrowNullOrEmptyException(argument, paramName, message); } } public static void ThrowIfNullOrEmpty<T>([NotNull] ICollection<T>? argument, string? paramName = null, string message = "Collection must have elements.") { if (argument == null || !argument.Any()) { ThrowArgumentException(paramName, message); } } public static void ThrowIfNullOrEmpty<T>([NotNull] T[]? argument, string? paramName = null, string message = "Array must have elements.") { if (argument == null || argument.Length == 0) { ThrowArgumentException(paramName, message); } }
{ "domain": "codereview.stackexchange", "id": 44649, "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#, .net, assertions", "url": null }
c#, .net, assertions public static void ThrowIfNullOrWhiteSpace(string argument, string? paramName = null, string message = "String cannot be empty or whitespace.") { if (string.IsNullOrWhiteSpace(argument)) { ThrowArgumentException(paramName, message); } } public static void ThrowIfOutOfRange<T>(T argument, T minValue, T maxValue, string? paramName = null, string message = "Value must be within the specified range.") where T : IComparable<T> { if (argument.CompareTo(minValue) < 0 || argument.CompareTo(maxValue) > 0) { ThrowArgumentOutOfRangeException(paramName, message); } } public static void ThrowIfLessThan<T>(T argument, T threshold, string? paramName = null, string message = "Value must be greater than or equal to the threshold.") where T : IComparable<T> { if (argument.CompareTo(threshold) < 0) { ThrowArgumentOutOfRangeException(paramName, message); } } public static void ThrowIfLessThanOrEqualTo<T>(T argument, T threshold, string? paramName = null, string message = "Value must be greater than the threshold.") where T : IComparable<T> { if (argument.CompareTo(threshold) <= 0) { ThrowArgumentOutOfRangeException(paramName, message); } } public static void ThrowIfGreaterThan<T>(T argument, T threshold, string? paramName = null, string message = "Value must be less than the threshold.") where T : IComparable<T> { if (argument.CompareTo(threshold) > 0) { ThrowArgumentOutOfRangeException(paramName, message); } }
{ "domain": "codereview.stackexchange", "id": 44649, "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#, .net, assertions", "url": null }
c#, .net, assertions public static void ThrowIfGreaterThanOrEqualTo<T>(T argument, T threshold, string? paramName = null, string message = "Value must be less than or equal to the threshold.") where T : IComparable<T> { if (argument.CompareTo(threshold) >= 0) { ThrowArgumentOutOfRangeException(paramName, message); } } public static void ThrowIfEqual<T>(T argument, T target, string? paramName = null, string message = "Parameter cannot be equal to its default value.") { if (EqualityComparer<T>.Default.Equals(argument, target)) { ThrowArgumentException(paramName, message); } } [DoesNotReturn] private static void ThrowNullOrEmptyException([NotNull] string? argument, string? paramName, string message) { ThrowIfNull(argument, paramName, message); throw new ArgumentException(message, paramName); } [DoesNotReturn] private static void ThrowArgumentException(string? paramName, string message) => throw new ArgumentException(message, paramName); [DoesNotReturn] private static void ThrowArgumentOutOfRangeException(string? paramName, string message) => throw new ArgumentOutOfRangeException(paramName, message); [DoesNotReturn] private static void ThrowArgumentNullException(string? paramName, string message) => throw new ArgumentNullException(paramName, message); } Answer: Your code is like a good champagne, it is semi-DRY :) (Sorry for the bad joke) The exception creations and throw command are extracted into their own methods but the guard expression is still repeated. IMHO you should define a single extension method to the conditional throw and inline the exception creation. static class BoolExtension { public static void ThrowIf(this bool condition, Exception ex) { if (condition) throw ex; } }
{ "domain": "codereview.stackexchange", "id": 44649, "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#, .net, assertions", "url": null }
c#, .net, assertions Or call it IfTrueThenThrow, FailWith or whatever if it makes more sense :) public static class Assertions { public static void ThrowIfNull<T>([NotNull] T? argument, string? paramName = null, string message = "Parameter cannot be null.") where T : class => (argument == null).ThrowIf(new ArgumentNullException(paramName, message)); public static void ThrowIfNullOrEmpty(string argument, string? paramName = null, string message = "String cannot be empty.") { ThrowIfNull(argument, paramName, message); string.IsNullOrEmpty(argument).ThrowIf(new ArgumentException(message, paramName)); } public static void ThrowIfNullOrEmpty<T>([NotNull] ICollection<T>? argument, string? paramName = null, string message = "Collection must have elements.") => (argument == null || !argument.Any()).ThrowIf(new ArgumentException(message, paramName)); public static void ThrowIfNullOrEmpty<T>([NotNull] T[]? argument, string? paramName = null, string message = "Array must have elements.") => (argument == null || argument.Length == 0).ThrowIf(new ArgumentException(message, paramName)); public static void ThrowIfNullOrWhiteSpace(string argument, string? paramName = null, string message = "String cannot be empty or whitespace.") => string.IsNullOrWhiteSpace(argument).ThrowIf(new ArgumentException(message, paramName)); public static void ThrowIfOutOfRange<T>(T argument, T minValue, T maxValue, string? paramName = null, string message = "Value must be within the specified range.") where T : IComparable<T> => (argument.CompareTo(minValue) < 0 || argument.CompareTo(maxValue) > 0).ThrowIf(new ArgumentOutOfRangeException(paramName, message));
{ "domain": "codereview.stackexchange", "id": 44649, "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#, .net, assertions", "url": null }
c#, .net, assertions public static void ThrowIfLessThan<T>(T argument, T threshold, string? paramName = null, string message = "Value must be greater than or equal to the threshold.") where T : IComparable<T> => (argument.CompareTo(threshold) < 0).ThrowIf(new ArgumentOutOfRangeException(paramName, message)); public static void ThrowIfLessThanOrEqualTo<T>(T argument, T threshold, string? paramName = null, string message = "Value must be greater than the threshold.") where T : IComparable<T> => (argument.CompareTo(threshold) <= 0).ThrowIf(new ArgumentOutOfRangeException(paramName, message)); public static void ThrowIfGreaterThan<T>(T argument, T threshold, string? paramName = null, string message = "Value must be less than the threshold.") where T : IComparable<T> => (argument.CompareTo(threshold) > 0).ThrowIf(new ArgumentOutOfRangeException(paramName, message)); public static void ThrowIfGreaterThanOrEqualTo<T>(T argument, T threshold, string? paramName = null, string message = "Value must be less than or equal to the threshold.") where T : IComparable<T> => (argument.CompareTo(threshold) >= 0).ThrowIf(new ArgumentOutOfRangeException(paramName, message)); public static void ThrowIfEqual<T>(T argument, T target, string? paramName = null, string message = "Parameter cannot be equal to its default value.") => EqualityComparer<T>.Default.Equals(argument, target).ThrowIf(new ArgumentException(message, paramName)); } Also, I think these methods are good candidates to become extension methods. (Even though [NotNull] this T? argument feels weird)
{ "domain": "codereview.stackexchange", "id": 44649, "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#, .net, assertions", "url": null }
c++, integer Title: C++ Arbitrary Precision Whole Number Class Question: The class below implements an arbitrarily sized whole number C++ class. It is wrapped around a bitvector class, which does most the binary heavy lifting. The basic mathematical operators are implemented using whole word manipulation, inspired from Modern Computer Arithmetic - Paul Zimmermann. I was unable to understand the pseudo-code and math notation for division from that book. So, I came up with my own algorithm. Feedback on that is very welcomed. I would be surprised if it couldn’t be optimized in some way. A design change was made from the previous bitvector class, to remove the std::string and std::stringstream aliases as recommended here. After thinking about it if I make the changes now and cascade them up as I revise the rest of the library, it will be more manageable, than later going top to bottom. This class is designed to abstract the arithmetic for arbitrary precision integrals, which will using this class in their design. Hence the boolean error variable in one of the constructors. whole_number.h #include "../support_files/string_support.h" #include "../BitVector/bitvector.h" namespace Olly { namespace MPA { /********************************************************************************************/ // // 'whole_number' Class Declaration // /********************************************************************************************/ class whole_number { using Word = bitvector::word_t; using Double_Word = bitvector::double_word_t; public: whole_number(); whole_number(Word value); whole_number(const std::string& value, Word base = 10); whole_number(const std::string& value, Word base, bool& error); virtual ~whole_number();
{ "domain": "codereview.stackexchange", "id": 44650, "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++, integer", "url": null }
c++, integer whole_number(whole_number&& obj) = default; whole_number(const whole_number& obj) = default; whole_number& operator=(whole_number&& obj) = default; whole_number& operator=(const whole_number& obj) = default; friend void swap(whole_number& first, whole_number& second); operator bool() const; bool is() const; bool is_odd() const; bool is_even() const; bool operator==(const whole_number& b) const; bool operator!=(const whole_number& b) const; std::partial_ordering operator<=>(const whole_number& b) const; whole_number& operator&=(const whole_number& other); whole_number& operator|=(const whole_number& other); whole_number& operator^=(const whole_number& other); whole_number& operator<<=(std::size_t index); whole_number& operator>>=(std::size_t index); whole_number bin_comp() const; whole_number operator&(const whole_number& b) const; whole_number operator|(const whole_number& b) const; whole_number operator^(const whole_number& b) const; whole_number operator~() const; whole_number operator<<(std::size_t index) const; whole_number operator>>(std::size_t index) const; whole_number& operator+=(const whole_number& other); whole_number& operator-=(const whole_number& other); whole_number& operator*=(const whole_number& other); whole_number& operator/=(const whole_number& other); whole_number& operator%=(const whole_number& other);
{ "domain": "codereview.stackexchange", "id": 44650, "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++, integer", "url": null }
c++, integer whole_number operator+(const whole_number& b) const; whole_number operator-(const whole_number& b) const; whole_number operator*(const whole_number& b) const; whole_number operator/(const whole_number& b) const; whole_number operator%(const whole_number& b) const; friend whole_number operator&(whole_number&& a, const whole_number& b); friend whole_number operator|(whole_number&& a, const whole_number& b); friend whole_number operator^(whole_number&& a, const whole_number& b); friend whole_number operator<<(whole_number&& a, std::size_t index); friend whole_number operator>>(whole_number&& a, std::size_t index); friend whole_number operator+(whole_number&& a, const whole_number& b); friend whole_number operator-(whole_number&& a, const whole_number& b); friend whole_number operator*(whole_number&& a, const whole_number& b); friend whole_number operator/(whole_number&& a, const whole_number& b); friend whole_number operator%(whole_number&& a, const whole_number& b); whole_number& operator++(); whole_number operator++(int); whole_number& operator--(); whole_number operator--(int); void div_rem(const whole_number& other, whole_number& qot, whole_number& rem) const; whole_number pow(std::size_t b) const; whole_number sqrt() const; whole_number root(const whole_number& b) const; std::string to_string() const; std::string to_string(std::size_t base) const; template<typename N> N to_integral() const; const bitvector& get_bitvector() const; private: bitvector _bitvec; whole_number(const bitvector& bitvec); void trim();
{ "domain": "codereview.stackexchange", "id": 44650, "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++, integer", "url": null }
c++, integer whole_number(const bitvector& bitvec); void trim(); void divide_remainder(Word d, whole_number& q, whole_number& r, int stop) const; bool set_numeric_value(const std::string& text, const Word& base); }; template<typename N> inline N whole_number::to_integral() const { return _bitvec.to_integral<N>(); } } } whole_number.cpp #include "whole_number.h" namespace Olly { namespace MPA { whole_number::whole_number() : _bitvec() { } whole_number::whole_number(Word value) : _bitvec(1, value) { } whole_number::whole_number(const std::string& value, Word base) : _bitvec() { set_numeric_value(value, base); } whole_number::whole_number(const std::string& value, Word base, bool& error) : _bitvec() { error = set_numeric_value(value, base); } whole_number::whole_number(const bitvector& bitvec) : _bitvec(bitvec) { } whole_number::~whole_number() { } void swap(whole_number& left, whole_number& right) { whole_number temp = std::move(left); left = std::move(right); right = std::move(temp); } whole_number::operator bool() const { return is(); } bool whole_number::is() const { return _bitvec.is(); } bool whole_number::is_odd() const { return _bitvec.last_word() & 1; } bool whole_number::is_even() const { return !is_odd(); } bool whole_number::operator==(const whole_number& b) const { return operator<=>(b) == std::partial_ordering::equivalent; } bool whole_number::operator!=(const whole_number& b) const { return operator<=>(b) != std::partial_ordering::equivalent; }
{ "domain": "codereview.stackexchange", "id": 44650, "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++, integer", "url": null }
c++, integer std::partial_ordering whole_number::operator<=>(const whole_number& b) const { return _bitvec <=> b._bitvec; } whole_number& whole_number::operator&=(const whole_number& other) { _bitvec &= other._bitvec; trim(); return *this; } whole_number& whole_number::operator|=(const whole_number& other) { _bitvec |= other._bitvec; trim(); return *this; } whole_number& whole_number::operator^=(const whole_number& other) { _bitvec ^= other._bitvec; trim(); return *this; } whole_number& whole_number::operator<<=(std::size_t index) { _bitvec <<= index; trim(); return *this; } whole_number& whole_number::operator>>=(std::size_t index) { _bitvec >>= index; trim(); return *this; } whole_number whole_number::bin_comp() const { whole_number n; n._bitvec = _bitvec.bin_comp(); return n; } whole_number whole_number::operator&(const whole_number& b) const { whole_number a = *this; a &= b; return a; } whole_number whole_number::operator|(const whole_number& b) const { whole_number a = *this; a |= b; return a; } whole_number whole_number::operator^(const whole_number& b) const { whole_number a = *this; a ^= b; return a; } whole_number whole_number::operator~() const { whole_number a; a._bitvec = ~_bitvec; return a; } whole_number whole_number::operator<<(std::size_t index) const { whole_number a = *this; a <<= index; return a; }
{ "domain": "codereview.stackexchange", "id": 44650, "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++, integer", "url": null }
c++, integer whole_number a = *this; a <<= index; return a; } whole_number whole_number::operator>>(std::size_t index) const { whole_number a = *this; a >>= index; return a; } whole_number& whole_number::operator+=(const whole_number& other) { std::size_t limit = _bitvec.size_words() > other._bitvec.size_words() ? _bitvec.size_words() : other._bitvec.size_words(); Double_Word n = 0; for (std::size_t i = 0; i < limit; i += 1) { n = n + _bitvec.at_word(i) + other._bitvec.at_word(i); _bitvec.at_word(i) = static_cast<Word>(n); n >>= _bitvec.value_type; } if (n != 0) { _bitvec.at_word(limit) = static_cast<Word>(n); } trim(); return *this; } whole_number& whole_number::operator-=(const whole_number& other) { if (other > *this) { *this = whole_number(); return *this; } std::size_t limit = _bitvec.size_words() > other._bitvec.size_words() ? _bitvec.size_words() : other._bitvec.size_words(); Double_Word n = 0; for (std::size_t i = 0; i < limit; i += 1) { n = n + _bitvec.at_word(i) - other._bitvec.at_word(i); _bitvec.at_word(i) = static_cast<Word>(n); n = ((n >> _bitvec.value_type) ? -1 : 0); } trim(); return *this; } whole_number& whole_number::operator*=(const whole_number& other) { *this = *this * other; return *this; } whole_number& whole_number::operator/=(const whole_number& other) { *this = *this / other; return *this; } whole_number& whole_number::operator%=(const whole_number& other) {
{ "domain": "codereview.stackexchange", "id": 44650, "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++, integer", "url": null }
c++, integer whole_number& whole_number::operator%=(const whole_number& other) { *this = *this % other; return *this; } whole_number whole_number::operator+(const whole_number& b) const { whole_number a = *this; a += b; return a; } whole_number whole_number::operator-(const whole_number& b) const { whole_number a = *this; a -= b; return a; } whole_number whole_number::operator*(const whole_number& b) const { std::size_t size_a = _bitvec.size_words(); std::size_t size_b = b._bitvec.size_words(); bitvector r((size_a + size_b + 1), 0); for (std::size_t j = 0; j < size_b; j += 1) { Double_Word n = 0; for (std::size_t i = 0; i < size_a; i += 1) { std::size_t k = i + j; n += static_cast<Double_Word>(_bitvec.at_word(i)) * b._bitvec.at_word(j) + r.at_word(k); r.at_word(k) = static_cast<Word>(n); n >>= _bitvec.value_type; } r.at_word(j + size_a) = static_cast<Word>(n); } r.trim(); return r; } whole_number whole_number::operator/(const whole_number& b) const { whole_number q; whole_number r; div_rem(b, q, r); return q; } whole_number whole_number::operator%(const whole_number& b) const { whole_number q; whole_number r; div_rem(b, q, r); return r; } whole_number operator&(whole_number&& a, const whole_number& b) { return a &= b; } whole_number operator|(whole_number&& a, const whole_number& b) { return a |= b; }
{ "domain": "codereview.stackexchange", "id": 44650, "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++, integer", "url": null }
c++, integer whole_number operator^(whole_number&& a, const whole_number& b) { return a ^= b; } whole_number operator<<(whole_number&& a, std::size_t index) { return a <<= index; } whole_number operator>>(whole_number&& a, std::size_t index) { return a >>= index; } whole_number operator+(whole_number&& a, const whole_number& b) { return a += b; } whole_number operator-(whole_number&& a, const whole_number& b) { return a -= b; } whole_number operator*(whole_number&& a, const whole_number& b) { return a *= b; } whole_number operator/(whole_number&& a, const whole_number& b) { return a /= b; } whole_number operator%(whole_number&& a, const whole_number& b) { return a %= b; } whole_number& whole_number::operator++() { ++_bitvec; trim(); return *this; } whole_number whole_number::operator++(int) { whole_number a(*this); operator++(); return a; } whole_number& whole_number::operator--() { --_bitvec; trim(); return *this; } whole_number whole_number::operator--(int) { whole_number a(*this); operator--(); return a; } void whole_number::div_rem(const whole_number& other, whole_number& qot, whole_number& rem) const { // Ensure both the qotient and remander are initalized to zero. qot = whole_number(); rem = whole_number(); if (!other.is()) { // Division by zero. return; }
{ "domain": "codereview.stackexchange", "id": 44650, "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++, integer", "url": null }
c++, integer if (other > *this) { // Division by a greater value. qot = whole_number(); rem = *this; return; } if (*this > other) { if (other._bitvec.size_words() == 1) { divide_remainder(other._bitvec.at_word(0), qot, rem, 0); return; } int stop = static_cast<int>(other._bitvec.size_words() - 1); auto d = other._bitvec.at_word(stop); for (int i = stop - 1; i >= 0; i -= 1) { // Add one to 'd' if any other digits are defined. if (other._bitvec.at_word(i) != 0) { d += 1; break; } } // Perform long division. whole_number n = *this; whole_number q = whole_number(); whole_number guard = whole_number(); while (n >= other && n != guard) { n.divide_remainder(d, q, rem, stop); qot += q; guard = n; n -= (other * q); q = whole_number(); } // Confirm the qoutent is correct. q = other * qot; while (q < *this) { qot += whole_number(1); q += other; } while (q > *this) { qot -= whole_number(1); q -= other; } // Determine the remainder. rem = *this - q; return; } // Return division by two equal values. qot = whole_number(1); rem = whole_number(); } whole_number whole_number::pow(std::size_t b) const {
{ "domain": "codereview.stackexchange", "id": 44650, "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++, integer", "url": null }
c++, integer whole_number whole_number::pow(std::size_t b) const { if (b == 2) { whole_number a = *this; return a * a; } if (b == 1) { return *this; } if (b == 0) { return 1; } whole_number a = *this; whole_number res = 1; while (b) { if (b & 1) { res *= a; } b >>= 1; if (b) { a *= a; } } return res; } whole_number whole_number::sqrt() const { return static_cast<Word>(_bitvec.lead_bit() - 1); } whole_number whole_number::root(const whole_number& b) const { std::size_t n = b.to_integral<std::size_t>(); whole_number low = 0; whole_number high = 1; whole_number ONE = 1; whole_number TWO = 2; while (high.pow(n) <= *this) { low = high; high *= TWO; } while (low != high - ONE) { whole_number step = (high - low) / TWO; whole_number candidate = low + step; auto value = candidate.pow(n); if (value == *this) { return candidate; } if (value < *this) { low = candidate; } else { high = candidate; } } return low; } std::string whole_number::to_string() const { return to_string(10); } std::string whole_number::to_string(std::size_t base) const { if (base == 10 || base == 0 || base == 2 || base == 8 || base == 16) { std::string result = "";
{ "domain": "codereview.stackexchange", "id": 44650, "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++, integer", "url": null }
c++, integer std::string result = ""; if (!is()) { return "0"; } whole_number radix = static_cast<Word>(base != 0 ? base : 10); whole_number n = *this; std::stringstream stream; int count = 0; while (n.is()) { whole_number q; whole_number r = n; n.div_rem(radix, q, r); n = q; if (base == 16) { stream << std::hex << r._bitvec.at_word(0); } else if (base == 8) { stream << std::oct << r._bitvec.at_word(0); } else { stream << r._bitvec.at_word(0); } if (base == 10) { count += 1; if (count == 3) { stream << ','; count = 0; } } } std::string res = stream.str(); if (res.back() == ',') { res.pop_back(); } for (auto i = res.crbegin(); i != res.crend(); ++i) { result += *i; } return result; } return ""; } const bitvector& whole_number::get_bitvector() const { return _bitvec; } void whole_number::divide_remainder(Word d, whole_number& q, whole_number& r, int stop) const { Double_Word n(0); for (int i = static_cast<int>(_bitvec.size_words() - 1); i >= stop; i -= 1) { n += _bitvec.at_word(i); q._bitvec.at_word(static_cast<std::size_t>(i) - stop) = static_cast<Word>(n / d);
{ "domain": "codereview.stackexchange", "id": 44650, "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++, integer", "url": null }
c++, integer q._bitvec.at_word(static_cast<std::size_t>(i) - stop) = static_cast<Word>(n / d); n %= d; n <<= _bitvec.value_type; } r._bitvec.at_word(0) = n >> _bitvec.value_type; return; } bool whole_number::set_numeric_value(const std::string& text, const Word& base) { if (base == 10) { // Parse a decimal number. Word x = 0; for (const auto n : text) { if (!std::isspace(n) && n != ',') { x = n - '0'; if (x >= 0 && x < base) { operator*=(base); operator+=(x); } else { _bitvec = bitvector(); return true; } } } } else if (base == 16) { // Parse a hexidecimal number. Word x; for (const auto n : text) { if (!std::isspace(n)) { switch (n) {
{ "domain": "codereview.stackexchange", "id": 44650, "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++, integer", "url": null }
c++, integer if (!std::isspace(n)) { switch (n) { case('a'): case('A'): x = 10; break; case('b'): case('B'): x = 11; break; case('c'): case('C'): x = 12; break; case('d'): case('D'): x = 13; break; case('e'): case('E'): x = 14; break; case('f'): case('F'): x = 15; break; default: x = (n - '0'); } if (x >= 0 && x < base) { operator*=(base); operator+=(x); } else { _bitvec = bitvector(); return true; } } } } else if (base == 8) { // Parse an octal number. Word x; for (const auto n : text) { if (!std::isspace(n)) { x = n - '0'; if (x >= 0 && x < base) { operator*=(base); operator+=(x); } else { _bitvec = bitvector(); return true; } } } }
{ "domain": "codereview.stackexchange", "id": 44650, "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++, integer", "url": null }
c++, integer else if (base == 2) { // Parse a binary number. for (const auto n : text) { operator<<=(1); if (n == '1') { operator+=(1); } else if (n != '0') { _bitvec = bitvector(); return true; } } } return false; } void whole_number::trim() { _bitvec.trim(); } } }
{ "domain": "codereview.stackexchange", "id": 44650, "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++, integer", "url": null }
c++, integer Answer: Interface I think the constructor that can be invoked with a std::string should be explicit. We should have implicit conversion only from integer types. And consider accepting std::string_view to avoid converting other string-like types to std::string. The only virtual function is the destructor. That's a likely sign that we're not intending to derive from this class and own it as a pointer-to-base, so we can make it non-virtual and eliminate the need for a vtable. operator!= can be defaulted. Function names is() and bin_func() are not self-explanatory - probably need comments. We don't need the member versions of binary operations, given the friend functions that implement them. Just pass the first argument by value. Is operator~() really useful with an arbitrary-width type? Consider naming the square-root function isqrt() - that's more explicit that we find only the integer part, and is a commonly-used name for this. Consider providing character stream << and >> operators, rather than requiring construction of std::string objects for this. to_string() could be a single function with default base. Do we really need get_bitvector? If we eliminate this, we would then be free to change the internal representation. Consider using the platform's native word size for arithmetic - GCC has __builtin_*_overflow() functions to help with this, as do many other platforms. Fall back to the usual overflow computation for unknown targets. Implementation It's hard to review the implementation without the bitvector interface. There's a lot more blank lines than I would use - it almost looks double-spaced. The member swap() exactly duplicates std::swap. It would be better implemented as std::swap(left.bitvec, right.bitvec) - or perhaps bitvector provides a better swap() that could be used instead?
{ "domain": "codereview.stackexchange", "id": 44650, "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++, integer", "url": null }
c++, integer Binary operators implemented in terms of assignment operators can be simplified, by passing first argument by value. That's done correctly in the friend functions, but not in the member versions which I've already said should be removed. It's not clear why +, ++, *, etc. require trim() to be called - isn't that necessary only for functions which might reduce the length? Division by zero gives results that are indistinguishable from division of zero. We need a better way to signal this error. sqrt() implementation looks strange - unless bitvector::lead_bit() does something surprising. I'd like to see the tests for this one. root() should probably just accept a std::size_t, rather than misleading the user. The values ONE and TWO should probably be const (and lower-case, since we normally use all-caps to draw attention to macro expansions). to_string could do the error return first, and remove an indentation for most of the function. We should be inserting , (or .) only if the locale specifies a thousands separator. What's the return type of bitvector::at_word()? It's not clear that streaming from this will emit a single digit. In particular, how does stream << r._bitvec.at_word(0); work for both binary and decimal? That's another case where seeing the unit tests would be helpful. div_rem() is expensive for the exact power-of-two bases - but sufficiently general that we can support more than just the specified set. I think we should use >>= for bases 2, 8 and 16. set_numeric_value() passes plain char to std::isspace() - that's UB for negative values. Octal and hex input could use <<= instead of *= for better performance. Unit tests ... are completely absent. I can't approve this code without them.
{ "domain": "codereview.stackexchange", "id": 44650, "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++, integer", "url": null }
performance, c, cuda Title: CUDA kernel to compare pairs of matrices Question: My first time writing anything significant in CUDA. This kernel takes two arrays representing square matrices and compares them pair-wise. It takes into consideration large input arrays, and calculates the appropriate number of threads on the GPU to spawn. Currently takes ~1 second to compare 10 million 2x2 matrices (so 40 million floating point operations) on an RTX3060. This timing is inclusive of the time it takes to copy data to the GPU. I feel this is a little slow for such a simple operation. Any suggestions to improve? #include "cuda_runtime.h" #include "device_launch_parameters.h" #include <stdio.h> // Kernel function to compare multiple pairs of square matrices element-wise __global__ void compare_multiple_matrices(bool *results, const float *matricesA, const float *matricesB, int rank, int num_matrices, int matrices_offset) { int row = blockIdx.y * blockDim.y + threadIdx.y; int col = blockIdx.x * blockDim.x + threadIdx.x; int matrix = blockIdx.z * blockDim.z + threadIdx.z + matrices_offset; results[matrix] = 1; if (row < rank && col < rank && matrix < num_matrices) { int index = matrix * rank * rank + row * rank + col; int is_equal = fabsf(matricesA[index] - matricesB[index]) <= 0.0001f; if (!is_equal) { results[matrix] = 0; } } } extern "C" { int cuda_compare_multiple_matrices(bool *results, const float *matricesA, const float *matricesB, const int rank, const int num_matrices) { int res = 0; // Choose which GPU to run on, change this on a multi-GPU system. cudaError_t cudaStatus = cudaSetDevice(0); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaSetDevice failed! Do you have a CUDA-capable GPU installed?"); return 1; }
{ "domain": "codereview.stackexchange", "id": 44651, "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": "performance, c, cuda", "url": null }
performance, c, cuda return 1; } // Get the GPU device properties cudaDeviceProp deviceProp; int device; cudaGetDevice(&device); cudaGetDeviceProperties(&deviceProp, device); // Calculate the optimal blockDim.z based on the maximum thread count per block int blockDim_z = deviceProp.maxThreadsPerBlock / (16 * 16); dim3 blockDim(16, 16, blockDim_z); // Calculate the grid dimensions based on the GPU's maximum blocks per grid int gridDim_x = min((rank + blockDim.x - 1) / blockDim.x, deviceProp.maxGridSize[0]); int gridDim_y = min((rank + blockDim.y - 1) / blockDim.y, deviceProp.maxGridSize[1]); int gridDim_z = min((num_matrices + blockDim.z - 1) / blockDim.z, deviceProp.maxGridSize[2]); dim3 gridDim(gridDim_x, gridDim_y, gridDim_z); // Allocate GPU buffers for three vectors (two input, one output) . float *dev_matricesA = 0; float *dev_matricesB = 0; bool *dev_results = 0; try { cudaStatus = cudaMalloc((void **)&dev_matricesA, num_matrices * rank * rank * sizeof(float)); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMalloc failed!"); throw; } cudaStatus = cudaMalloc((void **)&dev_matricesB, num_matrices * rank * rank * sizeof(float)); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMalloc failed!"); throw; } cudaStatus = cudaMalloc((void **)&dev_results, num_matrices * sizeof(bool)); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMalloc failed!"); throw; }
{ "domain": "codereview.stackexchange", "id": 44651, "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": "performance, c, cuda", "url": null }
performance, c, cuda // Copy input vectors from host memory to GPU buffers. cudaStatus = cudaMemcpy(dev_matricesA, matricesA, num_matrices * rank * rank * sizeof(float), cudaMemcpyHostToDevice); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMemcpy failed!"); throw; } cudaStatus = cudaMemcpy(dev_matricesB, matricesB, num_matrices * rank * rank * sizeof(float), cudaMemcpyHostToDevice); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMemcpy failed!"); throw; } int matrices_processed = 0; while (matrices_processed < num_matrices) { int matrices_remaining = num_matrices - matrices_processed; int matrices_to_process = min(matrices_remaining, blockDim.z * gridDim.z); compare_multiple_matrices<<<gridDim, blockDim>>>(dev_results, dev_matricesA, dev_matricesB, rank, num_matrices, matrices_processed); // Check for any errors launching the kernel cudaStatus = cudaGetLastError(); if (cudaStatus != cudaSuccess) { fprintf(stderr, "kernel launch failed: %s\n", cudaGetErrorString(cudaStatus)); throw; } // cudaDeviceSynchronize waits for the kernel to finish, and returns any errors encountered during the launch. cudaStatus = cudaDeviceSynchronize(); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaDeviceSynchronize returned error code %d after launching kernel!\n", cudaStatus); throw; } matrices_processed += matrices_to_process; }
{ "domain": "codereview.stackexchange", "id": 44651, "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": "performance, c, cuda", "url": null }
performance, c, cuda matrices_processed += matrices_to_process; } // Copy output vector from GPU buffer to host memory. cudaStatus = cudaMemcpy(results, dev_results, num_matrices * sizeof(bool), cudaMemcpyDeviceToHost); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMemcpy failed!"); throw; } } catch (...) { res = 1; } cudaFree(dev_matricesA); cudaFree(dev_matricesB); cudaFree(dev_results); // cudaDeviceReset must be called before exiting in order for profiling and // tracing tools such as Nsight and Visual Profiler to show complete traces. cudaStatus = cudaDeviceReset(); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaDeviceReset failed!"); res = 1; } return res; } } ```` Answer: ... this is a little slow for such a simple operation. Any suggestions to improve? Avoid work Minor idea: defer computations until needed with re-ordered code. Only assign once. __global__ void compare_multiple_matrices(bool *results, const float *matricesA, const float *matricesB, int rank, int num_matrices, int matrices_offset) { int row = blockIdx.y * blockDim.y + threadIdx.y; if (row < rank) { int col = blockIdx.x * blockDim.x + threadIdx.x; if (col < rank) { int matrix = blockIdx.z * blockDim.z + threadIdx.z + matrices_offset; if (matrix < num_matrices) { // int index = matrix * rank * rank + row * rank + col; int index = (matrix * rank + row) * rank + col; int is_equal = fabsf(matricesA[index] - matricesB[index]) <= 0.0001f; if (!is_equal) { results[matrix] = 0; return; } } } } results[matrix] = 1; }
{ "domain": "codereview.stackexchange", "id": 44651, "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": "performance, c, cuda", "url": null }
performance, c, cuda Non-speed issues Beware overflow Allocation uses: num_matrices * rank * rank * sizeof(float) which is ((int * int) * int) * size_t resulting in a size_t product. Avoid int overflow in the 1st 3 terms and use the widest type first. // num_matrices * rank * rank * sizeof(float) sizeof(float) * num_matrices * rank * rank Likely not now a problem with 40 million, yet code may stumble with later/larger tasks. Allocate to the referenced object, not type I have found sizing the the reference object easier to code right, review and maintain and so reccomend: // cudaStatus = cudaMalloc((void **)&dev_matricesA, // num_matrices * rank * rank * sizeof(float)); cudaStatus = cudaMalloc((void **)&dev_matricesA, sizeof dev_matricesA[0] * num_matrices * rank * rank);
{ "domain": "codereview.stackexchange", "id": 44651, "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": "performance, c, cuda", "url": null }
python, beginner, converting Title: Convert bool to int and int to bool Question: I'm a noob. I wrote this code to convert bools to ints and ints to bools as a past-time but I would like to know whether to continue programming - this is the kind of thing I've been doing, no useful scripts at all. So, I wanted a program and not a module and that's why I wrote the decorator tab: for output. "|" means it's called from the outer scope, and " |" means it's one function deep. boolxint, bool to int. intxbool, int to bool. I also did not want to dirty the functions with prints. I thought it'd be OK to name the decorator underscore, because it just doesn't show. boolean returns an int and integer takes an int and returns a bool. It plays on bool being a subclass of int and plays only with 0's and 1's, False's and True's. Think bool.real, think indexes... __author__ = 'joao pedro' def tab(s): def _(func): def wrapper(*args, **kwargs): print(s) return func(*args, **kwargs) return wrapper return _ @tab(' | boolxint') def boolean(index: bool) -> int: return [0, 1][index] @tab(' | intxbool') def integer(index: int) -> bool: return [False, True][index] @tab('|') def convert(index): if type(index) is bool: return boolean(index) if type(index) is int: return integer(index) print(convert(False)) print(convert(True)) print(convert(0)) print(convert(1)) This is what it does | | boolxint 0 | | boolxint 1 | | intxbool False | | intxbool True
{ "domain": "codereview.stackexchange", "id": 44652, "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, beginner, converting", "url": null }
python, beginner, converting Answer: Don't overengineer things: it leads to code bloat. As you know, bool is already a subclass of int, so conversion between the two should be really simple. You end up having your primary convert() function, two helpers that use index-based trickeration, and then an entire decorator apparatus to print stuff telling you which helper was called. For comparison, here's a simpler approach, with and without validation. Because everything is in one function, I feel no desire for a decorator to tell me which helper was called. def convert(x): # Quick and dirty. return int(x) if x in (True, False) else bool(x) def convert(x): # With validation. if x in (True, False): return int(x) elif isinstance(x, int): return bool(x) else: raise ValueError('...') Overengineering often leads to bugs or ill-conceived design. Due to its index-based mechanics your code doesn't deliver on its promised ability to convert int to bool: it blows up when given anything other than 0 or 1 [correction: as noted in a comment from AJNeufeld, the code also accepts -1 and -2, but gives undesirable answers]. In fairness, you say that the code was written with that intent. But the world doesn't need an int-to-bool converter that handles only zeros and ones ... because False and True are already interchangeable with 0 and 1. If your converter won't handle all integers, what good is it? And if you truly want to limit the conversions to such a small universe of inputs, why write a function at all when a dict will do the same thing? convert = {0: False, 1: True, False: 0, True: 1} convert[True] # If you squint, it almost looks like calling a function. Should you continue with programming? Absolutely! In my experience, it has usually been interesting, sometimes fun, and always useful in career, academics, and personal projects. Every new programmer comes up with strange, convoluted ideas. Don't let this early detour discourage you.
{ "domain": "codereview.stackexchange", "id": 44652, "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, beginner, converting", "url": null }
c++, thread-safety, locking, atomic Title: Basic RAII spinlock class Question: I have written the following class that acts as a simple lock for mutual exclusion: #include <atomic> #include <thread> #include <functional> #include <vector> #include <array> #include <fmt/core.h> namespace util { class [[ nodiscard ]] spinlock { public: using lockable_type = std::atomic_flag; [[ nodiscard ]] explicit spinlock( lockable_type& lockable ) noexcept : m_lockable { lockable } { while ( m_lockable.test_and_set( std::memory_order_acquire ) ) { while ( m_lockable.test( std::memory_order_relaxed ) ); } } spinlock( const spinlock& ) noexcept = delete; spinlock& operator=( const spinlock& ) noexcept = delete; ~spinlock( ) noexcept { m_lockable.clear( std::memory_order_release ); } private: lockable_type& m_lockable; }; } void func( const int value, std::vector<int>& vec, std::atomic_flag& flag ) { for ( auto count { 0uz }; count < 5; ++count ) { const util::spinlock lock { flag }; vec.emplace_back( count + static_cast<decltype( count )>( value ) ); } } int main( ) { std::atomic_flag flag { }; std::vector<int> result; { std::array<std::jthread, 3> threads { }; auto& [ first_thread, second_thread, third_thread ] { threads }; first_thread = std::jthread { func, 0, std::ref( result ), std::ref( flag ) }; second_thread = std::jthread { func, 5, std::ref( result ), std::ref( flag ) }; third_thread = std::jthread { func, 10, std::ref( result ), std::ref( flag ) }; } for ( auto&& elem : result ) fmt::print( "{}\n", elem ); }
{ "domain": "codereview.stackexchange", "id": 44653, "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++, thread-safety, locking, atomic", "url": null }
c++, thread-safety, locking, atomic for ( auto&& elem : result ) fmt::print( "{}\n", elem ); } Is the above program (live) correct (in terms of race conditions, etc)? How good/bad is the design of the spinlock class? What could be improved here? It seems to work fine though. The design of the class is similar to std::lock_guard but operates on the std::atomic_flag instead of a mutex type. It does not support copying/moving. And the constructor and the destructor are marked as noexcept. Also would be better if while ( m_lockable.test( std::memory_order_relaxed ) ); had a body like std::this_thread::sleep_for(duration); in order to reduce the load on the CPU? If so then how should it be implemented so that it depends on the client's choice whether they want to have sleeps in between calls to test or not and the amount of sleeping? Answer: Instead of creating your own std::lock_guard-style class that works on a std::atomic_flag, consider creating a class that wraps the std::atomic_flag but provides lock() and unlock() member functions. This would allow std::lock_guard to work with your spinlock class. Even better, other standard functions and classes like std::lock(), std::unique_lock and std::scoped_lock would then also work with your class. Another benefit would be safety: a std::atomic_flag variable itself doesn't look like a lock. The compiler doesn't warn you if something sets or clears the flag when it shouldn't. By wrapping it in a type to make it look and behave like a BasicLockable, there is less chance of making mistakes in your code.
{ "domain": "codereview.stackexchange", "id": 44653, "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++, thread-safety, locking, atomic", "url": null }
c++, recursion, template, c++20, constrained-templates Title: A recursive_sum Template Function Implementation with Unwrap Level in C++ Question: This is a follow-up question for A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++ and A recursive_transform_view Template Function Implementation. In the previous question, the implementation of recursive_sum template function performs summation operation on input container exhaustively. I am trying to make another version recursive_sum function which is used for dealing with nested iterables with unwrap level in C++. The experimental implementation recursive_sum template function implementation: template< std::size_t unwrap_level, class T> requires (unwrap_level <= recursive_depth<T>()) constexpr auto recursive_sum(const T& input) { if constexpr (recursive_depth<T>() - unwrap_level == 0) { return input; } else { return UL::recursive_transform<unwrap_level>( input, [](auto&& element){ return recursive_sum_all(element); } ); } } Full Testing Code The full testing code: // A recursive_sum Template Function Implementation with Unwrap Level in C++ #include <algorithm> #include <array> #include <cassert> #include <chrono> #include <complex> #include <concepts> #include <deque> #include <execution> #include <exception> #include <functional> #include <iostream> #include <iterator> #include <list> #include <map> #include <mutex> #include <numeric> #include <optional> #include <queue> #include <ranges> #include <stack> #include <stdexcept> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <variant> #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); };
{ "domain": "codereview.stackexchange", "id": 44654, "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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<typename T> concept is_summable = requires(T x) { x + x; }; // recursive_depth function implementation template<typename T> constexpr std::size_t recursive_depth() { return 0; } template<std::ranges::input_range Range> constexpr std::size_t recursive_depth() { return recursive_depth<std::ranges::range_value_t<Range>>() + 1; } // recursive_invoke_result_t implementation template<typename, typename> struct recursive_invoke_result { }; template<typename T, std::regular_invocable<T> F> struct recursive_invoke_result<F, T> { using type = std::invoke_result_t<F, T>; }; template<typename F, template<typename...> typename Container, typename... Ts> requires ( !std::regular_invocable<F, Container<Ts...>>&& // F cannot be invoked to Container<Ts...> directly std::ranges::input_range<Container<Ts...>>&& requires { typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type; }) struct recursive_invoke_result<F, Container<Ts...>> { using type = Container< typename recursive_invoke_result< F, std::ranges::range_value_t<Container<Ts...>> >::type >; }; template<template<typename, std::size_t> typename Container, typename T, std::size_t N, std::regular_invocable<Container<T, N>> F> struct recursive_invoke_result<F, Container<T, N>> { using type = std::invoke_result_t<F, Container<T, N>>; };
{ "domain": "codereview.stackexchange", "id": 44654, "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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<template<typename, std::size_t> typename Container, typename T, std::size_t N, typename F> requires ( !std::regular_invocable<F, Container<T, N>>&& // F cannot be invoked to Container<Ts...> directly requires { typename recursive_invoke_result<F, std::ranges::range_value_t<Container<T, N>>>::type; }) struct recursive_invoke_result<F, Container<T, N>> { using type = Container< typename recursive_invoke_result< F, std::ranges::range_value_t<Container<T, N>> >::type , N>; }; template<typename F, typename T> using recursive_invoke_result_t = typename recursive_invoke_result<F, T>::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": 44654, "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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, 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; // 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)); } } namespace UL // unwrap_level { template< std::ranges::input_range Container, std::copy_constructible F> requires (std::ranges::view<Container>&& std::is_object_v<F>) constexpr auto make_view(const Container& input, const F& f) noexcept { return std::ranges::transform_view( input, [&f](const auto&& element) constexpr { return recursive_transform(element, f ); } ); }
{ "domain": "codereview.stackexchange", "id": 44654, "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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates /* Override make_view to catch dangling references. A borrowed range is * safe from dangling.. */ template <std::ranges::input_range T> requires (!std::ranges::borrowed_range<T>) constexpr std::ranges::dangling make_view(T&&) noexcept { return std::ranges::dangling(); }
{ "domain": "codereview.stackexchange", "id": 44654, "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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates // clone_empty_container template function implementation template< std::size_t unwrap_level = 1, std::ranges::input_range Container, std::copy_constructible F> requires (std::ranges::view<Container>&& std::is_object_v<F>) constexpr auto clone_empty_container(const Container& input, const F& f) noexcept { const auto view = make_view(input, f); recursive_variadic_invoke_result<unwrap_level, F, Container> output(std::span{input}); return output; } // recursive_transform template function implementation (the version with unwrap_level template parameter) template< std::size_t unwrap_level = 1, class T, std::copy_constructible F> requires (unwrap_level <= recursive_depth<T>()&& // handling incorrect unwrap levels more gracefully, https://codereview.stackexchange.com/a/283563/231235 std::ranges::view<T>&& std::is_object_v<F>) constexpr auto recursive_transform(const T& input, const F& f) { if constexpr (unwrap_level > 0) { auto output = clone_empty_container(input, f); if constexpr (is_reservable<decltype(output)>&& is_sized<decltype(input)>) { output.reserve(input.size()); std::ranges::transform( input, std::ranges::begin(output), [&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); } ); } else { std::ranges::transform( input, std::inserter(output, std::ranges::end(output)), [&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); } ); } return output; }
{ "domain": "codereview.stackexchange", "id": 44654, "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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates ); } return output; } else if constexpr(std::regular_invocable<F, T>) { return std::invoke(f, input); } else { static_assert(!std::regular_invocable<F, T>, "Uninvocable?"); } }
{ "domain": "codereview.stackexchange", "id": 44654, "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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates /* This overload of recursive_transform is to support std::array */ template< std::size_t unwrap_level = 1, template<class, std::size_t> class Container, typename T, std::size_t N, typename F > requires (std::ranges::input_range<Container<T, N>>) constexpr auto recursive_transform(const Container<T, N>& input, const F& f) { Container<recursive_variadic_invoke_result_t<unwrap_level, F, T>, N> output; std::ranges::transform( input, std::ranges::begin(output), [&f](auto&& element){ return recursive_transform<unwrap_level - 1>(element, f); } ); return output; } // recursive_transform function implementation (the version with unwrap_level, without using view) template<std::size_t unwrap_level = 1, class T, class F> requires (!std::ranges::view<T>) constexpr auto recursive_transform(const T& input, const F& f) { if constexpr (unwrap_level > 0) { static_assert(unwrap_level <= recursive_depth<T>(), "unwrap level higher than recursion depth of input"); // trying to handle incorrect unwrap levels more gracefully recursive_variadic_invoke_result_t<unwrap_level, F, T> output{}; std::ranges::transform( input, // passing a range to std::ranges::transform() std::inserter(output, std::ranges::end(output)), [&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); } ); return output; } else { return std::invoke(f, input); // use std::invoke() } } }
{ "domain": "codereview.stackexchange", "id": 44654, "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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates namespace NonUL { template< std::ranges::input_range Container, std::copy_constructible F> requires (std::ranges::input_range<Container>&& std::ranges::view<Container>&& std::is_object_v<F>) constexpr auto make_view(const Container& input, const F& f) noexcept { return std::ranges::transform_view( input, [&f](const auto&& element) constexpr { return recursive_transform(element, f ); } ); } /* Override make_view to catch dangling references. A borrowed range is * safe from dangling.. */ template <std::ranges::input_range T> requires (!std::ranges::borrowed_range<T>) constexpr std::ranges::dangling make_view(T&&) noexcept { return std::ranges::dangling(); } /* Base case of NonUL::recursive_transform template function https://codereview.stackexchange.com/a/283581/231235 */ template< typename T, std::regular_invocable<T> F> requires (std::copy_constructible<F>) constexpr auto recursive_transform( const T& input, const F& f ) { return std::invoke( f, input ); } /* The recursive case of NonUL::recursive_transform template function https://codereview.stackexchange.com/a/283581/231235 */ template< std::ranges::input_range Container, std::copy_constructible F> requires (std::ranges::input_range<Container>&& std::ranges::view<Container>&& std::is_object_v<F>) constexpr auto recursive_transform(const Container& input, const F& f) { const auto view = make_view(input, f); recursive_invoke_result_t<F, Container> output( std::ranges::begin(view), std::ranges::end(view) ); // One last sanity check. if constexpr( is_sized<Container> && is_sized<recursive_invoke_result_t<F, Container>> ) { assert( output.size() == input.size() ); }
{ "domain": "codereview.stackexchange", "id": 44654, "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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates return output; } /* The recursive case of NonUL::recursive_transform template function for std::array https://codereview.stackexchange.com/a/283581/231235 */ template< template<typename, std::size_t> typename Container, typename T, std::size_t N, std::copy_constructible F> requires std::ranges::input_range<Container<T, N>> constexpr auto recursive_transform(const Container<T, N>& input, const F& f) { Container<recursive_invoke_result_t<F, T>, N> output; std::ranges::transform( // Use std::ranges::transform() for std::arrays input, std::ranges::begin(output), [&f](auto&& element){ return recursive_transform(element, f); } ); // One last sanity check. if constexpr( is_sized<Container<T, N>> && is_sized<recursive_invoke_result_t<F, Container<T, N>>> ) { assert( output.size() == input.size() ); } return output; } } /* recursive_sum_all template function performs summation operation on input container exhaustively */ template<class T> requires is_summable<T> auto recursive_sum_all(const T& input) { return input; } template<std::ranges::input_range T> auto recursive_sum_all(const T inputArray) { typedef typename std::iterator_traits<typename T::iterator>::value_type value_type; decltype(recursive_sum_all(std::declval<value_type &&>())) sun_output{}; for (auto& element : inputArray) { sun_output += recursive_sum_all(element); } return sun_output; }
{ "domain": "codereview.stackexchange", "id": 44654, "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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template< std::size_t unwrap_level, class T> requires (unwrap_level <= recursive_depth<T>()) constexpr auto recursive_sum(const T& input) { if constexpr (recursive_depth<T>() - unwrap_level == 0) { return input; } else { return UL::recursive_transform<unwrap_level>( input, [](auto&& element){ return recursive_sum_all(element); } ); } } template<class T> requires (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<class T> requires (std::ranges::input_range<T> && 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::transform(input.cbegin(), input.cend(), output.begin(), [level](auto&& element) { return recursive_print(element, level + 1); } ); return output; } void recursive_sum_tests() { auto test_vectors = n_dim_container_generator<std::vector, 4, int>(1, 3); std::cout << "Play with test_vectors:\n\n"; std::cout << "recursive_sum_all function: \n"; auto recursive_sum_all_result = recursive_sum_all(test_vectors); std::cout << recursive_sum_all_result << "\n\n"; std::cout << "unwrap_level = 4:\n"; auto test_output_1 = recursive_sum<4>(test_vectors); recursive_print(test_output_1); std::cout << "\n\n";
{ "domain": "codereview.stackexchange", "id": 44654, "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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates std::cout << "unwrap_level = 3:\n"; auto test_output_2 = recursive_sum<3>(test_vectors); recursive_print(test_output_2); std::cout << "\n\n"; std::cout << "unwrap_level = 2:\n"; auto test_output_3 = recursive_sum<2>(test_vectors); recursive_print(test_output_3); std::cout << "\n\n"; std::cout << "unwrap_level = 1:\n"; auto test_output_4 = recursive_sum<1>(test_vectors); recursive_print(test_output_4); std::cout << "\n\n"; std::cout << "unwrap_level = 0:\n"; auto test_output_5 = recursive_sum<0>(test_vectors); std::cout << test_output_5 << "\n\n"; return; } int main() { recursive_sum_tests(); return 0; } The output of the test code above: Play with test_vectors: recursive_sum_all function: 81 unwrap_level = 4: Level 0: Level 1: Level 2: Level 3: 1 1 1 Level 3: 1 1 1 Level 3: 1 1 1 Level 2: Level 3: 1 1 1 Level 3: 1 1 1 Level 3: 1 1 1 Level 2: Level 3: 1 1 1 Level 3: 1 1 1 Level 3: 1 1 1 Level 1: Level 2: Level 3: 1 1 1 Level 3: 1 1 1 Level 3: 1 1 1 Level 2: Level 3: 1 1 1 Level 3: 1 1 1 Level 3: 1 1 1 Level 2: Level 3: 1 1 1 Level 3: 1 1 1 Level 3: 1 1 1 Level 1: Level 2: Level 3: 1 1 1 Level 3: 1 1 1 Level 3: 1 1 1 Level 2: Level 3: 1 1 1 Level 3: 1 1 1 Level 3: 1 1 1 Level 2: Level 3: 1 1 1 Level 3: 1 1 1 Level 3: 1 1 1 unwrap_level = 3: Level 0: Level 1: Level 2: 3 3 3 Level 2: 3 3 3 Level 2: 3 3 3 Level 1: Level 2: 3 3 3 Level 2: 3 3 3 Level 2: 3 3 3 Level 1: Level 2: 3 3 3 Level 2: 3 3 3 Level 2: 3 3 3
{ "domain": "codereview.stackexchange", "id": 44654, "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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates unwrap_level = 2: Level 0: Level 1: 9 9 9 Level 1: 9 9 9 Level 1: 9 9 9 unwrap_level = 1: Level 0: 27 27 27 unwrap_level = 0: 81 Godbolt link All suggestions are welcome. The summary information: Which question it is a follow-up to? A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++ and A recursive_transform_view Template Function Implementation What changes has been made in the code since last question? I am trying to implement recursive_sum template function with unwrap level parameter in this post. In this example, I think that the usage of the version recursive_transform with unwrap level is necessary. If there is any misunderstanding, please let me know. Why a new review is being asked for? Please review the experimental implementation of recursive_sum template function. The function perfroms the summation operation on specified level of container.
{ "domain": "codereview.stackexchange", "id": 44654, "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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates Answer: Make it more generic Summing is a very specific operation. What if you want to calculate the product of all elements instead? Or get the minimum or maximum value? Instead of hardcoding the operation, create a recursive_reduce() that works like std::reduce(). You can still have it sum by default if you don't specify which operation to perform. Associativity and initial values Note that the order in which you perform operations matters. While operator+ is often associative, it doesn't have to be. That's why in C++23, std::ranges::fold_left() and std::ranges::fold_right() were introduced. Furthermore, some value types might not have a default constructor, thus sun_output{} might not compile. This is why most algorithms in the STL that perform some kind of reduction take an initial value as a parameter. I recommend you add that here as well. Sometimes you know the input is non-empty, and you want to avoid providing an initial values. C++23 introduced std::ranges::fold_left_first() and related functions for this purpose. Meaning of the unwrap level I was surprised by the fact that your recursive_sum() uses recursive_transform() internally, and by the output from your example code. I would rather have expected the following: std::vector<std::string> words = {"foo", "bar", "baz", "quux"}; std::cout << recursive_sum<2>(words) << '\n'; std::cout << recursive_sum<1>(words) << '\n'; To output: : foobarbazquux
{ "domain": "codereview.stackexchange", "id": 44654, "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++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates To output: : foobarbazquux Basically, the call to recursive_sum<2>(words) would unwrap two levels, so it would iterate over the characters in each string, whereas recursive_sum<1>(words) would unwrap only the vector, and add the strings together. I think that would be more logical. Also consider math libraries that have vector and matrix types that can be iterated over; sometimes you want to sum the elements of a matrix, sometimes you want to sum matrices together, but your code will always sum the innermost elements. Here is how I would implement a basic recursive_sum(): template<std::size_t unwrap_level, class R, class T = recursive_unwrap_type<unwrap_level, R>> requires (unwrap_level <= recursive_depth<R>()) constexpr auto recursive_sum(const R& input, T init = {}) { if constexpr (unwrap_level > 0) { for (const auto& element: input) { init = recursive_sum(element, init); } } else { init += input; } return init; } Where recursive_unwrap_type<unwrap_level, R> would give you the type after unwrapping R for unwrap_level levels. If you want your original behavior, the caller could then combine recursive_transform() and recursive_sum() themselves, like so: auto test_output_3 = recursive_transform<2>( test_vectors, [](auto&& element){ return recursive_sum(element); } );
{ "domain": "codereview.stackexchange", "id": 44654, "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++, recursion, template, c++20, constrained-templates", "url": null }
performance, array, vba, excel Title: concatenate values and delete the remaining rows using arrays Question: the below code used to: Concatenate the values on a specific column "N" depend on the value of column "A" then delete the remaining rows. It works, but with range of 30k rows the macro takes a long time to finish (14 seconds) on powerful PC. Edit: the bottle neck is on this line .SpecialCells(xlCellTypeConstants).EntireRow.Delete (it takes 13.5 seconds) from the overall code time ( 14 seconds). I tried to replace it with VBA AutoFilter , but the same issue. This is updated screenshot: of current values and the current result, My goal is to do all processing on arrays or dictionary to achieve the fastest speed. I have office 2016 on my work. Option Explicit Option Compare Text Sub Concatenate_column_N_values_Delete_remaining_Rows() Dim t: t = Timer
{ "domain": "codereview.stackexchange", "id": 44655, "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": "performance, array, vba, excel", "url": null }
performance, array, vba, excel Sub Concatenate_column_N_values_Delete_remaining_Rows() Dim t: t = Timer Const sep As String = vbLf Dim arrKeys, arrVals, arrFlags, rngRows As Range, key, currKey, s As String Dim ub As Long, n As Long, ws As Worksheet, rngVals As Range, i As Long Set ws = ActiveSheet Set rngRows = ws.Range("A2:A" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row) 'Column Contains WO Set rngVals = rngRows.EntireRow.Columns("N") 'Column contains pure string Application.ScreenUpdating = False arrKeys = rngRows.Value2 ub = UBound(arrKeys, 1) arrVals = rngVals.Value2 ReDim arrFlags(1 To UBound(arrKeys, 1), 1 To 1) currKey = Chr(0) 'non-existing key... For i = ub To 1 Step -1 'looping from bottom up key = arrKeys(i, 1) 'this row's key If key <> currKey Then 'different key from row below? If i < ub Then arrVals(i + 1, 1) = s 'populate the collected info for any previous key s = arrVals(i, 1) 'collect this row's "N" value currKey = key 'set as current key Else If i < ub Then arrFlags(i + 1, 1) = "x" 'flag for deletion n = n + 1 End If s = arrVals(i, 1) & sep & s 'concatenate the "N" value End If Next i arrVals(1, 1) = s 'populate the last (first) row... rngVals.Value = arrVals 'drop the concatenated values If n > 0 Then 'any rows to delete? With rngRows.Offset(0, 100) 'use any empty column .Value = arrFlags .SpecialCells(xlCellTypeConstants).EntireRow.Delete End With End If Application.ScreenUpdating = True Debug.Print "Concatenate_column_N_values_Delete_remaining_Rows, in " & Round(Timer - t, 2) & " sec" End Sub
{ "domain": "codereview.stackexchange", "id": 44655, "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": "performance, array, vba, excel", "url": null }
performance, array, vba, excel Answer: The Bottle Neck: the bottle neck is on this line .SpecialCells(xlCellTypeConstants).EntireRow.Delete (it takes 13.5 seconds) from the code overall time ( 14 seconds). Reason: It is tuned out that deletion of a lot of non-continuous rows takes a lot of time to finish, even after using Application optimizations (ScreenUpdateing.False,...) Answer: I tried another approach by sort the values (rows) which need to be deleted and then set this rows to a range and then delete that range , I measured (Sorting values + Deletion of that range) and it toke 0.12 sec to finish (significantly faster). I replaced .SpecialCells(xlCellTypeConstants).EntireRow.Delete with the below code. Sub Sort_vlaues_x_and_Delete() Dim ws As Worksheet: Set ws = ActiveSheet Dim rng As Range, lastR As Long, lastC As Long, lastcol As String lastR = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row 'Last Row number on coulmn A lastC = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column + 1 'next Last Column on Row 1 lastcol = Split(Cells(1, lastC).Address(True, False), "$")(0) 'Last Column Letter Set rng = ws.Range(ws.Cells(1, 1), ws.Cells(lastR, lastC)) Application.ScreenUpdating = False Application.Calculation = xlCalculationManual '--- Sort values x ws.Sort.SortFields.Clear ws.Sort.SortFields.Add key:=Range(lastcol & "2:" & lastcol & lastR), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal With ws.Sort .SetRange Range("A1:" & lastcol & lastR) .Header = xlYes: .MatchCase = False .Orientation = xlTopToBottom: .SortMethod = xlPinYin .Apply End With '--- Delete range of values x lastR = ws.Cells(ws.Rows.Count, lastcol).End(xlUp).Row Set rng = ws.Range(ws.Cells(2, 1), ws.Cells(lastR, lastC)) rng.Rows.EntireRow.Delete Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True
{ "domain": "codereview.stackexchange", "id": 44655, "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": "performance, array, vba, excel", "url": null }
performance, array, vba, excel End Sub
{ "domain": "codereview.stackexchange", "id": 44655, "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": "performance, array, vba, excel", "url": null }
performance, c, linux, curses, tetris Title: Tetris in C, in 200 lines Question: I aimed at making fully functional (real) Tetris, in the shortest way possible in C. The result is a terminal game for Linux, that uses ncurses. I made it for my friend, who wanted to play it on his Arduino with LED matrix. Before doing it, I browsed for the shortest Tetris code so far. I found the 140-bytes (buggy) JS "Tetris" and 36 lines of JS Tetris with additional HTML. The main idea is to make it even shorter is using bitwise operations: shifting and logical OR. That was my first idea, but when I got to rotation, I had to switch to the array structure. However, there is a problem: it is insanely CPU-intensive. My bet is the main loop that gets cycled too many times. So how can I regulate this problem? And do you think this can be done even shorter in C? #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/time.h> #include <ncurses.h> #define ROWS 20 #define COLS 11 #define TRUE 1 #define FALSE 0 char Table[ROWS][COLS] = {0}; int score = 0; char GameOn = TRUE; double timer = 500000; //half second typedef struct { char **array; int width, row, col; } Shape; Shape current; const Shape ShapesArray[7]= { {(char *[]){(char []){0,1,1},(char []){1,1,0}, (char []){0,0,0}}, 3}, //S_shape {(char *[]){(char []){1,1,0},(char []){0,1,1}, (char []){0,0,0}}, 3}, //Z_shape {(char *[]){(char []){0,1,0},(char []){1,1,1}, (char []){0,0,0}}, 3}, //T_shape {(char *[]){(char []){0,0,1},(char []){1,1,1}, (char []){0,0,0}}, 3}, //L_shape {(char *[]){(char []){1,0,0},(char []){1,1,1}, (char []){0,0,0}}, 3}, //ML_shape {(char *[]){(char []){1,1},(char []){1,1}}, 2}, //SQ_shape {(char *[]){(char []){0,0,0,0}, (char []){1,1,1,1}, (char []){0,0,0,0}, (char []){0,0,0,0}}, 4} //R_shape };
{ "domain": "codereview.stackexchange", "id": 44656, "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": "performance, c, linux, curses, tetris", "url": null }
performance, c, linux, curses, tetris Shape CopyShape(Shape shape){ Shape new_shape = shape; char **copyshape = shape.array; new_shape.array = (char**)malloc(new_shape.width*sizeof(char*)); int i, j; for(i = 0; i < new_shape.width; i++){ new_shape.array[i] = (char*)malloc(new_shape.width*sizeof(char)); for(j=0; j < new_shape.width; j++) { new_shape.array[i][j] = copyshape[i][j]; } } return new_shape; } void DeleteShape(Shape shape){ int i; for(i = 0; i < shape.width; i++){ free(shape.array[i]); } free(shape.array); } int CheckPosition(Shape shape){ //Check the position of the copied shape char **array = shape.array; int i, j; for(i = 0; i < shape.width;i++) { for(j = 0; j < shape.width ;j++){ if((shape.col+j < 0 || shape.col+j >= COLS || shape.row+i >= ROWS)){ //Out of borders if(array[i][j]) //but is it just a phantom? return FALSE; } else if(Table[shape.row+i][shape.col+j] && array[i][j]) return FALSE; } } return TRUE; } void GetNewShape(){ //returns random shape Shape new_shape = CopyShape(ShapesArray[rand()%7]); new_shape.col = rand()%(COLS-new_shape.width+1); new_shape.row = 0; DeleteShape(current); current = new_shape; if(!CheckPosition(current)){ GameOn = FALSE; } } void RotateShape(Shape shape){ //rotates clockwise Shape temp = CopyShape(shape); int i, j, k, width; width = shape.width; for(i = 0; i < width ; i++){ for(j = 0, k = width-1; j < width ; j++, k--){ shape.array[i][j] = temp.array[k][i]; } } DeleteShape(temp); } void WriteToTable(){ int i, j; for(i = 0; i < current.width ;i++){ for(j = 0; j < current.width ; j++){ if(current.array[i][j]) Table[current.row+i][current.col+j] = current.array[i][j]; } } }
{ "domain": "codereview.stackexchange", "id": 44656, "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": "performance, c, linux, curses, tetris", "url": null }
performance, c, linux, curses, tetris void Halleluyah_Baby(){ //checks lines int i, j, sum, count=0; for(i=0;i<ROWS;i++){ sum = 0; for(j=0;j< COLS;j++) { sum+=Table[i][j]; } if(sum==COLS){ count++; int l, k; for(k = i;k >=1;k--) for(l=0;l<COLS;l++) Table[k][l]=Table[k-1][l]; for(l=0;l<COLS;l++) Table[k][l]=0; } } timer-=1000; score += 100*count; } void PrintTable(){ char Buffer[ROWS][COLS] = {0}; int i, j; for(i = 0; i < current.width ;i++){ for(j = 0; j < current.width ; j++){ if(current.array[i][j]) Buffer[current.row+i][current.col+j] = current.array[i][j]; } } clear(); for(i = 0; i < ROWS ;i++){ for(j = 0; j < COLS ; j++){ printw("%c ", (Table[i][j] + Buffer[i][j])? 'O': '.'); } printw("\n"); } printw("\nScore: %d\n", score); } void ManipulateCurrent(int action){ Shape temp = CopyShape(current); switch(action){ case 's': temp.row++; //move down if(CheckPosition(temp)) current.row++; else { WriteToTable(); Halleluyah_Baby(); //check full lines, after putting it down GetNewShape(); } break; case 'd': temp.col++; //move right if(CheckPosition(temp)) current.col++; break; case 'a': temp.col--; //move left if(CheckPosition(temp)) current.col--; break; case 'w': RotateShape(temp); //yes if(CheckPosition(temp)) RotateShape(current); break; } DeleteShape(temp); PrintTable(); }
{ "domain": "codereview.stackexchange", "id": 44656, "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": "performance, c, linux, curses, tetris", "url": null }
performance, c, linux, curses, tetris int main() { srand(time(0)); score = 0; int c; initscr(); struct timeval before, after; gettimeofday(&before, NULL); nodelay(stdscr, TRUE); GetNewShape(); PrintTable(); while(GameOn){ if ((c = getch()) != ERR) { ManipulateCurrent(c); } gettimeofday(&after, NULL); if (((double)after.tv_sec*1000000 + (double)after.tv_usec)-((double)before.tv_sec*1000000 + (double)before.tv_usec) > timer){ //time difference in microsec accuracy before = after; ManipulateCurrent('s'); } } printw("\nGame over\n"); DeleteShape(current); return 0; } Makefile: tetris: tetris.c gcc tetris.c -lncurses -o tetris UPDATE This is how I finished this little "project": https://github.com/najibghadri/Tetris200lines You can make any shape and play on any sized table :) Answer: Minimize math operations if (((double)after.tv_sec*1000000 + (double)after.tv_usec)-((double)before.tv_sec*1000000 + (double)before.tv_usec) > timer){ //time difference in microsec accuracy You do four conversions from integer types to a double precision floating point type. And do two multiplications times a million. Consider //time difference in microsec accuracy if (((double)(after.tv_sec - before.tv_sec)*1000000 + (double)(after.tv_usec - before.tv_usec)) > timer) { This only does two conversions and one multiplication. Or this answer suggests that you could instead use uint64_t. //time difference in microsec accuracy if (((after.tv_sec - before.tv_sec)*(uint64_t)1000000 + (after.tv_usec - before.tv_usec)) > timer) { Optimize the common path Also, if this is usually false, consider flipping things around.
{ "domain": "codereview.stackexchange", "id": 44656, "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": "performance, c, linux, curses, tetris", "url": null }
performance, c, linux, curses, tetris Optimize the common path Also, if this is usually false, consider flipping things around. if (((double)after.tv_sec*1000000 + (double)after.tv_usec)-((double)before.tv_sec*1000000 + (double)before.tv_usec) > timer){ //time difference in microsec accuracy before = after; ManipulateCurrent('s'); } could become if (IS_LATER(after, before)) { before = ADD_TO_TIMEVALUE(after, 500000); ManipulateCurrent('s'); } with #define IS_LATER(a, b) ((a.tv_sec == b.tv_sec && a.tv_usec > b.tv_usec) || a.tv_sec > b.tv_sec) and #define ADD_TO_TIMEVALUE(tv, t) do {\ tv.tv_usec += t; \ while (tv.tv_usec >= 1000000) { \ tv.tv_usec -= 1000000; \ tv.tv_sec++; \ } \ } while (0) This makes updating before more expensive, but makes comparing before and after cheaper (up to three comparisons rather than two conversions, a multiplication, an addition, subtractions, and a comparison). If you usually don't update, this is better. Also note that it is more modern (C99 and later) to do this with inline functions than macros. But is that the problem? This will make the loop operate faster, but that's not really the problem. You keep looping until a certain amount of time has passed. Looping faster won't change that. You might better find a way to loop more slowly to use less CPU. You are using nodelay(stdscr, TRUE); Consider instead halfdelay(1); Then it should block on input until it times out (after a tenth of a second). So if the user isn't hitting keys, this will only process five times (at most) before advancing the row. Note: I haven't tried it.
{ "domain": "codereview.stackexchange", "id": 44656, "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": "performance, c, linux, curses, tetris", "url": null }
python, python-3.x Title: Script to access API and print formatted report to stdout Question: I work for a non-profit that runs acoustic music camps for adults. This script queries the API for Regfox, the event registration software we use, and prints for each camp a table showing the number of spots available for each of the accommodation types we offer. All comments appreciated, especially how to make the code more pythonic. import requests from collections import namedtuple import credentials # local file # ========================================================================= # THIS INFO CHANGES AT START OF EACH CAMP SEASON, OTHERWISE IMMUTABLE # ------------------------------------------------------------------------ CampInfo = namedtuple("CampInfo", ["full_name", "regfox_page_id"]) MANDO_CAMP = CampInfo("2023 Mandolin Camp North", credentials.MC_REGFOX_PAGE_ID) BANJO_CAMP = CampInfo("2023 Banjo Camp North", credentials.BC_REGFOX_PAGE_ID) ColumnWidth = namedtuple("ColumnWidth", ["name", "width"]) name = ColumnWidth("Name", 47) supply = ColumnWidth("Supply", 7) # these three are number of chars + 1 sold = ColumnWidth("Sold", 5) available = ColumnWidth("Available", 10) ROOM_TYPES = ( "Single room, private bath, Hilltop campus", "Single room, shared bath, Pondside campus", "Double room, private bath, Hilltop campus", "Double room, shared bath, Pondside campus", "Quad room, shared bath, Pondside campus", "Double room, [NON-PARTICIPATING CAMPER], private bath, Hilltop campus", "Double room, [NON-PARTICIPATING CAMPER], shared bath, Pondside campus", "Commuter / RV", "Commuter / RV, [NON-PARTICIPATING CAMPER]", "Friday", "Saturday", "Sunday", "Friday evening", "Saturday evening", ) # =========================================================================
{ "domain": "codereview.stackexchange", "id": 44657, "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", "url": null }
python, python-3.x def print_row(a, b, c, d): """Print a row in a table""" for text, align, width in zip( [a, b, c, d], "<>>>", [name.width, supply.width, sold.width, available.width], ): print( "{text:{align}{width}}".format(text=text, align=align, width=width), end="", ) print() def print_header(camp): """Print a header for a camp""" separator_length = 69 print() print("=" * separator_length) print(camp.full_name) print("-" * separator_length) print_row("Room type", "Supply", "Sold", "Available") print("-" * separator_length) def get_inventory(regfox_page_id): """Get data for each kind of room via Regfox API""" url_string = ( "https://api.webconnex.com/v2/public/forms/" + regfox_page_id + "/inventory" ) try: r = requests.get( url=url_string, headers={ "apiKey": credentials.API_KEY, }, ) return r.json() except requests.exceptions.RequestException: print("HTTP Request failed") def create_table(camp): """Create a table for one camp""" inventory_raw = get_inventory(camp.regfox_page_id) inventory = inventory_raw["data"] for room_type in ROOM_TYPES: for i in inventory: if i["name"] == room_type: available = i["quantity"] - i["sold"] # shorten long names if "NON-PARTICIPATING" in i["name"]: i["name"] = i["name"].replace( "[NON-PARTICIPATING CAMPER]", "NON-PART" ) i["name"] = i["name"].replace(" campus", "") print_row(i["name"], i["quantity"], i["sold"], available) def main(): for camp in [MANDO_CAMP, BANJO_CAMP]: print_header(camp) create_table(camp) print() if __name__ == main(): main()
{ "domain": "codereview.stackexchange", "id": 44657, "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", "url": null }
python, python-3.x if __name__ == main(): main() Answer: In many ways this is some very nice code. The author has clearly exercised great care when trying to make it readable & maintainable by others. There are some structural aspects that could be improved, the biggest of which is dealing generically with tables. CampInfo = namedtuple("CampInfo", ["full_name", "regfox_page_id"]) MANDO_CAMP = CampInfo("2023 Mandolin Camp North", credentials.MC_REGFOX_PAGE_ID) BANJO_CAMP = CampInfo("2023 Banjo Camp North", credentials.BC_REGFOX_PAGE_ID) I really like this approach to solving "same problem" for two camps. supply = ColumnWidth("Supply", 7) # these three are number of chars + 1 sold = ColumnWidth("Sold", 5) available = ColumnWidth("Available", 10) The magic number 47 is apparently a tuning parameter related to your data and your paper width or video display width; I'm willing to call it inevitable for now. It has a nice clear name.width label, good. For the code as written, the comment is very helpful, thank you. But DRY. I am sad that we're specifying 7, 5, 10, rather than obtaining them as 1 + len() of string constant results. Pep-8 asks that you capitalize these class names: Name, Supply, Sold, Available. separator_length = 69 Kudos, this is the perfect way to deal with a magic number. (Assuming it must be hardcoded, rather than dynamically computed. Or even found as a sum of other static magic numbers.) def get_inventory(regfox_page_id): """Get data for each kind of room via Regfox API""" ... return r.json() except requests.exceptions.RequestException: print("HTTP Request failed")
{ "domain": "codereview.stackexchange", "id": 44657, "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", "url": null }
python, python-3.x Yay, we have a docstring! There is a single business concept, a room type, which here we refer to as a room kind. On initial reading I utterly failed to understand what the docstring was trying convey to me. From the singular "each" I got the impression that page ID encoded room type and we would return records for just one of the 14 room types. Recommend you rephrase it as "Get data for all room types...", since it turns out that page ID encodes the camp rather than the room type of interest. Getting the URL looks beautiful. But it might have errored. And then we swallow the error and soldier on, having reported it to stdout. For the benefit of future maintainers, it might be nice to mention which URL failed. Consider discarding the try and do this right after the GET: r.raise_for_status() return r.json() That is, consider making errors fatal. It's not clear to me that the business can usefully consume a "partial" report. Consider doing return r.json()["data"], since that's all the consumer cares about anyway. for room_type in ROOM_TYPES: for i in inventory: if i["name"] == room_type: Making 14 passes over the API result is not end of the world, but it is slightly unfortunate. There's a couple of things going on here, and we would like for create_table to stick to a single responsibility. So consider writing a helper that generates rows in the desired order, and using sorted() to produce that order. Here is what I have in mind: for row in _get_sorted_rows(inventory): available = row["quantity"] - row["sold"] ... from functools import lru_cache def _get_sorted_rows(inventory): """Puts same room type together. Due to stable sort, row order is otherwise preserved.""" return sorted(inventory, key=lambda row: _room_type_index(row["name"])) @lru_cache def _room_type_index(room_type: str) -> int: return ROOM_TYPES.index(room_type) # shorten long names
{ "domain": "codereview.stackexchange", "id": 44657, "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", "url": null }
python, python-3.x # shorten long names Thank you for the helpful comment. The fact that you found it necessary to write it suggests that we should revisit the Single Responsibility topic and break out a def _shorten(long_name): helper. def print_row(a, b, c, d): ... for text, align, width in zip( [a, b, c, d], "<>>>", [name.width, supply.width, sold.width, available.width], The generic parameter names is kind of nice. It suggests this is a pretty general purpose routine. But then it turns out there's this peculiar relationship to the static magic width figures. Maybe caller should pass in four arguments which each have a width attached? Maybe pass in a vector of widths? Kudos on the zip() and the <>>>, that's just lovely. dynamic widths Maybe there are aesthetic or business reasons why the column widths must be what they are. But maybe we could compute them dynamically from the data? Your table is a list of rows, a list of dicts. Processing phases would be: table = _get_rows(...) widths = _find_max_column_widths(table) display_table(table, widths) This codebase achieves its design goals. I would be willing to delegate or accept maintenance tasks on it.
{ "domain": "codereview.stackexchange", "id": 44657, "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", "url": null }
c++, concurrency Title: Simple, fool-proof pattern to execute tasks in parallel Question: Assume I have a type task_info that stores the task-specific data needed to execute the task. A std::vector of those is built before executing any of the individual tasks; this build-up is done in single-thread fashion. Then the parallel task execution is set up. To control access to the mutable resource (e.g. the output streams), I need a mutex. #include <atomic> #include <thread> #include <mutex> #include <vector> class task_info{}; // fill the blanks void execute_task(task_info info, std::mutex& mutex); // fill the blanks void process_in_parallel( std::vector<task_info> task_infos, std::size_t threads_count = std::thread::hardware_concurrency() ) { // Never use more threads than there is work. threads_count = std::min(threads_count, task_infos.size()); std::atomic_size_t task_index{ 0 }; // Note: std::atomic_size_t task_index{} is UB! std::mutex mutex{}; // Every thread will do this. auto process = [&task_index, &task_infos, &mutex] { // The loop variable i indicates the next task to do on this thread. // Note: `fetch_add` is a post-increment, basically task_index++. for (std::size_t i; (i = task_index.fetch_add(1, std::memory_order_relaxed)) < task_infos.size(); ) { execute_task(task_infos[i], mutex); } }; std::vector<std::thread> threads(threads_count); // Set up the threads. for (auto& thread : threads) thread = std::thread{ process }; // Start the threads. for (auto& thread : threads) thread.join(); // Don’t forget to join the threads! }
{ "domain": "codereview.stackexchange", "id": 44658, "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++, concurrency", "url": null }
c++, concurrency What is std::memory_order_relaxed? That is a memory fence and it is concerned with the relations of changes to multiple atomic variables are visible to threads. As long as you have one atomic variable only, use std::memory_order_relaxed as it puts the least constraints on the optimizer. For that reason, do not ever use task_index++ because it does fetch_add(1, std::memory_order_seq_cst), i.e. it does what you want, but with a fence that puts unnecessary restrictions. How to use the mutex? The mutex is locked before the resource is accessed and unlocked as soon as the thread does not use the resource anymore. In simple cases, you use a std::lock_guard object to lock the mutex at its initialization and unlock the mutex at its destruction. void execute_task(task_info info, std::mutex& mutex) { // work ... { std::lock_guard<std::mutex> lock{ mutex }; std::cout << "Task " << info.id() << " done 50%" << std::endl; // lock_guard unlocks mutex at the closing brace } // work ... { std::lock_guard<std::mutex> lock{ mutex }; std::cout << "Task " << info.id() << " completed" << std::endl; } } If the little scopes are too noisy for a single line of code, one can use a comma expression: // work ... std::lock_guard<std::mutex>{ mutex }, std::cout << "Task " << info.id() << " done 50%" << std::endl; // work ... std::lock_guard<std::mutex>{ mutex }, std::cout << "Task " << info.id() << " completed" << std::endl;
{ "domain": "codereview.stackexchange", "id": 44658, "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++, concurrency", "url": null }