text
stringlengths
1
2.12k
source
dict
c#, programming-challenge Title: Advent of Code 2023 Day 2 in C# Question: To paraphrase the puzzle, Santa takes a walk with an Elf, and they play a game involving a bag of colorful cubes. In each game, there is an unknown number of each colored cubes in the bag, and the Elf pulls out a number of cubes, for example: Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green Part 1 In part 1, we want to know which games would have been possible if the bag contained only 12 red cubes, 13 green cubes, and 14 blue cubes. The answer is the sum of the eligible game ids, in the above example 1 + 2 + 5 = 8. Part 2 To paraphrase the change in part 2, for each game, we're looking for the maximum number of cubes per color that were drawn, multiply them together, and then sum this number for all games. With the example above this would be 48 + 12 + 1560 + 630 + 36 = 2286. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; string input = File.ReadAllText("day2.txt"); Console.WriteLine(GetSumOfInvalidIDs(input)); Console.WriteLine(GetCubeSetPower(input)); static int GetSumOfInvalidIDs(string input) { return input .Split("\r\n") .Sum(ProcessGamePart1); } static int GetCubeSetPower (string input) { return input .Split("\r\n") .Sum(ProcessGamePart2); } static int ProcessGamePart1(string game) { Dictionary<string, int> maxForColor = new() { {"red", 12}, {"green", 13}, {"blue", 14} };
{ "domain": "codereview.stackexchange", "id": 45300, "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#, programming-challenge", "url": null }
c#, programming-challenge foreach (string colorCount in GetColorCounts(game)) { var (numberOfBalls, color) = ParseColorCounts(colorCount.Trim()); if (numberOfBalls > maxForColor[color]) { return 0; } } return GetGameId(game); } static int ProcessGamePart2(string game) { Dictionary<string, int> maxSeenOfColor = new(); foreach (string colorCount in GetColorCounts(game)) { var (numberOfBalls, color) = ParseColorCounts(colorCount.Trim()); maxSeenOfColor.TryGetValue(color, out int currentMax); maxSeenOfColor[color] = Int32.Max(currentMax, numberOfBalls); } return maxSeenOfColor.Values.Aggregate(1, (currentPower, nextColor) => currentPower * nextColor); } static int GetGameId(string game) { return Int32.Parse(game.Split(" ")[1].TrimEnd(':')); } static string[] GetColorCounts(string game) { // Each color is given all at once for each handful, // so we only have to look at each count given. return game.Split(":")[1].Split(new char[] { ',', ';' }); } static (int, string) ParseColorCounts(string handful) { var parts = handful.Split(" "); int numberOfBalls = Int32.Parse(parts[0]); string color = parts[1]; return (numberOfBalls, color); } Review Request What could be improved upon? I am new to the language and am specifically interested in readability and idiomatic usage. Answer: Usings Keep the using directives tidy - System.Text and System.Threading.Tasks are not needed but System.IO is missing. Potential bug due to unclear input specifications The implementation will treat Game 1: 5 red, 10 red as a valid game. Which it isn't since there are only 12 red balls. It's not clear from the description if this is an expected input or not. If it's not a valid input then it should be rejected. Input processing
{ "domain": "codereview.stackexchange", "id": 45300, "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#, programming-challenge", "url": null }
c#, programming-challenge Hard-coded input file name. If you follow the Unix philosophy you'd be just reading from stdin and process the input as you go. This has the advantage that users have the flexibility to decide where the data is coming from. Split("\r\n") will fail on a Unix file since the line endings are \n there. File.ReadAllLines already does the work for you and also removes the need to split the input several times. Otherwise if you do end up needing to split lines yourself then Environment.NewLine exists. Overall you process and parse all input several times which is wasteful and also intermixes the parsing logic with the actual game logic. This makes it hard to read and will also make maintenance hard (in the real world you can usually bet that the input specs and/or the game logic will be changing as time goes on). The better way to do this would be to create a data structure representing the games, parse the input into this structure and the apply the game logic on the structure. This has several advantages: input is processed just once, different input formats or slight changes in input format can be easily supported without having to touch the game logic and you can separate input validation from game logic.
{ "domain": "codereview.stackexchange", "id": 45300, "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#, programming-challenge", "url": null }
c#, beginner, console Title: Best Practices For A Console Menu App Question: I am quite fresh to c# and creating programs. I wrote a very basic program which allows you to go through menu selections via up and down arrowkeys and select your selection along with sending you to a sub menu and back. I feel like it's kind of clunky and suspect there's definitely better practices to utilize but unsure of any really. For example, most of my classes have public methods but I hear that's bad practice, however I couldn't necessarily find a way around this? Here's the code below. Feel free to criticize it all! Keys to use would be up arrow, down arrow, and enter. ***Edit is because this was flagged as "code not working" Which I think is a mistake because I just copied and pasted everything here into visual studio and it ran just fine. I believe because I had a sentence saying "not working to what it's intended to do" was taken out of context as it was more so that the actual program isn't done not that it wont run...I wish there was a more specific reason as to why this was closed. It's just a simple code review. Program using System.IO; using System.Collections; using System.Collections.Generic; using System.Net; using System; namespace EmployeeAndClientDatabase { internal class Program { static void Main(string[] args) { Employee employee = new Employee(); Client client = new Client(); Menu menu = new Menu();
{ "domain": "codereview.stackexchange", "id": 45301, "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#, beginner, console", "url": null }
c#, beginner, console Console.WriteLine("Welcome to the FrontStar Worker & Client Database System"); Console.WriteLine(); Console.WriteLine("*********************************************************"); Console.WriteLine(@"* * * * * Press enter to continue. * * * * * ********************************************************"); Console.ReadLine(); Console.Clear(); menu.Start(client, employee); } } } IPerson interface IPerson { string NameFirst { get; set; } string NameLast { get; set; } string IdNumber { get; set; } string Month { get; set; } string Day { get; set; } string Year { get; set; } string Address { get; set; } int Social { get; set; } } Employee public class Employee : IPerson { List<Employee> employees = new List<Employee>(); public string NameFirst { get; set; } public string NameLast { get; set; } public string IdNumber { get; set; } public string Month { get; set; } public string Day { get; set; } public string Year { get; set; } public string Address { get; set; } public int Social { get; set; } public Employee() { } public Employee(string first, string last, string id, string month, string day, string year, string address, int social) { this.NameFirst = first; this.NameLast = last; this.IdNumber = "E:" + id; this.Month = month; this.Day = day; this.Year = year; this.Address = address; this.Social = social; } public void EmployeeMenu() { Console.WriteLine("Employee Sub-Menu"); Console.ReadLine(); Console.Clear(); } public void AddEmployee() { string first; string last; string id; string month; string day; string year; string address; int social;
{ "domain": "codereview.stackexchange", "id": 45301, "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#, beginner, console", "url": null }
c#, beginner, console Console.WriteLine("Test: adding employee"); Console.Write("name: "); first = Console.ReadLine(); Console.Write("Last: "); last = Console.ReadLine(); Console.Write("ID: "); id = Console.ReadLine(); Console.Write("DOB Month: "); month = Console.ReadLine(); Console.Write("DOB Day: "); day = Console.ReadLine(); Console.Write("DOB Year: "); year = Console.ReadLine(); Console.Write("Address: "); address = Console.ReadLine(); Console.Write("Social: "); social = Convert.ToInt32(Console.ReadLine()); employees.Add(new Employee(first, last, id, month, day, year, address, social)); } public void ViewEmployees() { string list; list = employees[0].ToString(); Console.WriteLine(list); } public override string ToString() { return $"First Name: {NameFirst}\nLast Name: {NameLast}\nID: {IdNumber} \nDate Of Birth: {Month} / {Day} / {Year} \nAddress: {Address} \nSocial Security: {Social} "; } } Client public class Client : IPerson { List<Client> clients = new List<Client>(); public string NameFirst { get; set; } public string NameLast { get; set; } public string IdNumber { get; set; } public string Month { get; set; } public string Day { get; set; } public string Year { get; set; } public string Address { get; set; } public int Social { get; set; } public Client(string first, string last, string id, string month, string day, string year, string address, int social) { this.NameFirst = first; this.NameLast = last; this.IdNumber = "C:" + id; this.Month = month; this.Day = day; this.Year = year; this.Address = address; this.Social = social; } public Client() {
{ "domain": "codereview.stackexchange", "id": 45301, "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#, beginner, console", "url": null }
c#, beginner, console } public Client() { } public void ClientMenu() { Console.WriteLine("Client Sub-Menu"); Console.ReadLine(); Console.Clear(); } public void AddClient() { string first; string last; string id; string month; string day; string year; string address; int social; Console.WriteLine("Test: adding Client"); Console.Write("name: "); first = Console.ReadLine(); Console.Write("Last: "); last = Console.ReadLine(); Console.Write("ID: "); id = Console.ReadLine(); Console.Write("DOB Month: "); month = Console.ReadLine(); Console.Write("DOB Day: "); day = Console.ReadLine(); Console.Write("DOB Year: "); year = Console.ReadLine(); Console.Write("Address: "); address = Console.ReadLine(); Console.Write("Social: "); social = Convert.ToInt32(Console.ReadLine()); clients.Add(new Client(first, last, id, month, day, year, address, social)); } } Menu public class Menu { public void Start(Client client, Employee employee) { bool exit = false; //string[] options = { "Employees Menu", "Clients Menu" }; int selectedOption = 0; ConsoleKey key; //ConsoleKeyInfo key = Console.ReadKey(); string marker = "*"; do { Console.WriteLine("*****+-: Main Menu :-+*****"); Console.WriteLine("___________________________"); Console.WriteLine(); Console.WriteLine("Please make a selection:"); Console.WriteLine(); Console.WriteLine($"{marker}Employee Menu"); Console.WriteLine($"Client Menu"); Console.WriteLine("Exit Program"); do { key = Console.ReadKey(true).Key;
{ "domain": "codereview.stackexchange", "id": 45301, "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#, beginner, console", "url": null }
c#, beginner, console do { key = Console.ReadKey(true).Key; if (key == ConsoleKey.DownArrow) { selectedOption++; } if(key == ConsoleKey.UpArrow) { selectedOption--; } if(key == ConsoleKey.Enter) { Console.Clear(); break; } if (selectedOption < 0 || selectedOption >= 3) { if (selectedOption < 0) { selectedOption = 2; } if (selectedOption >= 3) { selectedOption = 0; } } switch (selectedOption) { case 0: Console.Clear(); Console.WriteLine("*****+-: Main Menu :-+*****"); Console.WriteLine("___________________________"); Console.WriteLine(); Console.WriteLine("Please make a selection:"); Console.WriteLine(); Console.WriteLine($"{marker}Employee Menu"); Console.WriteLine($"Client Menu"); Console.WriteLine($"Exit Program"); break; case 1: Console.Clear(); Console.WriteLine("*****+-: Main Menu :-+*****"); Console.WriteLine("___________________________"); Console.WriteLine(); Console.WriteLine("Please make a selection:"); Console.WriteLine(); Console.WriteLine($"Employee Menu"); Console.WriteLine($"{marker}Client Menu"); Console.WriteLine($"Exit program"); break;
{ "domain": "codereview.stackexchange", "id": 45301, "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#, beginner, console", "url": null }
c#, beginner, console case 2: Console.Clear(); Console.WriteLine("*****+-: Main Menu :-+*****"); Console.WriteLine("___________________________"); Console.WriteLine(); Console.WriteLine("Please make a selection:"); Console.WriteLine(); Console.WriteLine($"Employee Menu"); Console.WriteLine($"Client Menu"); Console.WriteLine($"{marker}Exit Program"); break; } } while (key != ConsoleKey.Enter); switch(selectedOption) { case 1: client.ClientMenu(); break; case 0: employee.EmployeeMenu(); break; case 2: exit = true; break; } selectedOption = 0; } while (exit == false); } public int Exit() { return 0; } } Answer: The other answer focused on the data objects. This answer focuses on the menu. Menu printing Repetitive menu header If you look at your code you can easily spot that the menu header is copy-pasted many times: Console.WriteLine("*****+-: Main Menu :-+*****"); Console.WriteLine("___________________________"); Console.WriteLine(); Console.WriteLine("Please make a selection:"); Console.WriteLine(); You could extract this piece of code into a separate method and call it as many times as you need. Multi-line text In case of C# you can use multi-line text by using the @ before your string literal. So, the above menu header could be rewritten to this: Console.WriteLine( @"*****+-: Main Menu :-+***** ___________________________ Please make a selection ");
{ "domain": "codereview.stackexchange", "id": 45301, "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#, beginner, console", "url": null }
c#, beginner, console Please make a selection "); Repetitive selected menu If you look at your code you can easily spot that the selected menu highlighting is copy-pasted with a slight difference in each occasion Console.WriteLine($"{marker}Employee Menu"); Console.WriteLine($"Client Menu"); Console.WriteLine("Exit Program"); ... Console.WriteLine($"Employee Menu"); Console.WriteLine($"{marker}Client Menu"); Console.WriteLine($"Exit program"); ... A better option could be to define the menu items in a single place and whenever you print the menu items you highlight the selected one: private static void PrintMenu(List<MenuItem> items, MenuItem selectedItem) { Console.Clear(); Console.WriteLine( @"*****+-: Main Menu :-+***** ___________________________ Please make a selection "); foreach (var item in items) { Console.Write(item == selectedItem ? "* " : " "); Console.WriteLine(item.Name); } } MenuItem I would suggest to create a simple data structure to store the display name of the menu item and the to-be-executed action in case of selection. For older C# versions you can easily do that via struct: struct MenuItem { public string Name {get; set;} public Action Handler {get; set;} public static bool operator ==(MenuItem item1, MenuItem item2) => item1.Equals(item2); public static bool operator !=(MenuItem item1, MenuItem item2) => !item1.Equals(item2); } For newer C# versions you can use record: record MenuItem(string Name, Action Handler); Menu Items If you have defined the MenuItem as struct then the menu items can be defined like this: var menu = new List<MenuItem> { new() { Name = "Employee Menu", Handler = () => Console.WriteLine("employee")}, new() { Name = "Client Menu", Handler = () => Console.WriteLine("client")}, new() { Name = "Exit Program", Handler = () => Environment.Exit(0)}, };
{ "domain": "codereview.stackexchange", "id": 45301, "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#, beginner, console", "url": null }
c#, beginner, console if you have defined the MenuItem as record then: var menu = new List<MenuItem> { new("Employee Menu", () => Console.WriteLine("employee")), new("Client Menu", () => Console.WriteLine("client")), new("Exit Program", () => Environment.Exit(0)), }; I've used Console.WriteLine("xyz") for the sake of simplicity but you can easily wire here any arbitrary method call In case of Exit Program I've used Environment.Exit(0) to close the application immediately Handling key press The last remaining thing is to make the menu interactive. In your code you have two nested do-while loops. The good news is that you don't need both. The same behaviour can be achieved with a single one. int selectedOption = 0; int maxIndex = menu.Count-1; do { PrintMenu(menu, menu[selectedOption]); Action next = Console.ReadKey().Key switch { ConsoleKey.DownArrow => () => { selectedOption = selectedOption == maxIndex ? 0 : selectedOption + 1; }, ConsoleKey.UpArrow => () => { selectedOption = selectedOption == 0 ? maxIndex : selectedOption - 1; }, ConsoleKey.Enter => () => { Console.Clear(); menu[selectedOption].Handler(); Console.ReadLine(); } }; next(); } while (true); DownArrow If the selected item is the last menu item then move to the first one otherwise move to the next one UpArrow If the selected item is the first menu item then move to the last one otherwise move to the previous one Enter Clear the screen Execute the menu item's Handler method Wait for any key press to move back to the main menu
{ "domain": "codereview.stackexchange", "id": 45301, "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#, beginner, console", "url": null }
c#, beginner, console You can replace the Console.ReadLine() to any arbitrary logic, like checking for Esc key next() This executes the method related to the associated key press. If you don't want to use switch expression then you can convert the logic back to simple if-else if statements: do { PrintMenu(menu, menu[selectedOption]); var key = Console.ReadKey().Key; if(key == ConsoleKey.DownArrow) { selectedOption = selectedOption == maxIndex ? 0 : selectedOption + 1; } else if(key == ConsoleKey.UpArrow) { selectedOption = selectedOption == 0 ? maxIndex : selectedOption - 1; } else if(key == ConsoleKey.Enter) { Console.Clear(); menu[selectedOption].Handler(); Console.ReadLine(); } } while (true); For the sake of completeness here is the complete code record MenuItem(string Name, Action Handler); public static class Menu { public static void Start() { var menu = new List<MenuItem> { new("Employee Menu", () => Console.WriteLine("employee")), new("Client Menu", () => Console.WriteLine("client")), new("Exit Program", () => Environment.Exit(0)), }; int selectedOption = 0; int maxIndex = menu.Count-1; do { PrintMenu(menu, menu[selectedOption]); Action next = Console.ReadKey().Key switch { ConsoleKey.DownArrow => () => selectedOption = selectedOption == maxIndex ? 0 : selectedOption +1, ConsoleKey.UpArrow => () => selectedOption = selectedOption == 0 ? maxIndex : selectedOption -1, ConsoleKey.Enter => () => { Console.Clear(); menu[selectedOption].Handler(); Console.ReadLine(); } }; next(); } while (true); }
{ "domain": "codereview.stackexchange", "id": 45301, "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#, beginner, console", "url": null }
c#, beginner, console } while (true); } private static void PrintMenu(List<MenuItem> items, MenuItem selectedItem) { Console.Clear(); Console.WriteLine( @"*****+-: Main Menu :-+***** ___________________________ Please make a selection "); foreach (var item in items) { Console.Write(item == selectedItem ? "* " : " "); Console.WriteLine(item.Name); } } }
{ "domain": "codereview.stackexchange", "id": 45301, "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#, beginner, console", "url": null }
python, programming-challenge, string-processing Title: Advent of Code 2023 - Day 4: Scratchcards Question: Part 1: The task involves determining the total points of a set of scratchcards. Each scratchcard contains two lists of numbers: the winning numbers and the numbers the player has. Points are awarded based on matches with the winning numbers, with the first match earning 1 point and each subsequent match doubling the point value. The goal is to calculate the total points for all scratchcards in a given input. The Elf leads you over to the pile of colorful cards. There, you discover dozens of scratchcards, all with their opaque covering already scratched off. Picking one up, it looks like each card has two lists of numbers separated by a vertical bar (|): a list of winning numbers and then a list of numbers you have. You organize the information into a table (your puzzle input). As far as the Elf has been able to figure out, you have to figure out which of the numbers you have appear in the list of winning numbers. The first match makes the card worth one point and each match after the first doubles the point value of that card. For example: Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53 Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19 Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1 Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83 Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36 Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11 In the above example: Card 1 has four winning numbers (48, 83, 86, and 17), so it is worth 8 points (1 for the first match, then doubled three times for each of the three matches after the first). Card 2 has two winning numbers (32 and 61), so it is worth 2 points. Card 3 has two winning numbers (1 and 21), so it is worth 2 points. Card 4 has one winning number (84), so it is worth 1 point. Card 5 has no winning numbers, so it is worth no points. Card 6 has no winning numbers, so it is worth no points.
{ "domain": "codereview.stackexchange", "id": 45302, "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, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing So, in this example, the Elf's pile of scratchcards is worth 13 points. #!/usr/bin/env python3 import re from pathlib import Path from typing import Iterable import typer def calculate_points(old: list, new: list) -> int: count = 0 for num in new: if num in old: count = 1 if count == 0 else count * 2 return count def card_points(line: str) -> int: # Card X: w1, w2, w3, .... | p1, p2, p3, .... pattern = r"((\d+\s+)+)|\s((\d+\s+)+)" groups = [x.group() for x in re.finditer(pattern, line)] winning, ours = [list(map(int, group.split())) for group in groups] return calculate_points(winning, ours) def total_points(lines: Iterable[str]) -> int: return sum(map(card_points, lines)) def main(scratchcards_file: Path) -> None: with open(scratchcards_file, "r") as f: print(total_points(f)) if __name__ == "__main__": typer.run(main) Part 2: The second part involves scratchcards where matching numbers result in winning additional copies of subsequent cards, creating a chain of winnings. The goal is to determine the total number of scratchcards, including both the original set and all copies won. This time, the above example goes differently: Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53 Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19 Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1 Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83 Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36 Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11
{ "domain": "codereview.stackexchange", "id": 45302, "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, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing Card 1 wins one copy each of the next four cards: cards 2, 3, 4, and 5. Original card 2 wins one copy each of cards 3 and 4. Copy of card 2 also wins one copy each of cards 3 and 4. Four instances of card 3 (one original and three copies) win four copies each of cards 4 and 5. Eight instances of card 4 (one original and seven copies) win eight copies of card 5. Fourteen instances of card 5 (one original and thirteen copies) have no matching numbers and win no more cards. One instance of card 6 (one original) has no matching numbers and wins no more cards. The result is 1 instance of card 1, 2 instances of card 2, 4 instances of card 3, 8 instances of card 4, 14 instances of card 5, and 1 instance of card 6. The total number of scratchcards at the end of this process is 30. #!/usr/bin/env python3 import re from pathlib import Path from typing import Iterable import typer def count_cards(line: str) -> int: # Card X: w1, w2, w3, .... | p1, p2, p3, .... pattern = r"((\d+\s+)+)|\s((\d+\s+)+)" groups = [x.group() for x in re.finditer(pattern, line)] winning, ours = [list(map(int, group.split())) for group in groups] return sum(1 for num in ours if num in winning) def total_cards(scratchcards: Iterable[str]) -> int: card_counts = {} line_idx = 1 total = 0 for card in scratchcards: card_counts[line_idx] = card_counts.get(line_idx, 0) + 1 matching = count_cards(card) for _ in range(card_counts[line_idx]): for i in range(line_idx + 1, line_idx + matching + 1): card_counts[i] = card_counts.get(i, 0) + 1 total += card_counts[line_idx] line_idx += 1 return total def main(scratchcards_file: Path) -> None: with open(scratchcards_file, "r") as f: print(total_cards(f)) if __name__ == "__main__": typer.run(main)
{ "domain": "codereview.stackexchange", "id": 45302, "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, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing if __name__ == "__main__": typer.run(main) Review Request: General coding comments, style, etc. Today, I learned that the default mode for the open() function is read, and the second argument is optional. What is the convention regarding specifying the mode? Is the regex robust? What are some possible simplifications? What would you do differently? Answer: Docstrings None of your functions are documented, while you have type annotations (which is great) they don't describe what the function is intended to do or how beyond the name. Docstrings can be added to functions simply by making the first line of the function a string: def double(x: int) -> int: """Doubles the integer x""" return 2*x and then can be read by calling help(double) Internal comments can also be helpful to describe what a block of code is meant to be doing. But commenting is somewhat of a dark art and everyone has a different way of doing it and expectations. Nonetheless the total lack of comments besides a slightly misleading pattern (as already highlighted) is probably not sufficient. REs REs are somewhat costly and in this case, I would say use split as suggested by J_H. However, you have capturing groups where the capturing group is not used. If the group is not used later it can be best to mark it as non-capturing. pattern = r"(?:re)" This means it does not get added to the groups. In your case, you use none of the captures and an unexpected alternation, which I believe you may have intended to be a literal |, in which case you need to escape it. pattern = r"(?:\d+\s+)+\|\s+(?:\d+\s+)+" In the case of parsing this, however, I would probably go for: # Could make "game_id" `_` since it's unused, # but we may have wanted it in part 2 and this # makes the code more flexible. game_id, numbers = line.split(":") ours, winning = numbers.split("|") ours = [int(x) for x in ours.split()] winning = [int(x) for x in winning.split()]
{ "domain": "codereview.stackexchange", "id": 45302, "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, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing or if you wanted to have it in fewer lines: ours, winning = ([int(x) for x in nums] for nums in numbers.split("|")) or equivalently as a set ours, winning = ({int(x) for x in nums} for nums in numbers.split("|")) Enumerate When you are looping over each game in part 2, you manually track the line_idx which is not really necessary. This is such a common operation Python has a built-in for it: card_counts = {} line_idx = 1 total = 0 for card in scratchcards: card_counts[line_idx] = card_counts.get(line_idx, 0) + 1 matching = count_cards(card) for _ in range(card_counts[line_idx]): for i in range(line_idx + 1, line_idx + matching + 1): card_counts[i] = card_counts.get(i, 0) + 1 total += card_counts[line_idx] line_idx += 1 becomes card_counts = {} total = 0 for line_idx, card in enumerate(scratchcards, 1): card_counts[line_idx] = card_counts.get(line_idx, 0) + 1 matching = count_cards(card) for _ in range(card_counts[line_idx]): for i in range(line_idx + 1, line_idx + matching + 1): card_counts[i] = card_counts.get(i, 0) + 1 total += card_counts[line_idx] where enumerate returns a tuple of (index, value) for an iterable. The 1 says start counting from 1 (default is 0). Calculating points Sometimes with these sorts of puzzles it's a good trick to think about what the maths is telling you rather than simply coding the naive solution (it becomes essential in many problems, in particular AoC is set up so that the part 1 can be easily brute-forced, while part 2 is impossible to solve in any real time without using some tricks). In our case, the points are essentially floor(2**(count - 1)) e.g. count pts reason 0 0 (2^-1 = 0.5 which floors to 0) 1 1 (2^0 = 1) 2 2 (2^1 = 2) 5 16 (2^4 = 16)
{ "domain": "codereview.stackexchange", "id": 45302, "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, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing 0 0 (2^-1 = 0.5 which floors to 0) 1 1 (2^0 = 1) 2 2 (2^1 = 2) 5 16 (2^4 = 16) That means that all we need is the count. If we were using lists as you are: def calculate_points(old: list, new: list) -> int: count = sum(1 for num in new if num in old) return floor(2**(count - 1)) # OR return 2**(count - 1) if count else 0 Or if we were using sets def calculate_points(old: set, new: set) -> int: count = len(old & new) return floor(2**(count - 1)) # OR return 2**(count - 1) if count else 0 Overall Structure For reusability of functions, I would probably: change calculate_points to just return the count which means we can use this again in part 2 rather than packing everything into card_points I would make card_points into parse_round and return winning & ours as a tuple from the function. This means that rather than having to duplicate everything in part 2 we already have the tools we need. It also (to me) divides the code into more concrete stages: parse file get winners score winners - Only different part between 1 & 2 compute total
{ "domain": "codereview.stackexchange", "id": 45302, "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, programming-challenge, string-processing", "url": null }
c, enum, macros Title: Macro to generate an enum and an array of strings Question: Often when I find myself working with magic number enum values and I want to know what they represent, so I create an array of strings in order to print out their label. This macro automates that process. //#define DEBUG #define GENERATE_ENUM(ENUM) ENUM, #define GENERATE_STRING(STRING) #STRING, #define GENERATE_ENUM_LIST(MACRO, NAME) \ enum NAME \ { \ MACRO(GENERATE_ENUM) \ }; //#ifdef DEBUG #define GENERATE_ENUM_STRING_NAMES(MACRO, NAME) \ const char *NAME##_Strings[] = { \ MACRO(GENERATE_STRING) \ }; //#else //#define GENERATE_ENUM_STRING_NAMES(MACRO, NAME) //#endif To use do: #include <stdio.h> /* ~ The macro ~ */ #define macro_handler(T) \ T(ZERO) \ T(ONE) \ T(TWO) GENERATE_ENUM_STRING_NAMES(macro_handler, nuclearLaunchCodesData) GENERATE_ENUM_LIST(macro_handler, nuclearLaunchCodesData) #undef macro_handler int main() { printf("%s\n", nuclearLaunchCodesData_Strings[ZERO]); } Answer: Most macro solutions are not readable nor maintainable. You should avoid macro solutions like this. The best way is to not use macros at all: typedef enum { ZERO, ONE, TWO, THREE, NUMBERS_N } numbers_t; static const char* NUMBER_STR[NUMBERS_N] = { [ZERO] = "ZERO", [ONE] = "ONE", [TWO] = "TWO", [THREE] = "THREE", }; puts(NUMBER_STR[1]); // prints ONE
{ "domain": "codereview.stackexchange", "id": 45303, "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, enum, macros", "url": null }
c, enum, macros puts(NUMBER_STR[1]); // prints ONE This code is perfectly readable and it maintains the integrity between the enum and the array well. It only has one small problem and that is code repetition. Code repetition should be avoided, but programmers tend to exaggerate how bad it is. It is rarely ever so bad that it justifies turning your whole program into "macro hell". The reasons why code repetition should be avoided is that is leads to typo-like bugs and problems with maintenance. However, while a "macro hell" solution might rule out the typos, it makes the code difficult to maintain and the increased complexity increases the chance of other more serious bugs. Famous quote by Brian Kernighan: Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it? That being said, there are valid cases where you must centralize data in one place, particularly when maintaining existing code that shouldn't be changed more than necessary. The macro you posted is a flavour of "X macros", which is the preferable way to write such macros - "messy in a standardized way" so to speak. X macros is about defining a list of data as you do, but to pass on that data to localized macros embedded into the code itself. To rewrite the above code with X macros, you'd do: #define NUMBER_LIST \ X(ZERO) \ X(ONE) \ X(TWO) \ X(THREE) \ typedef enum { #define X(name) name, NUMBER_LIST #undef X NUMBERS_N } numbers_t; static const char* NUMBER_STR[NUMBERS_N] = { #define X(name) [name] = #name, NUMBER_LIST #undef X }; puts(NUMBER_STR[1]); // prints ONE
{ "domain": "codereview.stackexchange", "id": 45303, "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, enum, macros", "url": null }
c, enum, macros puts(NUMBER_STR[1]); // prints ONE The advantage here is the flexibility to apply the same data in different ways, on case-by-case basis. A macro such as #define X(name) [name] = #name, is cryptic by itself, but when given the context of the surrounding array initializer list, one can easier understand the meaning. "X macros" can also be used to manually unroll loops: #define X(name) puts(NUMBER_STR[name]); NUMBER_LIST #undef X This is equivalent to iterating over the array and printing all items, but the loop is unrolled and we end up with a number of puts calls.
{ "domain": "codereview.stackexchange", "id": 45303, "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, enum, macros", "url": null }
c, vectors Title: Dynamic array of int in C Question: This is my first C program I just wrote in like 30 minutes and I was wondering if you could give me any pointers on ways to improve this. I'm decent at programming (around 5 years experience), but have no experience with C so I imagine I'm not following the proper idioms and/or doing things properly. Note: I didn't make it "generic", because learning templates was beyond the scope of this little adventure. #include <assert.h> #include <stddef.h> #include <stdlib.h> #include <string.h> /** A dynamically sized array of `int` */ typedef struct { size_t capacity; size_t length; int *data; } DynamicArray; /** Appends `value` to the `DynamicArray` */ void dynamic_array_push(DynamicArray *arr, int value) { if (arr->length == arr->capacity) { int *new_data = malloc(arr->capacity * 2 * sizeof(int)); memcpy(new_data, arr->data, arr->capacity * sizeof(int)); free(arr->data); arr->data = new_data; arr->capacity *= 2; } arr->data[arr->length] = value; arr->length++; } /** Cleans up the `DynamicArray`. */ void dynamic_array_cleanup(DynamicArray *arr) { free(arr->data); } DynamicArray dynamic_array_new(size_t cap) { DynamicArray arr = { .capacity = cap, .length = 0, .data = malloc(cap * sizeof(int)), }; return arr; } int main() { DynamicArray arr = dynamic_array_new(2); // Putting in some test values for (int i = 0; i < 30; i++) { dynamic_array_push(&arr, i); } // Testing that the data came in correctly for (int i = 0; i < arr.length; i++) { assert(i == arr.data[i]); } dynamic_array_cleanup(&arr); return 0; }
{ "domain": "codereview.stackexchange", "id": 45304, "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, vectors", "url": null }
c, vectors dynamic_array_cleanup(&arr); return 0; } Answer: Thank you for the very nice Doxygen comment. Consider renaming the struct to DynamicIntArray, and then I won't even have to read the comment. Or perhaps in the use case you're tackling, there is a concept in the business domain, such as Widget, that can be represented as an int. Then we'd have a DynamicWidgetArray. magic number Some code bases, such as BIND9, choose to start (some of) their structs with a distinct magic number. This is a debugging aid, so library code can choose to assert that an object of the expected type was passed in. It's completely optional, but you might consider adopting such a practice. It tends to make debugging with gdb a bit easier. libc function reimplemented int *new_data = malloc(arr->capacity * 2 * sizeof(int)); memcpy(new_data, arr->data, arr->capacity * sizeof(int)); free(arr->data); arr->data = new_data;
{ "domain": "codereview.stackexchange", "id": 45304, "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, vectors", "url": null }
c, vectors This is duplicating the functionality of a realloc() call. For the Author's sake, may as well just reuse a well -tested, -documented function. For the Gentle Reader's sake, write a single line instead of several, using a familiar contract. cleanup In dynamic_array_cleanup the free() is very nice. Consider additionally zeroing out those three fields, so we don't have a dangling pointer that tempts some application to try a use-after-free blunder. Certainly it is accurate that length and capacity are zero after the free(). Or write 0xDeadBeef into them, for the benefit of someone examining memory with gdb. public API You have defined a Public API that is broken -- it is not fit for purpose. Sometimes malloc() returns NULL. I know, it's sad. But it's a fact of life. One which a library author must cope with. And C doesn't offer error reporting via exceptions. Each time you make a call, your code must verify that malloc() succeeded. You should either document that malloc fail will tear down the calling process, or you should return its status to the caller, so now it is the caller's problem to decide what to do. mulitply by zero If caller fails to supply new() with a positive number then Bad Things can happen. Recycling an old struct after free() can also run afoul of this. @MatthieuM. observes that the growth function does not work with cap == 0, because 0 * 2 == 0. max(cap * 2, 1) will work. Even cap * 2 + 1 would suffice.
{ "domain": "codereview.stackexchange", "id": 45304, "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, vectors", "url": null }
rust, generics, circular-list Title: Ringbuffer over a const generic Array in Rust Question: I implemented this generic ringbuffer over a const generic array with the usage of the MaybeUninit type. Is there something which is maybe unsound (having the lines with drop_in_place in mind) or which could be optimized? Thanks in advance #![feature(inline_const)] use core::mem::MaybeUninit; use core::ptr; struct Ringbuffer<T, const N: usize> { buffer: [MaybeUninit<T>; N], read: usize, write: usize, size: usize } impl <T, const N: usize> Ringbuffer<T, N> { pub const fn new() -> Self { Self { buffer: [const { MaybeUninit::<T>::zeroed() }; N], read: 0, write: 0, size: 0, } } pub fn push(&mut self, value: T) { if N == 0 { return; } if self.size >= N { unsafe { ptr::drop_in_place(self.buffer[self.write].as_mut_ptr()); } self.buffer[self.write].write(value); self.wrap_inc_write(); } else { self.buffer[self.write].write(value); self.wrap_inc_write(); self.inc_size(); } } pub fn pop(&mut self) -> Option<T> { if N == 0 { return None; } if self.is_empty() { return None; } let ret = unsafe { self.buffer[self.read].assume_init_read() }; self.wrap_inc_read(); self.dec_size(); Some(ret) } pub fn skip(&mut self) { if N == 0 { return; } if self.is_empty() { return; } unsafe { ptr::drop_in_place(self.buffer[self.read].as_mut_ptr()); } self.wrap_inc_read(); self.dec_size(); }
{ "domain": "codereview.stackexchange", "id": 45305, "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": "rust, generics, circular-list", "url": null }
rust, generics, circular-list pub fn peek(&mut self) -> Option<&T> { if N == 0 { return None; } if self.is_empty() { return None; } let ret = unsafe { self.buffer[self.read].assume_init_ref() }; Some(ret) } pub fn size(&self) -> usize { self.size } pub fn capacity(&self) -> usize { N } pub fn is_empty(&self) -> bool { self.size == 0 } pub fn is_full(&self) -> bool { self.size == N } fn wrap_inc_read(&mut self) { self.read = (self.read + 1) % N; } fn wrap_inc_write(&mut self) { self.write = (self.write + 1) % N; } fn inc_size(&mut self) { self.size += 1; } fn dec_size(&mut self) { self.size -= 1; } } Answer: Your code looks perfectly sound to me after looking through docs and the code. Nothing to add, but there is one more way for implementing your push, one that may be effectively the same or slower, though still using some unsafe: if self.size >= N { unsafe { mem::replace(&mut self.buffer[self.write], MaybeUninit::new(value)).assume_init(); } self.wrap_inc_write(); } All you need to know is how MaybeUninit works, and this: https://doc.rust-lang.org/core/ptr/fn.drop_in_place.html#safety
{ "domain": "codereview.stackexchange", "id": 45305, "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": "rust, generics, circular-list", "url": null }
c, linux, windows Title: A print function which works with /NODEFAULTLIB Question: #include <stdint.h> #include <stdarg.h> #include <stddef.h> #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> HANDLE inHandle = INVALID_HANDLE_VALUE; HANDLE outHandle = INVALID_HANDLE_VALUE; #else #include <unistd.h> #endif int stdoutFunction(const char* buffer, size_t bufferSize) { #ifdef _WIN32 int bytesWritten = 0; WriteConsoleA(outHandle, buffer, bufferSize, &bytesWritten, NULL); return bytesWritten; #else return write(1, buffer, bufferSize); #endif } size_t copyAscii(char* buffer, const char* src, size_t charSize, size_t bufferIdx, const size_t maxBufferIdx) { for (; *src != '\0'; src += charSize) { buffer[bufferIdx] = *src; bufferIdx += (bufferIdx < maxBufferIdx); } return bufferIdx; } size_t intToHexStr(char* buffer, const size_t n, size_t bufferIdx, const size_t maxBufferIdx) { const char hexCharacters[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; for (int32_t shiftRightBy = (sizeof(size_t) * 8) - 4; shiftRightBy >= 0; shiftRightBy -= 4) { buffer[bufferIdx] = hexCharacters[(n >> shiftRightBy) % 16]; bufferIdx += (bufferIdx < maxBufferIdx); } return bufferIdx; } size_t intToStr(char* buffer, size_t n, size_t bufferIdx, const size_t maxBufferIdx) { size_t frontIdx = bufferIdx; do { buffer[bufferIdx] = '0' + (n % 10); bufferIdx += (bufferIdx < maxBufferIdx); n /= 10; } while (n > 0); size_t backIdx = bufferIdx - 1; while (frontIdx < backIdx) { char tmp = buffer[frontIdx]; buffer[frontIdx] = buffer[backIdx]; buffer[backIdx] = tmp; frontIdx += 1; backIdx -= 1; } return bufferIdx; } // working format specifiers: s, ls, d, u, zu, x, % int dumberPrintf(const char* fmt, ...) { if (fmt[0] == '\0') { return 0; }
{ "domain": "codereview.stackexchange", "id": 45306, "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, linux, windows", "url": null }
c, linux, windows char buffer[512]; size_t bufferIdx = 0; size_t maxBufferIdx = sizeof(buffer) - 1; va_list args; va_start(args, fmt); for (size_t fmtIdx = 0; fmt[fmtIdx] != '\0'; fmtIdx++) { if (fmt[fmtIdx] == '%') { if ( fmt[fmtIdx + 1] == 's' || (fmt[fmtIdx + 1] == 'l' && fmt[fmtIdx + 2] == 's') ) { bufferIdx = copyAscii( buffer, fmt[fmtIdx + 1] == 's' ? va_arg(args, char*) : (char*)va_arg(args, wchar_t*), fmt[fmtIdx + 1] == 's' ? sizeof(char) : sizeof(wchar_t), bufferIdx, maxBufferIdx ); fmtIdx += (fmt[fmtIdx + 1] == 'l'); } else if ( fmt[fmtIdx + 1] == 'd' || fmt[fmtIdx + 1] == 'u' || (fmt[fmtIdx + 1] == 'z' && fmt[fmtIdx + 2] == 'u') ) { bufferIdx = intToStr(buffer, va_arg(args, size_t), bufferIdx, maxBufferIdx); fmtIdx += (fmt[fmtIdx + 1] == 'z'); } else if (fmt[fmtIdx + 1] == 'x') { bufferIdx = intToHexStr(buffer, va_arg(args, size_t), bufferIdx, maxBufferIdx); } else { buffer[bufferIdx] = '%'; bufferIdx += (bufferIdx < maxBufferIdx); } fmtIdx += 1; } else { buffer[bufferIdx] = fmt[fmtIdx]; bufferIdx += (bufferIdx < maxBufferIdx); } } va_end(args); return stdoutFunction(buffer, bufferIdx); } int main() { #ifdef _WIN32 inHandle = GetStdHandle(STD_INPUT_HANDLE); outHandle = GetStdHandle(STD_OUTPUT_HANDLE); if (inHandle == INVALID_HANDLE_VALUE || outHandle == INVALID_HANDLE_VALUE) { return GetLastError(); } #endif
{ "domain": "codereview.stackexchange", "id": 45306, "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, linux, windows", "url": null }
c, linux, windows dumberPrintf("%%s test: %s\n%%ls test: %ls\n%%d test: %d\n%%u test: %u\n%%zu test: %zu\n%%x test: %x\n", "char string", L"wchar_t string", 12345, 54321, 56789, 0xabcdef ); return 0; } /* int __stdcall mainCRTStartup() { int result = main(); return result; } */ I'm making something which I'm going to update to not use any C runtime functions, including printf. I'm going to compile with /NODEFAULTLIB. I made this function to imitate printf. It works with the format specifiers s, ls, d, u, zu, x, and %. It's not expected to print any negative numbers. It's also not expected to print anything longer than 512 bytes, so it cuts off anything beyond that length. Answer: Use the standard library There is no reason to use /NODEFAULTLIB` Use printf instead of rolling your solution. But since you are probably removing the standard library. Here you go. write does not promise that all bytes will be written. If the kernel buffers are smaller than the number of bytes to be written it will only write a few bytes. You have to address that in your stdoutFunction. You might want to create two different definitions for Windows and Linux and then choose which one to use based on a macro, instead of using macros in the same function. It makes the code easier to read. But that is just my style. People may differ. When writing parsing code, don't loop over the parse string character by character. Instead, think in terms of tokens. You can break your problem into tokenizing the format string and doing the correct stuff in a switch statement based on the toke. Like below. It is much more clear than mixing wchar_t and char strings. It also leads to fewer bugs because you are focusing on printing a single in each case statement.
{ "domain": "codereview.stackexchange", "id": 45306, "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, linux, windows", "url": null }
c, linux, windows typedef enum { ConversionType_StringLiteral = 0, ConversionType_String, ConversionType_WideString, //... ConversionType_MAX } ConversionType; typedef struct ConversionSpecification { ConversionType type; size_t length; size_t precision; }ConversionSpecification; ConversionSpecification getFormatSpecification(const char* fmt){ } int dumberPrintf(const char* fmt, ...) { va_list args; va_start(args, fmt); size_t bytesWritten = 0; while(*fmt){ ConversionSpecification spec = getFormatSpecification(fmt); if(spec.type >= ConversionType_MAX){ return -1; } switch(spec.type){ case ConversionType_StringLiteral: { // Do string literal stuff } case ConversionType_String: { // Do string stuff } case ConversionType_WideString: { // Do wide string stuff stuff } default: } fmt += spec.length;` } va_end(args); return bytesWritten; }
{ "domain": "codereview.stackexchange", "id": 45306, "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, linux, windows", "url": null }
javascript, html5 Title: programmatically update a element per table row Question: A table that gets updated with new values as soon as they arrive. Each value is in its own row: An array of objects representing each a quote (ticker and price) let array_of_quotes = [ { ticker: "AAPL", price: 999 }, { ticker: "AMZN", price: 957 }, { ticker: "GOOG", price: 959 }, { ticker: "YHOO", price: 225 }, { ticker: "MSFT", price: 514 }, { ticker: "AAPL", price: 218 }, { ticker: "AMZN", price: 256 }, { ticker: "AAPL", price: 526 }, { ticker: "AMZN", price: 288 }, { ticker: "MSFT", price: 514 }, { ticker: "AMZN", price: 909 }, { ticker: "YHOO", price: 225 }, ]; A counter that keeps track of the current row to be updated let counter = 0; A function that updates the row, it gets the body by its id, then adds a row with the current count as its id. In said row, 4 table datas <td> are added with the ticker and current count as id so that, the function only has to get that <td> element and injects the price in its inner text leaving the other <td>s untouched let table_s_body = document.getElementById("quote_table_body"); function table_row_updater(ticker_price) { table_s_body.innerHTML += `<tr id=row-${counter}></tr>`; let current_row = document.getElementById(`row-${counter}`); current_row.innerHTML += `<td id=AAPL-${counter}></td>`; current_row.innerHTML += `<td id=MSFT-${counter}></td>`; current_row.innerHTML += `<td id=AMZN-${counter}></td>`; current_row.innerHTML += `<td id=GOOG-${counter}></td>`; current_row.innerHTML += `<td id=YHOO-${counter}></td>`; let td_to_be_updated = document.getElementById( `${ticker_price.ticker}-${counter}` ); td_to_be_updated.innerText = ticker_price.price; counter += 1; }
{ "domain": "codereview.stackexchange", "id": 45307, "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, html5", "url": null }
javascript, html5 of course, the counter gets incremented so that the next iteration starts a new. For this demo purpose, i paced the "injection" of prices into their relative row's so it is less confusing. array_of_quotes.forEach((quote, index) => { setTimeout(() => { table_row_updater(quote); }, (index + 1) * 1000); }); What I would like to take out of your answers: Is this solution clean? I feel it's a bit dirty to rely on a counter. Couldn't the counter be achieved with a closure? If so, would anyone show me how? How would you go about updating a single out of multiple ones in a table with an ever growing number of rows. let array_of_quotes = [ { ticker: "AAPL", price: 999 }, { ticker: "AMZN", price: 957 }, { ticker: "GOOG", price: 959 }, { ticker: "YHOO", price: 225 }, { ticker: "MSFT", price: 514 }, { ticker: "AAPL", price: 218 }, { ticker: "AMZN", price: 256 }, { ticker: "AAPL", price: 526 }, { ticker: "AMZN", price: 288 }, { ticker: "MSFT", price: 514 }, { ticker: "AMZN", price: 909 }, { ticker: "YHOO", price: 225 }, ]; let counter = 0; let table_s_body = document.getElementById("quote_table_body"); function table_row_updater(ticker_price) { table_s_body.innerHTML += `<tr id=row-${counter}></tr>`; let current_row = document.getElementById(`row-${counter}`); current_row.innerHTML += `<td id=AAPL-${counter}></td>`; current_row.innerHTML += `<td id=MSFT-${counter}></td>`; current_row.innerHTML += `<td id=AMZN-${counter}></td>`; current_row.innerHTML += `<td id=GOOG-${counter}></td>`; current_row.innerHTML += `<td id=YHOO-${counter}></td>`; let td_to_be_updated = document.getElementById( `${ticker_price.ticker}-${counter}` ); td_to_be_updated.innerText = ticker_price.price; counter += 1; }
{ "domain": "codereview.stackexchange", "id": 45307, "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, html5", "url": null }
javascript, html5 array_of_quotes.forEach((quote, index) => { setTimeout(() => { table_row_updater(quote); }, (index + 1) * 1000); }); <table> <thead> <tr> <th>AAPL</th> <th>MSFT</th> <th>AMZN</th> <th>GOOG</th> <th>YHOO</th> </tr> </thead> <tbody id="quote_table_body"></tbody> </table>
{ "domain": "codereview.stackexchange", "id": 45307, "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, html5", "url": null }
javascript, html5 Answer: Is this solution clean? I feel it's a bit dirty to rely on a counter. Couldn't the counter be achieved with a closure? If so, would anyone show me how? You don't need a counter at all. If you want to use a counter then you don't need an extra variable and iterate it by yourself. First, if you iterate a counter then don't do it your way counter += 1 do it the easy way counter++. However, as said, you don't need a counter and if you want one you could simply use your index from your forEach iteration array_of_quotes.forEach((quote, index) => { ... }), which is exactly this by default. The first issue I have with your code is the usage of element.innerHTML += {HTML Code} which is an unclean method that should never be done. Unfortunately, it is still taught in schools, tutorials, and so on. Despite the fact that it is unclean, it is also comparably "slow" and can pose security issues such as XSS injections. The "only really correct way" to add elements to the DOM is by using the createElement method. Create an element and then append it to the DOM! The next issue I have is the missing abstraction from your table. Your JS code always assumes and relies on, that your table has only 5 columns with that exact name. If a column name changes or another column is added your JS would stop working correctly. An update would have to be done both in the JS and the HTML code which adds maintenance load and effort as well as adding error possibilities. For that, I wrote you a little function that reads out how many columns you have and how they are named. They push those names to an array and with that I can keep the JS on its own up to date with the HTML table: function getColumns() { let columns_array = []; THEAD_COLS.forEach(col => { columns_array.push(col.textContent); }) return columns_array; }
{ "domain": "codereview.stackexchange", "id": 45307, "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, html5", "url": null }
javascript, html5 With that array, I can simply iterate through that array while creating a new road and read cells for every existing column and do not have to hard code every single cell: COLUMNS.forEach(cell => { const CELL = document.createElement('td'); ROW.appendChild(CELL); }) The last real issue I have is to add an ID to every single cell. Rather then doing that use the tool that you have for such purpose: data-attribtues! How would you go about updating a single out of multiple ones in a table with an ever growing number of rows? First to add more data later on that is not covered by the array, you can write a simple function to read out the last used index and then execute your existing function while sending a new dataset and the last used index + 1; If you want to update an existing row, you need to know the index of the row that needs to be updated. Then you can call that row by searching for the data-row attribute. Eg. the first row you get by using document.querySelector('tr[data-row="0"]') let array_of_quotes = [ { ticker: "AAPL", price: 999 }, { ticker: "AMZN", price: 957 }, { ticker: "GOOG", price: 959 }, { ticker: "YHOO", price: 225 }, { ticker: "MSFT", price: 514 }, { ticker: "AAPL", price: 218 }, { ticker: "AMZN", price: 256 }, { ticker: "AAPL", price: 526 }, { ticker: "AMZN", price: 288 }, { ticker: "MSFT", price: 514 }, { ticker: "AMZN", price: 909 }, { ticker: "YHOO", price: 225 }, ]; const TBODY = document.getElementById("quote_table_body"); const THEAD_COLS = document.querySelectorAll('th'); const COLUMNS = getColumns(); window.addEventListener('DOMContentLoaded', function() { array_of_quotes.forEach(function(quote, index) { setTimeout(() => { table_row_updater(quote, index); }, (index + 1) * 1000); }); });
{ "domain": "codereview.stackexchange", "id": 45307, "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, html5", "url": null }
javascript, html5 function table_row_updater(quote, index) { const TICKER = quote.ticker; const PRICE = quote.price; const ROW = document.createElement('tr'); ROW.dataset.row = index; COLUMNS.forEach(cell => { const CELL = document.createElement('td'); CELL.dataset.col = cell; CELL.textContent = (cell === TICKER) ? PRICE : ''; ROW.appendChild(CELL); }) TBODY.appendChild(ROW); } function getColumns() { let columns_array = []; THEAD_COLS.forEach(col => { columns_array.push(col.textContent); }) return columns_array; } /* function to add an aditional row not covered by the array */ function addTableRow(newData) { let nextIndex = parseInt(TBODY.lastChild.dataset.row) + 1; table_row_updater(newData, nextIndex) } /* delay and random data as proof of concept that the above function works */ setTimeout(function() { const newData = { ticker: "AAPL", price: 747 }; addTableRow(newData); }, 15000); <table> <thead> <tr> <th>AAPL</th> <th>MSFT</th> <th>AMZN</th> <th>GOOG</th> <th>YHOO</th> </tr> </thead> <tbody id="quote_table_body"></tbody> </table> If you have more questions about it or why some things where changed or parts you do not understand, feel free to add a comment.
{ "domain": "codereview.stackexchange", "id": 45307, "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, html5", "url": null }
c++, template, c++20, floating-point Title: An is_integer Template Function Implementation in C++ Question: I am trying to make an is_integer template function to determine a number is an integer or not. The experimental implementation is_integer Template Function Implementation template<typename T, typename TestT = double> constexpr bool is_integer(T input) { TestT floor_input = std::floor(static_cast<TestT>(input)); if (std::abs(floor_input - input) <= std::numeric_limits<T>::epsilon() ) { return true; } return false; } Full Testing Code The full testing code: // An is_integer Template Function Implementation in C++ #include <cassert> #include <chrono> #include <cmath> #include <iostream> #include <vector> template<typename T, typename TestT = double> constexpr bool is_integer(T input) { TestT floor_input = std::floor(static_cast<TestT>(input)); if (std::abs(floor_input - input) <= std::numeric_limits<T>::epsilon() ) { return true; } return false; } void isIntegerTest(); int main() { auto start = std::chrono::system_clock::now(); isIntegerTest(); auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::time_t end_time = std::chrono::system_clock::to_time_t(end); std::cout << "Computation finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << '\n'; return 0; } void isIntegerTest() { assert(is_integer(1) == true); assert(is_integer(2) == true); assert(is_integer(3) == true); assert(is_integer(1.1) == false); float test_number1 = 1.2; assert(is_integer(test_number1) == false); test_number1 = 1; assert(is_integer(test_number1) == true); double test_number2 = 2; assert(is_integer(test_number2) == true); test_number2 = 2.0001; assert(is_integer(test_number2) == false); return; } Godbolt link is here. All suggestions are welcome.
{ "domain": "codereview.stackexchange", "id": 45308, "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++, template, c++20, floating-point", "url": null }
c++, template, c++20, floating-point Answer: This is wrong for several reasons. What do you mean by "is an integer"? There are many ways to interpret the assertion that some number "is an integer". Do you mean it's an integer type? If so you could use the concept std::integral<T>, but that's obviously not what you mean. Next is checking if a given number can be stored without loss of precision in an integer variable. That is actually a very useful definition. However, your test would fail that because input might be much larger than can be stored even in a std::uintmax_t. Then you can check if a given number is actually exactly an integer. I am assuming that that is what you want to achieve here. Luckily that is not too hard, but see below. Finally, it could be that you have done some floating point operations and want to know if the result is an integer, but due to the inexact nature of floating point it might not come out as an exact integer. In that case, the right tolerance to use actually depends on which and how many operations you did on the numbers before getting the final answer, as every operation increases the error. In any case: Don't use epsilon epsilon is the smallest possible difference between floating point numbers that are in the range of 1 to 2. However, consider that input might be much larger than 1, in which case the smallest difference between input and floor_input will be much larger than epsilon. And if input is very close to 0, the opposite will be the case. You could scale epsilon based on the exponent of input, as shown in this example. But even then it is not necessary: Use std::modf() Due to the way the floating point number format IEEE 754 works, you can tell exactly if a given float or double is an integer or not. One way would be to just cast the number to an integer and compare it with the floating point version: template<typename T> constexpr bool is_integer(T input) { return static_cast<intmax_t>(input) == input; }
{ "domain": "codereview.stackexchange", "id": 45308, "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++, template, c++20, floating-point", "url": null }
c++, template, c++20, floating-point Which works well until input is larger than intmax_t can handle. Luckily, an even better way is available by using std::modf(), which splits a floating point value into an integer and fractional part: template<std::floating_point T> constexpr bool is_integer(T input) { T integer_part; return std::modf(input, &integer_part) == 0; } template<std::integral T> constexpr bool is_integer(T input) { return true; } This also returns true for +INFINITY and -INFINITY. Is infinity an integer though? On the other hand, all floating point values with an exponent larger than the size of the mantissa in bits are integers, so treating infinity as integer might be considered reasonable. What about other numeric types? There are more numeric types than just integers and floating point numbers. What about std::complex? Maybe you are using a library that provides rational numbers? Either you could try in some way to make the code even more generic such that it handles those cases, or you could just forbid those types by requiring that std::is_arithmetic_v<T>. Unnecessary use of if Whenever you have a piece of code that looks like: if (condition) return true; else return false; Just replace that with: return condition;
{ "domain": "codereview.stackexchange", "id": 45308, "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++, template, c++20, floating-point", "url": null }
performance, beginner, c, reinventing-the-wheel, cryptography Title: SHA-256 Implementation Question: I've been working on a byte-oriented SHA-256 implementation for educational purposes. I then tested it using the NIST CAVP tests found here. All tests pass but I would appreciate some feedback from a third party (especially regarding things I may be too involved to see like pointer errors or performance improvements that may have slipped my mind). sha256.h #ifndef SHA256_H #define SHA256_H #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include "utils.h" void sha256(uint8_t* message, size_t message_length); #endif sha256.c #include "sha256.h" const uint32_t round_constants[64] = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; uint32_t right_rotate(uint32_t x, size_t k) { return ((x >> k) | (x << (32 - k))); } uint32_t choice(uint32_t x, uint32_t y, uint32_t z) { return ((x & y) ^ (~x & z)); } uint32_t majority(uint32_t x, uint32_t y, uint32_t z) { return ((x & y) ^ (x & z) ^ (y & z)); } uint32_t delta0(uint32_t x) { return (right_rotate(x, 2) ^ right_rotate(x, 13) ^ right_rotate(x, 22)); } uint32_t delta1(uint32_t x) { return (right_rotate(x, 6) ^ right_rotate(x, 11) ^ right_rotate(x, 25)); }
{ "domain": "codereview.stackexchange", "id": 45309, "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, beginner, c, reinventing-the-wheel, cryptography", "url": null }
performance, beginner, c, reinventing-the-wheel, cryptography uint32_t sigma0(uint32_t x) { return (right_rotate(x, 7) ^ right_rotate(x, 18) ^ (x >> 3)); } uint32_t sigma1(uint32_t x) { return (right_rotate(x, 17) ^ right_rotate(x, 19) ^ (x >> 10)); } void sha256_padding(uint8_t* message, uint8_t** buffer, size_t message_length, size_t* buffer_length) { size_t total_zeros = 0; uint64_t bit_length = 0; // When the message is 9 bytes short of a block multiple there is no additional block added. if ((message_length + 9) % 64 == 0) { *buffer_length = message_length + 9; } else { *buffer_length = ((message_length + 9 + 64) / 64) * 64; } *buffer = safe_malloc((*buffer_length * sizeof **buffer)); memcpy((*buffer), message, message_length); // Add the 1 bit as big-endian using the byte 0x80 = 0b10000000. (*buffer)[message_length] = 0x80; // Compute and add the needed amount of 0 bits to reach congruence modulo 512. total_zeros = *buffer_length - message_length - 9; memset((*buffer + message_length + 1), 0x00, total_zeros); // Add the length of the message as a big-endian 64-bit value. bit_length = (uint64_t)message_length * 8; for (size_t i = 0; i < 8; i++) { (*buffer)[*buffer_length - 8 + i] = (uint8_t)(bit_length >> (56 - i * 8)); } } void sha256_compression(const uint8_t* block, uint32_t* hash) { uint32_t a = hash[0]; uint32_t b = hash[1]; uint32_t c = hash[2]; uint32_t d = hash[3]; uint32_t e = hash[4]; uint32_t f = hash[5]; uint32_t g = hash[6]; uint32_t h = hash[7]; uint32_t temp1, temp2; uint32_t msg_schedule[64]; for (size_t i = 0, j = 0; i < 16; i++, j += 4) { msg_schedule[i] = (block[j] << 24) | (block[j + 1] << 16) | (block[j + 2] << 8) | (block[j + 3]); } for (size_t i = 16; i < 64; i++) { msg_schedule[i] = sigma1(msg_schedule[i - 2]) + msg_schedule[i - 7] + sigma0(msg_schedule[i - 15]) + msg_schedule[i - 16]; }
{ "domain": "codereview.stackexchange", "id": 45309, "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, beginner, c, reinventing-the-wheel, cryptography", "url": null }
performance, beginner, c, reinventing-the-wheel, cryptography for (size_t i = 0; i < 64; i++) { temp1 = h + delta1(e) + choice(e, f, g) + round_constants[i] + msg_schedule[i]; temp2 = delta0(a) + majority(a, b, c); h = g; g = f; f = e; e = d + temp1; d = c; c = b; b = a; a = temp1 + temp2; } hash[0] += a; hash[1] += b; hash[2] += c; hash[3] += d; hash[4] += e; hash[5] += f; hash[6] += g; hash[7] += h; } void sha256(uint8_t* message, size_t message_length) { uint8_t* padded_message = NULL; size_t padded_length = 0; uint32_t hash[8] = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 }; sha256_padding(message, &padded_message, message_length, &padded_length); // Apply the compression function on every block. for (size_t i = 0; i < padded_length / 64; i++) { sha256_compression((padded_message + i * 64), hash); } for (size_t i = 0; i < 8; i++) { printf("%08x", hash[i]); } printf("\n"); free(padded_message); } utils.h #ifndef UTILS_H #define UTILS_H #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> void* safe_malloc(size_t size); FILE* safe_fopen(const char* file_path, const char* mode); void read_file_bytes(const char* file_path, uint8_t** buffer, size_t* file_length); #endif utils.c #include "utils.h" void* safe_malloc(size_t size) { void* ptr = malloc(size); if (ptr == NULL) { printf("Unable to allocate enough memory!!\n"); exit(EXIT_FAILURE); } return ptr; } FILE* safe_fopen(const char* file_path, const char* mode) { FILE* file_ptr = fopen(file_path, mode); if (file_ptr == NULL) { printf("Unable to open the file!!\n"); exit(EXIT_FAILURE); } return file_ptr; }
{ "domain": "codereview.stackexchange", "id": 45309, "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, beginner, c, reinventing-the-wheel, cryptography", "url": null }
performance, beginner, c, reinventing-the-wheel, cryptography return file_ptr; } // Returns the size of a file in bytes (max 2GiB due to ftell()). size_t file_size(FILE* file_ptr) { size_t file_length = 0; fseek(file_ptr, 0, SEEK_END); file_length = ftell(file_ptr); rewind(file_ptr); return file_length; } // Reads a file into a byte array passed by reference. // Freeing the buffer is the callers responsibility. void read_file_bytes(const char* file_path, uint8_t** buffer, size_t* file_length) { FILE* file_ptr = safe_fopen(file_path, "rb"); size_t bytes_read = 0; *file_length = file_size(file_ptr); *buffer = safe_malloc(*file_length * sizeof **buffer); bytes_read = fread(*buffer, 1, *file_length, file_ptr); if (bytes_read != *file_length) { printf("An error occurred while trying to read from the file!!\n"); exit(EXIT_FAILURE); } fclose(file_ptr); } driver.c #include "sha256.h" int main(int argc, char* argv[]) { uint8_t* message = NULL; size_t message_length = 0; read_file_bytes(argv[1], &message, &message_length); sha256(message, message_length); free(message); return 0; } Hope I didn't break any rules when writing the question :)) Thanks in advance Answer: The functions that are not used outside of a translation unit should be defined as having internal linkage: Everything except sha256() should be defined with the static keyword. #if 0 uint32_t right_rotate(uint32_t x, size_t k) { return ((x >> k) | (x << (32 - k))); } #else static uint32_t right_rotate(uint32_t x, size_t k) { return ((x >> k) | (x << (32 - k))); } #endif // And so on... Error messages go to stderr: I suggest: #if 0 if (ptr == NULL) { printf("Unable to allocate enough memory!!\n"); exit(EXIT_FAILURE); } #else #include <errno.h> errno = 0; ... if (ptr == NULL) { if (errno) { perror("malloc()"); } else { fputs("Unable to allocate enough memory!!\n", stderr); } exit(EXIT_FAILURE); } #endif
{ "domain": "codereview.stackexchange", "id": 45309, "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, beginner, c, reinventing-the-wheel, cryptography", "url": null }
performance, beginner, c, reinventing-the-wheel, cryptography See: Why use stderr when printf works fine? file_size() risks invoking undefined behavior: From the C Standard: (footnote 234 on p. 267 of the linked Standard) Setting the file position indicator to end-of-file, as with fseek(file, 0, SEEK_END),has undefined behavior for a binary stream (because of possible trailing null characters) or for anystream with state-dependent encoding that does not assuredly end in the initial shift state. If the file was opened in binary mode, fseek(file_ptr, 0, SEEK_END); would invoke undefined behavior. Don't include unnecessary header files: sha256.h doesn't require anything but stdint.h and stddef.h. #if 0 #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #else #include <stdint.h> #include <stddef.h> /* This suffices for the definition of size_t. */ #endif sha256.c should not depend on sha256.h. Use the headers you need per file, no more, no less. Minor: You don't need the extra parenthesis in the calls to memcpy(). You can safely drop them: #if 0 memcpy((*buffer), message, message_length); #else memcpy(*buffer, message, message_length); #endif
{ "domain": "codereview.stackexchange", "id": 45309, "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, beginner, c, reinventing-the-wheel, cryptography", "url": null }
c++, performance, template, c++20, proxy Title: Optimizing Vector 2D Length Comparisons in C++ Question: I've encountered a readability issue in C++ when comparing the length of a vector to a scalar. Commonly, I see solutions like this: Vector<float> v{23., 42.}; if (v.lengthSquared() < 8 * 8) ... While this works, it's not very readable. I believe a more intuitive approach would be: if (v.length() < 8) ... To achieve this, I've written a LengthProxy for my vector class: #include <cmath> #include <cstdlib> #include <iostream> template<typename T> concept Sqrtable = requires(T a) { { std::sqrt(a) } -> std::convertible_to<T>; };
{ "domain": "codereview.stackexchange", "id": 45310, "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++, performance, template, c++20, proxy", "url": null }
c++, performance, template, c++20, proxy template <class T> requires Sqrtable<T> class LengthProxy { T lengthSquared; public: LengthProxy(T lengthSquared) : lengthSquared(lengthSquared) {} T operator*() const { return std::sqrt(lengthSquared); } operator T() const { return std::sqrt(lengthSquared); } #if __cplusplus >= 202002L auto operator<=>(const LengthProxy<T>& other) const { return lengthSquared <=> other.lengthSquared; } auto operator<=>(const auto& other) const { return lengthSquared <=> other * other; } #endif auto operator==(const LengthProxy<T>& other) const { return lengthSquared == other.lengthSquared; } auto operator==(const auto& other) const { return lengthSquared == other * other; } auto operator!=(const LengthProxy<T>& other) const { return lengthSquared != other.lengthSquared; } auto operator!=(const auto& other) const { return lengthSquared != other * other; } auto operator<=(const LengthProxy<T>& other) const { return lengthSquared <= other.lengthSquared; } auto operator<=(const auto& other) const { return lengthSquared <= other * other; } auto operator>=(const LengthProxy<T>& other) const { return lengthSquared >= other.lengthSquared; } auto operator>=(const auto& other) const { return lengthSquared >= other * other; } auto operator<(const LengthProxy<T>& other) const { return lengthSquared < other.lengthSquared; } auto operator<(const auto& other) const { return lengthSquared < other * other; } auto operator>(const LengthProxy<T>& other) const { return lengthSquared > other.lengthSquared; } auto operator>(const auto& other) const { return lengthSquared > other * other; } }; template <class T> struct Vector2 { T x, y; Vector2(T x, T y) : x(x), y(y) {} auto length() const { return LengthProxy<T>(x * x + y * y); } };
{ "domain": "codereview.stackexchange", "id": 45310, "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++, performance, template, c++20, proxy", "url": null }
c++, performance, template, c++20, proxy int main(int argc, char** argv) { if (argc < 4) return 0; Vector2<double> p(atof(argv[1]), atof(argv[2])); auto l = p.length(); std::cout << (l < atof(argv[3])) << std::endl; } This LengthProxy aims to make length comparisons more readable without sacrificing performance. I'm utilizing C++20 features like concepts and the spaceship operator. Here are my specific concerns and queries: Readability vs. Performance: Does the LengthProxy improve readability at the cost of significant performance overhead, especially considering the use of std::sqrt in comparisons? Code Complexity: Although LengthProxy makes the calling code more readable, it adds complexity. Is this an acceptable trade-off, or are there simpler alternatives? C++20 Features: My solution relies heavily on C++20 features. Are there compatibility issues I should be aware of, or ways to make this more backward-compatible while maintaining readability? Testing and Benchmarks: I haven't yet conducted extensive tests, particularly for edge cases or performance benchmarks. Are there specific scenarios or tests you would recommend? Alternative Approaches: Is there a better or more idiomatic way to achieve the same goal in C++? Any insights, suggestions, or critiques would be greatly appreciated. Answer: Bad concept template<typename T> concept Sqrtable = requires(T a) { { std::sqrt(a) } -> std::convertible_to<T>; };
{ "domain": "codereview.stackexchange", "id": 45310, "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++, performance, template, c++20, proxy", "url": null }
c++, performance, template, c++20, proxy This is a bad use of concepts. Concepts are not for testing what a type can do, they are for testing what a type is. A concept like “square-root-able” is silly… what you want is a number concept. (And, yes, I am aware that the standard concepts library has a ton of "-able" concepts, like std::default_initializable and std::copyable, which seem to violate my point. However, these are very low-level building blocks. And unless you are making other very low-level building blocks, like a copy() algorithm (like std::ranges::copy())—which, again, is what the standard library mostly does—you normally need more than very low-level building block concepts. In real world user code, rather than those low-level concepts, you would probably use something a bit higher level, like std::regular (at least).) You can already see why a “square-root-able” concept is a bad idea, I hope. If you did constrain LengthProxy as “square-root-able”, then you would be unable to rewrite it using std::hypot() instead of std::sqrt(), as @TobySpeight suggests. Your class would be locked into a specific, potentially sub-par implementation, because a concept is part of the public API; you can’t change it without breaking everyone else’s code. In a perfect world, the standard library math functions would already be properly constrained, so there would be a xstd::number concept, and std::sqrt() and std::hypot() would both be constrained to use it. Which means that your Vector2 and LengthProxy would naturally both be using xstd::number, and everything would just work. It would be magical.
{ "domain": "codereview.stackexchange", "id": 45310, "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++, performance, template, c++20, proxy", "url": null }
c++, performance, template, c++20, proxy What you could, and probably should, do is make a decent number concept. This is not trivial. I’ve been considering something like that for my own library, but haven’t settled on a design. I’ve toyed around with a mathematical hierarchy of “natural number”, “rational number”, “real number”, and “complex number”; I’ve mucked around with defining numbers based on the standard concepts (like std::floating_point) or traits (like std::is_arithmetic); or by operations (as in requires (T a, T b) { { a + b } -> std::convertible_to<T>; /* etc. */ }. If you had a number concept, then even if it were not literally constrained to work with std::sqrt() (or std::hypot()), types that satisfy the concept should support being “square-rooted”, even if not necessarily by std::sqrt() or std::hypot() specifically. That’s because, internally and/or conceptually, that’s how those functions work. They probably do something conceptually (if not literally) like using Newton’s method to iteratively solve for the square root, which really just boils down to a bunch of multiplications, divisions, and additions. Thus, anything that supports multiplying, dividing, and adding is automatically “square-root-able”. This is how concepts are supposed to work. (In practice, to support any number type, you’d probably want to rewrite your function more like using std::sqrt; sqrt(lengthSquared);, and trust in the gods of ADL to find the right sqrt() function. But that’s just a quirk of C++.) But yeah, if you want a simple and clear rule for concepts: Don’t simply look at a class or function’s implementation, pull out the operations used, and then constrain the class or function using a list of those operations. Think of concepts as conceptual, and ask, “conceptually speaking, what should a type that should work with this class or function be?” In your case, you’re considering the components of a mathematical vector, so, it should be a mathematical number (or something conceptually equivalent).
{ "domain": "codereview.stackexchange", "id": 45310, "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++, performance, template, c++20, proxy", "url": null }
c++, performance, template, c++20, proxy So yeah, tl;dr:
{ "domain": "codereview.stackexchange", "id": 45310, "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++, performance, template, c++20, proxy", "url": null }
c++, performance, template, c++20, proxy “-able” concepts are bad. Constrain on what things are, not on what they do. Make a decent “number” concept; that’s all you need. Questions Readability vs. Performance: Does the LengthProxy improve readability at the cost of significant performance overhead, especially considering the use of std::sqrt in comparisons? I don’t see what the “significant performance overhead” is. Isn’t the whole point of the proxy class to avoid the square root that would have otherwise been inevitable? If you never use the raw length—if you only do a comparison—then where is the extra overhead? If you do use the raw length, then you were doomed to pay for a square root regardless, so, again, where is the extra overhead? Of course, everything depends how you use the length. If you just use it once, and don’t hold on to it or pass it around, then the proxy wins every time. But if you use the length value more than once, things get dicier. auto const v_length = v.length(); // Comparison with a scalar: // - total natural cost: 1 sqrt // - total proxy cost : 1 multiply // Advantage: proxy. if (v_length > 1.0) // With a scalar range: // - total natural cost: 1 sqrt // - total proxy cost : 2 multiplies // Advantage: proxy. if ((v_length >= min) and (v_length <= max)) // Doing some math: // - total natural cost: 1 sqrt // - total proxy cost : 1 sqrt // Advantage: neither. auto const x = v_length - 1.0; // Doing more complex math: // - total natural cost: 1 sqrt // - total proxy cost : 3 sqrt // Advantage: natural. auto const y = std::min(std::acos(v_length), std::asin(v_length)) / v_length; So here is the trade-off in readability and performance: If you know length() is expensive (which is the natural, default assumption), then you should: do simple comparisons with length_squared() do complex stuff with length() If you know length() is cheap, but returns a proxy, then you should:
{ "domain": "codereview.stackexchange", "id": 45310, "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++, performance, template, c++20, proxy", "url": null }
c++, performance, template, c++20, proxy If you know length() is cheap, but returns a proxy, then you should: do simple comparisons with length() do complex stuff with auto len = static_cast<T>(length()); and use len
{ "domain": "codereview.stackexchange", "id": 45310, "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++, performance, template, c++20, proxy", "url": null }
c++, performance, template, c++20, proxy Your challenge is that case 1 is the “natural”, default case. Anyone going in blind to a new codebase will do this by default. You want to change the calculus, which is fine… but now you need to communicate that to users. You need to change the default behaviour. That is not impossible… but it is hard. I am always very wary of people talking up “readability” when changing factors that are universally known and understood, and that’s what you are doing here. In my mind “readability” doesn’t just involve being aesthetically pleasing, it also involves communicating well. And changing a universally understood meaning of something is not good communication. EVERYONE writing code dealing with vectors knows that length() is expensive… which is why everyone does the length_squared() dance. You want to make that universal knowledge wrong, and make code that EVERYONE understands no longer work the way they understand. Is that “more readable”? I struggle to agree. You may disagree, and that’s fine, but I would point out that the odds are stacked heavily against you, because the “natural” case is, naturally, not only very well understood, it is very well-supported. As @TobySpeight pointed out, std::hypot() exists to guard against out-of-range computations for vector lengths, and anyone who knows their salt knows to check for v * v being out-of-range before doing length_squared() > (v * v) if that’s a potential problem. But length() > v appears safe (assuming length() is written properly, with std::hypot()). You need to make sure users understand that it is not; you need to make them understand that their standard assumptions have been violated. Again, not impossible… but hard. Is it worth it for a minor aesthetic improvement? Code Complexity: Although LengthProxy makes the calling code more readable, it adds complexity. Is this an acceptable trade-off, or are there simpler alternatives?
{ "domain": "codereview.stackexchange", "id": 45310, "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++, performance, template, c++20, proxy", "url": null }
c++, performance, template, c++20, proxy It doesn’t really add all that much complexity (once the proxy class is pared down a bit), and most of that complexity is hidden from users. C++20 Features: My solution relies heavily on C++20 features. Are there compatibility issues I should be aware of, or ways to make this more backward-compatible while maintaining readability? Decide whether you’re C++20 or not. If you’re in, then you’re in. It makes no sense to use concepts without any checks, but then to wrap operator<=> in a guard. If you’re not committed to C++20, then you have to guard both the concepts and the spaceship operator (and any other C++20 features). So either do this: #include <cmath> #include <compare>
{ "domain": "codereview.stackexchange", "id": 45310, "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++, performance, template, c++20, proxy", "url": null }
c++, performance, template, c++20, proxy // Need a number concept. template <number T> class LengthProxy { T _length_squared; public: constexpr explicit LengthProxy(T v) : _length_squared{std::move(v)} {} constexpr operator auto() const { using std::sqrt; return sqrt(_length_squared); } constexpr auto operator<=>(LengthProxy const&) const = default; constexpr auto operator<=>(T const& t) const { return _length_squared <=> (t * t); } }; Or do this: #ifdef __has_include # if __has_include(<version>) # include <version> # endif #endif #include <cmath> #ifdef __cpp_lib_three_way_comparison # include <compare> #endif // __cpp_lib_three_way_comparison template <typename T> #ifdef __cpp_concepts requires number<T> #endif // __cpp_concepts class LengthProxy { T _length_squared; public: constexpr explicit LengthProxy(T v) : _length_squared{std::move(v)} {} constexpr operator auto() const { using std::sqrt; return sqrt(_length_squared); } #ifdef __cpp_impl_three_way_comparison constexpr auto operator<=>(LengthProxy const&) const = default;
{ "domain": "codereview.stackexchange", "id": 45310, "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++, performance, template, c++20, proxy", "url": null }
c++, performance, template, c++20, proxy constexpr auto operator<=>(T const& t) const { return _length_squared <=> (t * t); } #else friend constexpr auto operator==(LengthProxy const& a, LengthProxy const& b) { return a._length_squared == b._length_squared; } friend constexpr auto operator!=(LengthProxy const& a, LengthProxy const& b) { return a._length_squared != b._length_squared; } friend constexpr auto operator<(LengthProxy const& a, LengthProxy const& b) { return a._length_squared < b._length_squared; } friend constexpr auto operator>(LengthProxy const& a, LengthProxy const& b) { return a._length_squared > b._length_squared; } friend constexpr auto operator<=(LengthProxy const& a, LengthProxy const& b) { return a._length_squared <= b._length_squared; } friend constexpr auto operator>=(LengthProxy const& a, LengthProxy const& b) { return a._length_squared >= b._length_squared; } friend constexpr auto operator==(LengthProxy const& p, T const& t) { return p._length_squared == (t * t); } friend constexpr auto operator!=(LengthProxy const& p, T const& t) { return p._length_squared != (t * t); } friend constexpr auto operator<(LengthProxy const& p, T const& t) { return p._length_squared < (t * t); } friend constexpr auto operator>(LengthProxy const& p, T const& t) { return p._length_squared > (t * t); } friend constexpr auto operator<=(LengthProxy const& p, T const& t) { return p._length_squared <= (t * t); } friend constexpr auto operator>=(LengthProxy const& p, T const& t) { return p._length_squared >= (t * t); }
{ "domain": "codereview.stackexchange", "id": 45310, "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++, performance, template, c++20, proxy", "url": null }
c++, performance, template, c++20, proxy friend constexpr auto operator==(T const& t, LengthProxy const& p) { return (t * t) == p._length_squared; } friend constexpr auto operator!=(T const& t, LengthProxy const& p) { return (t * t) != p._length_squared; } friend constexpr auto operator<(T const& t, LengthProxy const& p) { return (t * t) < p._length_squared; } friend constexpr auto operator>(T const& t, LengthProxy const& p) { return (t * t) > p._length_squared; } friend constexpr auto operator<=(T const& t, LengthProxy const& p) { return (t * t) <= p._length_squared; } friend constexpr auto operator>=(T const& t, LengthProxy const& p) { return (t * t) >= p._length_squared; } #endif // __cpp_impl_three_way_comparison };
{ "domain": "codereview.stackexchange", "id": 45310, "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++, performance, template, c++20, proxy", "url": null }
c++, performance, template, c++20, proxy Pick a lane. It’s 2023, and all compilers worth mentioning support at least the subset of C++20 that you’re using. I would suggest not worrying about it, and going all in on C++20. Testing and Benchmarks: I haven't yet conducted extensive tests, particularly for edge cases or performance benchmarks. Are there specific scenarios or tests you would recommend? Not particularly. If you want to specify behaviour in the cases of x where x * x or any of the other operations overflows or underflows, then of course you’d need to test that. But I’d just declare that UB, and leave dealing with it to safe number wrappers. That way, people who know it won’t be a problem (which is the vast majority of the time) pay nothing, and people who are concerned about it can pay the whatever costs they are willing to incur via their safe number wrappers. Alternative Approaches: Is there a better or more idiomatic way to achieve the same goal in C++? I mean, the more idiomatic way is literally the way you are trying to avoid (“length_squared() > (x * x)”. You are deliberately trying to violate the idiom. Is that “better”? Other, miscellaneous comments about code You need to include <compare> if you’re defining the spaceship operator (because, under the hood, the auto is being defined to one of the ordering types defined in <compare>). You should really use more vertical space in the LengthProxy class. Everything is kinda squished together.
{ "domain": "codereview.stackexchange", "id": 45310, "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++, performance, template, c++20, proxy", "url": null }
c++, performance, template, c++20, proxy The converting constructor should be explicit but—and here I disagree with @TobySpeight—the conversion operator to T should not be explicit. It would be silly for a proxy type for T to have an explicit conversion to T. That kinda defeats the purpose. (Of course, here you have the issue that your conversion to T is expensive… but that’s just part of the whole “violating the idiom” thing you’ve committed to. You might consider having an optional<T> data member for the un-squared length, that gets set iff the un-squared length is ever needed, so you only ever pay the cost of sqrt() one time max. That makes the proxy heavier, but not by all that much, and if you are trucking around a ton of these proxies, something else has gone horribly awry.) I don’t see the point of operator*. Don’t add stuff to a public interface that you don’t actually need. However, an accessor to get the squared length could be useful. If I know length() is returning a proxy object, but I could use the squared length for some reason, there is no sense in getting the un-squared length (via operator T) then squaring it. There is also no sense in calling length_squared() to recalculate the squared length when it’s already right there in the proxy object.
{ "domain": "codereview.stackexchange", "id": 45310, "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++, performance, template, c++20, proxy", "url": null }
c++, performance, template, c++20, proxy You might also consider adding some noexcepts in there, even if only conditionally, for stuff that shouldn’t fail… which is most stuff in the proxy class. The constructor could probably be noexcept(std::is_nothrow_move_constructible_v<T>) (and you should move construct lengthSquared). The comparisons should be noexcept((std::declval<T const>() <=> std::declval<T const>()) and (std::declval<T const&>() <=> std::declval<T const&>())), or similar. Even the square root should theoretically never fail, because the class is being initialized with a value that should be positive, and should never over- or underflow because of how it was calculated. You can really double-down on that assumption by making the constructor private, and making the proxy a friend of Vector2, so only Vector2 can initialize it with (what you assume) are valid values. And, of course, constexpr all the things.
{ "domain": "codereview.stackexchange", "id": 45310, "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++, performance, template, c++20, proxy", "url": null }
c++, strings Title: Trimming a string Question: Function: Trim Returns a new string after removing any white-space characters from the beginning and end of the argument. string trim(string word) { if(startsWith(word, " ")) return removeSpaces(word, "Front"); if(endsWith(word, " ")) return removeSpaces(word , "Back"); return word; } string removeSpaces(string word , string position){ if(position == "Front"){ for(int i =0; i <word.length();i++){ if(word[i] != ' '){ return word; }else{ word.erase(i); } } return word; }else if(position == "Back"){ for(int i =word.length() - 1 ; i >=0 ; i--){ if(word[i] != ' '){ return word; }else{ word.erase(i); } } return word; } } Answer: The second argument to removeSpaces should by no means be a string. I suggest an enum: enum StringPostion { BEGINNING_OF_STRING, END_OF_STRING, }; You appear to have a using namespace std; statement in your program. You shouldn't do this. This StackOverflow question explains why. Your implementation of trim removes spaces from the front or back of word, not both.
{ "domain": "codereview.stackexchange", "id": 45311, "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++, strings", "url": null }
c++, strings Your implementation of trim removes spaces from the front or back of word, not both. You've chosen an O(kn) algorithm (which is in any case incorrect), where k is the number of spaces at the beginning of the string and n is the number of characters in the string. Each call to s.erase(i) causes all of the characters after i to be shifted to the left. It also causes the string to be shortened by one character. Your function will only erase half of the leading or trailing spaces since you shorten the string and increment i. Try this: std::string trim(std::string word) { removeSpaces(word, BEGINNING_OF_STRING); removeSpaces(word, END_OF_STRING); return word; } void removeSpaces(std::string& word, StringPosition position) { switch (position) { case BEGINNING_OF_STRING: { const auto first_nonspace = word.find_first_not_of(' '); word.erase(0, first_nonspace); return; } case END_OF_STRING: { const auto last_nonspace = word.find_last_not_of(' '); if (last_nonspace != std:string::npos) word.erase(last_nonspace + 1); return; } } }
{ "domain": "codereview.stackexchange", "id": 45311, "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++, strings", "url": null }
python, pandas, natural-language-processing Title: Creating csvs using Pandas on large dataset for document retrieval Question: I am trying to build a useable NLP corpus but getting bottlenecked by how long the program takes (200 hours). With so much data I know that optimizing my code even a little bit will net me huge time savings down the road, so I wanted to post this code and ask for some advice on speeding it up. I added a parameter to load the dataset if I have already made it, resulting in much faster times afterward, and tested on a small portion of the dataset, not the whole thing. When generating the tables, kwargs expects a size parameter and for loading it expects two file directory parameters. The features "full_text" is the raw full text of an academic article and "full_text_cleaned" has had the text set to lowercase and punctuation stripped. I can also provide how I created this dataset if requested. Sample Corpus: 29000 entries paper_id title abstract full_text full_text_cleaned string string string string string Relevant code class Doc_Finder(): def __init__(self, corpus_file): self.corpus = pd.read_csv(corpus_file) self.corpus_dir = corpus_file
{ "domain": "codereview.stackexchange", "id": 45312, "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, pandas, natural-language-processing", "url": null }
python, pandas, natural-language-processing def make_keywords(self, save=False, load=False, **kwargs): if save and load: raise Exception("Invalid Parameters") if save: self.keyword_index = pd.DataFrame(columns=['id','keyword']) total = kwargs['size'] self.keyword_map = [] for _, row in tqdm(self.corpus.head(total).iterrows(), total=total): s = [] for i in str(row['full_text_cleaned']).split(' '): if i not in s and not i.isnumeric() and i not in stopwords.words('english') and i.isalnum() and not isHyperlink(i): s.append(i) if i not in self.keyword_map: self.keyword_map.append(i) for i in s: self.keyword_index.loc[len(self.keyword_index.index)] = [row['paper_id'], i] if save: idx_dir = './keyword_index_' + str(total) + '.csv' self.keyword_index.to_csv(idx_dir, index=False) tempdf = pd.DataFrame(data=self.keyword_map, columns=['keyword'], dtype=str) map_dir = './keyword_map_' + str(total) + '.csv' tempdf.to_csv(map_dir, index=False) elif load: self.keyword_index = pd.read_csv(kwargs['index_dir']) self.keyword_map = pd.read_csv(kwargs['map_dir'])['keyword'].tolist() I run the code using this snippet doc_finder = Doc_Finder(sample_corpus) doc_finder.make_keywords(save=True, size=len(doc_finder.corpus['paper_id'])) The result is two csvs: The keyword index has a paper_id and keyword pair. Listing each keyword and each paper. paper_id keyword 00033d5a12240a8684cfe943954132b43434cf48 extraction 00033d5a12240a8684cfe943954132b43434cf48 expected
{ "domain": "codereview.stackexchange", "id": 45312, "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, pandas, natural-language-processing", "url": null }
python, pandas, natural-language-processing 00033d5a12240a8684cfe943954132b43434cf48 expected Then the set of all keywords from all the documents. This is in an attempt to make the document retrieval I will be doing after this faster, as I can match against the set of keywords and then query all the papers that have those keywords in the index table. Keyword list keyword expected ... I recognize that an SQL table of some kind would probably be a better solution, but I am limited to my local machine and do not know SQL very well. I also found a library called Dask but I think I would need to rethink how I perform this creation process since not all of the techniques would transfer. I am a little out of my comfort zone but this has been a rewarding experience.
{ "domain": "codereview.stackexchange", "id": 45312, "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, pandas, natural-language-processing", "url": null }
python, pandas, natural-language-processing Answer: measurements This submission is about performance, yet it includes no profile measurements, and almost no performance data. We are told only that each of 29k articles takes an expected 25 seconds to extract keywords, without learning how many megabytes that is. representation We are told we need to "build a useable NLP corpus" without learning how subsequent stages of the pipeline will use this first stage. Discarding full_text in favor of just full_text_cleaned would be an easy way to cut I/O delays in half, if the pipeline only needs the cleaned text. Using parquet format compression offers similar benefits. From your mention of keywords, almost certainly you should be using an RDBMS that offers full text indexing. memory use You're storing 29k articles in RAM. Twice. Maybe you have lots of memory. And your article count will not increase in the coming months. Cross your fingers. Consider adopting a streaming approach, where you continuously stream data out to disk, never holding onto the text of more than one article at a time. Process an article, spit out its data, forget the article, and move on to the next. Organizing your workflow around enormous memory-hungry data frames is the exact opposite of streaming. If you're not paging to disk now, you will be once the corpus gets bigger. constructor class Doc_Finder(): No. Pep-8 is very clear on how to spell this: DocFinder Similarly, spell it def is_hyperlink. def __init__(self, corpus_file): self.corpus = ... self.corpus_dir = corpus_file That second object attribute appears to be misnamed as a directory when really it's a ..._file The language doesn't require this, but it is polite to the Gentle Reader to introduce all object attributes up in the constructor, as an inventory of what's important. Please add: self.keyword_index = None self.keyword_map = None stuttering if if save: ... if save:
{ "domain": "codereview.stackexchange", "id": 45312, "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, pandas, natural-language-processing", "url": null }
python, pandas, natural-language-processing stuttering if if save: ... if save: It's unclear what good that second clause is doing. Recommend you combine the two of them. meaningful identifiers s = [] Wow. You're just not going to give me anything, are you? Not a hint, not a comment. Maybe call this vocabulary? Also, based on the i not in s conjunct, it looks like you really want a set rather than a list. The in operator runs in O(N) linear time for vocabulary list of size N, and in O(1) constant time for a set of any size. As it stands, you have a O(N²) quadratic loop which is very slow for "large" articles. Similar remarks for the keyword_map list, which should be a set. Also there's no need to test membership, you can just unconditionally add word i to that set. If it's already there, no harm done, there's no effect. pre-allocate for i in s: self.keyword_index.loc[len(self.keyword_index.index)] = [row['paper_id'], i] We are extending the keyword_index DataFrame one row at a time. Don't do that, as it is slower than necessary. Build up a giant list of dicts, and feed that all at once to pd.DataFrame to create a giant DataFrame all at once. Or have a generator yield those dicts.
{ "domain": "codereview.stackexchange", "id": 45312, "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, pandas, natural-language-processing", "url": null }
c++, strings, c++20 Title: trimming a string using C++20 ranges Question: I have a function which is supposed to trim a string by removing trailing whitespace, then exactly one instance of a fixed string, if it exists, and then any remaining trailing whitespace. It works as intended but I'd like to do this neatly just by using views. Is there a clever and efficient way to do that? Also, I'm currently limited to C++20, but if there's a nice way to do this with future standards (I already know I'd like to use std::ranges::to from C++23), that would be welcome as well. The rtrim function is below with a test function in main to exercise it. When everything is working as expected, the program prints nothing. #include <iostream> #include <iomanip> #include <ranges> #include <string> #include <string_view> std::string& rtrim(std::string& str, const std::string_view pattern) { auto view = str | std::views::reverse | std::views::drop_while([](char x){ return std::isspace(x); }) | std::views::reverse ; str = {view.begin(), view.end()}; if (str.ends_with(pattern)) { str.erase(str.size() - pattern.size(), pattern.size()); } auto view2 = str | std::views::reverse | std::views::drop_while([](char x){ return std::isspace(x); }) | std::views::reverse ; return str = {view2.begin(), view2.end()}; }
{ "domain": "codereview.stackexchange", "id": 45313, "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++, strings, c++20", "url": null }
c++, strings, c++20 int main() { struct { std::string input; std::string pattern; std::string expected; } tests[] = { { "xox foo xox", "xox", "xox foo" }, { "xox foo xox ", "xox", "xox foo" }, { "xox foo xoxox ", "xox", "xox foo xo" }, { "xox fooxox", "xox", "xox foo" }, { "xox fooxxxx", "xxx", "xox foox" }, { "xox fooxxxxx", "xxx", "xox fooxx" }, { "xox fooxxxxxx", "xxx", "xox fooxxx" }, }; for (auto& test : tests) { auto result = rtrim(test.input, test.pattern); if (result != test.expected) { std::cerr << "Expected " << std::quoted(test.expected) << " but got " << std::quoted(result) << " with input " << std::quoted(test.input) << " and pattern " << std::quoted(test.pattern) << '\n'; } } } ``` Answer: The dream of ranges C++20 is really incomplete in a lot of ways. There were so many features added, there was a lot of push just to get the basics in, and add the polish later. Every major feature suffered because of it, including ranges. A lot of the things you should do for a problem like this are just not possible until C++23. C++23 really completes C++20; in many ways, C++20 is just not “finished” without C++23’s additions. (This happened before, by the way. C++14 was really a “bugfix” for C++11. The standardization for C++11 had gone on for so long—it was originally optimistically called C++0x, assuming it would be done before 2010—that they just wanted to get it out there, and then add the polish later.) What you should do is make a custom range adaptor that drops all of the trailing elements for which a predicate is satisfied; a drop_last_while adaptor. With that and a drop_suffix range adaptor you could do this: auto rtrim(std::string& str, std::string_view pattern) -> std::string& { auto const is_space = [](auto c) { return std::isspace(c); }
{ "domain": "codereview.stackexchange", "id": 45313, "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++, strings, c++20", "url": null }
c++, strings, c++20 str.resize( std::ranges::size( str | drop_last_while(is_space) | drop_suffix(pattern) | drop_last_while(is_space) ) ); // Or, the same, spread out: // // Transform the string to the final form (as a view): // auto view = str // | drop_last_while(is_space) // | drop_suffix(pattern) // | drop_last_while(is_space); // // Get the size of the final form: // auto const view_size = std::ranges::size(view); // // Resize the string to that size (works because we're only trimming // from the end): // str.resize(view_size); return str; }
{ "domain": "codereview.stackexchange", "id": 45313, "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++, strings, c++20", "url": null }
c++, strings, c++20 return str; } But… you can’t actually make a custom range adaptor in C++20, because they forgot that key little feature. Starting in C++23, you have what you need: std::ranges::range_adaptor_closure. So, to put it bluntly, you simply can’t do this as “nicely” as you might hope in C++20. You can get partway there, but not all the way. (Incidentally, I don’t see why you’d want to use ranges::to in a case like this. That just doesn’t make any sense. ranges::to creates a new object from a range… but you already have the object you want: str. You are modifying that object, so why would you want to create a new one?) You can’t create range adaptors in C++20, but you can create views. That’s a little clunkier, but it’ll have to do. So, what you’d want to do is create a drop_last_while_view. For bidirectional views or better, that’s pretty trivial: template <std::ranges::view V, typename Pred> requires std::ranges::forward_range<V> and std::is_object_v<Pred> and std::indirect_unary_predicate<Pred const, std::ranges::iterator_t<V>> class drop_last_while_view : public std::ranges::view_interface<drop_last_while_view<V, Pred>> { public: constexpr drop_last_while_view() requires std::default_initializable<V> and std::default_initializable<Pred> : _begin{std::ranges::begin(V{})} , _end{std::ranges::end(V{})} {} constexpr drop_last_while_view(V base, Pred pred) requires std::ranges::bidirectional_range<V> : _begin{std::ranges::begin(base)} , _end{std::ranges::end(base)} { while ((_end != _begin) and std::invoke(pred, *std::ranges::prev(_end))) --_end; } // Forward iterator version left as an exercise for the reader! //constexpr drop_last_while_view(V base, Pred pred) { ??? } constexpr auto begin() const { return _begin; } constexpr auto end() const { return _end; }
{ "domain": "codereview.stackexchange", "id": 45313, "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++, strings, c++20", "url": null }
c++, strings, c++20 constexpr auto begin() const { return _begin; } constexpr auto end() const { return _end; } private: std::ranges::iterator_t<V> _begin; std::ranges::iterator_t<V> _end; }; template <typename R, typename Pred> drop_last_while_view(R&&, Pred) -> drop_last_while_view<std::views::all_t<R>, Pred>; Same idea for drop_suffix_view. Then your function is: auto rtrim(std::string& str, std::string_view pattern) -> std::string& { auto const is_space = [](auto c) { return std::isspace(c); } auto const v1 = drop_last_while_view{str, is_space}; auto const v2 = drop_suffix_view{v1, pattern}; auto const v3 = drop_last_while_view{v2, is_space}; str.resize(std::ranges::size(v3)); return str; } If you make a constexpr is_space, then you can make the whole thing constexpr. Now, if you’re asking how to write this using only existing views and range adaptors… well, then you’ve more or less got the gist of it. There will necessarily be a lot of reversing and un-reversing, because none of the standard views or range adaptors work on the end of a range. You kinda “cheat” in the middle by not using a view to remove the suffix… I mean, if you’re going to do that, then you could do the whole operation without ranges or views and just operate on the string directly. So here’s how I’d do it in all C++20 ranges/views, no cheating: auto rtrim(std::string& str, std::string_view pattern) -> std::string& { auto const is_space = [](auto c) { return std::isspace(c); }; auto view = str | std::views::reverse | std::views::drop_while(is_space) | std::views::reverse ; str.resize(std::ranges::size(view)); auto const pattern_size = std::ranges::size(pattern);
{ "domain": "codereview.stackexchange", "id": 45313, "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++, strings, c++20", "url": null }
c++, strings, c++20 str.resize(std::ranges::size(view)); auto const pattern_size = std::ranges::size(pattern); if (std::ranges::equal(str | std::views::reverse | std::views::take(pattern_size), pattern | std::views::reverse)) { auto view = str | std::views::reverse | std::views::drop(pattern_size) | std::views::drop_while(is_space) | std::views::reverse ; str.resize(std::ranges::size(view)); } return str; } But, IMO, this is silly. Compare that to what you’d get if you made the necessary views, like I showed above. And compare it to what you could if you could write your own range adaptors: // With only custom views (C++20): auto rtrim(std::string& str, std::string_view pattern) -> std::string& { auto const is_space = [](auto c) { return std::isspace(c); } auto const v1 = drop_last_while_view{str, is_space}; auto const v2 = drop_suffix_view{v1, pattern}; auto const v3 = drop_last_while_view{v2, is_space}; str.resize(std::ranges::size(v3)); return str; } // With custom range adaptors (C++23): auto rtrim(std::string& str, std::string_view pattern) -> std::string& { auto const is_space = [](auto c) { return std::isspace(c); } auto view = str | drop_last_while(is_space) | drop_suffix(pattern) | drop_last_while(is_space) ; str.resize(std::ranges::size(view)); return str; }
{ "domain": "codereview.stackexchange", "id": 45313, "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++, strings, c++20", "url": null }
c++, strings, c++20 str.resize(std::ranges::size(view)); return str; } That is what range-based code is supposed to look like. You just can’t do that with standard views or range adaptors in C++20, and without C++23 you can’t even get all the way to the last example at all. One more thing to note: because you are modifying the string you were passed, you aren’t really getting into the full “vibe” of ranges. To really grok ranges, you have to think in terms of returning views—either sub-views or modified views or both—not modifying ranges directly. So if I were really doing this fully-range-flavoured, I would basically make a function that looks more like this: auto rtrim(std::string_view str, std::string_view pattern) { auto const is_space = [](auto c) { return std::isspace(c); } auto view = str | drop_last_while(is_space) | drop_suffix(pattern) | drop_last_while(is_space) ; return std::string_view{view}; } And then I would rework that as a range adaptor, so I could write: auto result = test.input | rtrim(test.pattern); Ranges/views are not really the best way to write library code However, that’s all nice and sexy, and if I were writing that operation quick-and-dirty, that would be fine. But if I were implementing this operation as a library function… it could be better. This is often true for range-based code. It’s great at the application level, or for one-time problem solving. It’s not always great for stuff that needs to be tight, like high-performance or library code. Let’s look again at the “ideal” code: auto rtrim(std::string_view str, std::string_view pattern) { auto const is_space = [](auto c) { return std::isspace(c); } auto view = str | drop_last_while(is_space) | drop_suffix(pattern) | drop_last_while(is_space) ; return std::string_view{view}; }
{ "domain": "codereview.stackexchange", "id": 45313, "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++, strings, c++20", "url": null }
c++, strings, c++20 return std::string_view{view}; } So, first we do the drop_last_while to remove trailing whitespace, if any. That’s fine; it’s about as ideal as we can get. Then we drop the suffix, if any. Again, this is as ideal as it’s going to get. But then we do the drop_last_while to remove trailing whitespace again, and here’s the rub: if we didn’t drop the suffix, we don’t need to do this. So, for the best performance, we’d want something more like: auto rtrim(std::string_view str, std::string_view pattern) { auto const is_space = [](auto c) { return std::isspace(c); } auto view = std::string_view{str | drop_last_while(is_space)}; if (view.ends_with(pattern)) { view = std::string_view{ view | drop_last(std::ranges::size(pattern)) | drop_last_while(is_space) }; } return view; }
{ "domain": "codereview.stackexchange", "id": 45313, "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++, strings, c++20", "url": null }
c++, strings, c++20 return view; } But even this isn’t perfect, because there is still unnecessary/duplicated work being done. To do the ends_with check we have to read the pattern and figure out its size… but then we need to do that again for the drop_last (which isn’t a standard view, just in case that isn’t clear). To really make this routine as efficient as it possibly can be, you pretty much have to toss out ranges, and work with iterators. You get the end iterator, and keep moving it backwards for each phase of the transformation. So long as you keep track of that iterator, you won’t need to do any unnecessary work. So, what I’m saying is: ranges-based code is fine and good for one-and-done stuff, high-level-logic, and application code. But when you really need the highest performance, the lowest memory usage… just the maximum of efficiency in general… ranges will often not be your friend. It’s the classic trade-off: do you want clear, high-level code… or do you want high-performance code. Ranges do a spectacular job of letting you eat your cake and have it, too… but not a perfect job. If your rtrim() function is not meant to be library code, intended to be the best implementation to give users the highest performance, then ranges are fine. Otherwise… you might have to ditch the sexy ranges and get low-level dirty. The lurking bug Even with the ideal C++23 ranges code, there is still one dangerous thing to watch out for. And this is something you almost do in your own code. More on that in the review, though. Consider this: auto str = std::string{"whatever"}; str = str | rtrim("pattern");
{ "domain": "codereview.stackexchange", "id": 45313, "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++, strings, c++20", "url": null }
c++, strings, c++20 Now, the right-hand side of the assignment creates a view into the character data of str. Which you then assign to str. In other words, you are assigning the character data of a string—or some part of its character data—to itself. In essence: str.assign(str.begin(), str.end()), or std.assign(str.begin() + n, str.end() - m) assuming n + m <= str.size(). That will result in implementation-defined behaviour, because you can’t know what order the characters of the string will be assigned over itself. In fact, there are a lot of things the string could technically do that would break your assumptions. For example, the string may allocate a new buffer, then delete the old buffer, then copy the characters but oh no now it’s copying from freed memory. Granted, I know that at least libstdc++ and libc++ behave as you’d expect when copying a string’s data over itself (at least I think I know that… it’s been many versions since I check). And I’ve seen some debate among experts about whether it is supposed to work. All I can say for certain is this: std::string does not explicitly guarantee this will work. So a conforming implementation does not have to make it work. As a general rule, I would say that if you modify a container while holding a view of it, you are almost always doing something wrong. That is why, in my rewrites of your code (see the “no cheating” version above in particular), I am very careful not to assign to the string. I use resize() instead. And I abandon/remake any views after I’ve modified the string. You don’t actually trigger this bug in your code… but only because you do something silly. I’ll get to that in the review. Code review std::string& rtrim(std::string& str, const std::string_view pattern)
{ "domain": "codereview.stackexchange", "id": 45313, "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++, strings, c++20", "url": null }
c++, strings, c++20 So, your function modifies the string… and returns a reference to it. I’m not a fan of that kind of interface. If a function takes reference parameters and modifies them, it should either return a different “thing” (like an error code or something), or void. It should not return the reference it’s modifying. At the very least, this creates confusion: without consulting the documentation, a user won’t know if they are supposed to assign the return value or not, and they might accidentally modify a string they didn’t intend to because they thought only the return value is modified. A better idea would be to embrace modern design principles and never modify arguments. In other words: auto rtrim(std::string str, const std::string_view pattern) -> std::string This can be just as efficient as passing references around, if you use moves. Instead of: auto str = "some string with a suffix"s; auto&& trimmed = rtrim(str, "suffix"); // Now, without knowing the function, riddle me this: // 1. Is str unchanged? // 2. Is trimmed a reference to str? // // How can I know that str will not be corrupted if I change trimmed? // How can I know that trimmed will not be corrupted if I change str? you do: auto str = "some string with a suffix"s; auto&& trimmed = rtrim(std::move(str), "suffix"); // Just the addition of the move() sends a clear signal: trimmed cannot be // a reference to str (or at least, it would be idiotic if it were, because // str was passed as an rvalue). // // So I can safely do anything I want with str, and trimmed will be // unaffected. And vice versa. or: auto const str = "some string with a suffix"s; auto&& trimmed = rtrim(str, "suffix");
{ "domain": "codereview.stackexchange", "id": 45313, "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++, strings, c++20", "url": null }
c++, strings, c++20 or: auto const str = "some string with a suffix"s; auto&& trimmed = rtrim(str, "suffix"); // The const sends a different signal. Even if trimmed is a reference to str, // there is no fear of causing corruption by inadvertently modifying str // via trimmed. And since str is const, there is no fear of trimmed being // modified either. // // So again, without even looking at the docs, I know that neither str nor // trimmed are in danger of being corrupted by spooky action at a distance. Of course, you could write: auto str = "some string with a suffix"s; auto&& trimmed = rtrim(str, "suffix"); and end up with the original uncertainty. But that would be your fault. If you want the uncertainty to go away, you just need to write better code, either by making str const (or using std::as_const()), or moving it. But you can’t write that better code with the original interface. That’s why it’s a bad interface. For maximum performance, you might want to write some overloads: auto rtrim(std::string&& str, std::string_view pattern) -> std::string { // Basically your function now, except with return std::move(str); } auto rtrim(std::string const& str, std::string_view pattern) -> std::string { return rtrim(std::string{str}, pattern); } You may also want to have a second function that works with views: auto rtrim_view(std::string_view, std::string_view) -> std::string_view; You could write the non-view function in terms of the view function. Just run the view function, get the size of the view, and use the resize() trick (in the rvalue case; in the lvalue case, you can just construct a new string from the view). str = {view.begin(), view.end()};
{ "domain": "codereview.stackexchange", "id": 45313, "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++, strings, c++20", "url": null }
c++, strings, c++20 Do you realize what you’re doing here is creating an entire second string, copying part of first string into it, then copying that back into the original string? There is no reason to create an entire second temporary string when you’re literally just copying some part the original string’s contents back into it. All you need to do is tell either the original what part(s) to keep, or what part(s) to drop. Now, I mentioned the lurking bug above, and how you almost trigger it, but not quite. This is because you copy the character data from str to a new string… then copy that new string’s (identical) character data back to str. Which is silly. But, by blind luck it avoids the problem of copying str’s own data directly into itself. A naïve solution would be to use a string view: str = std::string_view{view.begin(), view.end()}; But that would trigger the bug. Without that extra string as an intermediary, you are copying a string’s data back into itself. There is no need to copy anything at all. The data you want is already in str. You just need to get rid of all the other crud. You know where the data you want is in str, too. Because you only trimmed from the end, the data you want is [str.begin(), str.begin() + ???), where ??? is the size of the view. You don’t need the contents of the view; they’re already in str. You just need to know its size. Thus: str.resize(view.size()); Which transforms str’s contents to [str.begin(), str.begin() + view.size())… which is what you want. No need for extra strings. No dangerous lurking bugs. Simple. Fast. if (str.ends_with(pattern)) { str.erase(str.size() - pattern.size(), pattern.size()); } auto view2 = str | std::views::reverse | std::views::drop_while([](char x){ return std::isspace(x); }) | std::views::reverse ;
{ "domain": "codereview.stackexchange", "id": 45313, "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++, strings, c++20", "url": null }
c++, strings, c++20 If str does not end with pattern, there is no need to do the second run of the whitespace trimming. So why not: auto rtrim(std::string& str, std::string_view const pattern) -> std::string& { auto view = str | std::views::reverse | std::views::drop_while([](char x){ return std::isspace(x); }) | std::views::reverse ; str = {view.begin(), view.end()}; // should use resize() if (str.ends_with(pattern)) { str.erase(str.size() - pattern.size(), pattern.size()); auto view2 = str | std::views::reverse | std::views::drop_while([](char x){ return std::isspace(x); }) | std::views::reverse ; str = {view2.begin(), view2.end()}; // should use resize() } return str; } You should have noticed that you’re doing the whitespace right trim twice. That’s a function! auto rtrim(std::string& str) -> std::string& { auto view = str | std::views::reverse | std::views::drop_while([](char x){ return std::isspace(x); }) | std::views::reverse ; str = {view.begin(), view.end()}; // should use resize() return str; } auto rtrim(std::string& str, std::string_view const pattern) -> std::string& { rtrim(str); if (str.ends_with(pattern)) { str.erase(str.size() - pattern.size(), pattern.size()); rtrim(str); } return str; } Finally: return str = {view2.begin(), view2.end()}; There is no benefit to cramming operations together like this. There are two distinct logical operations here: an assignment to str, and a return statement. They should be on two distinct lines. That’s all! Have a good one!
{ "domain": "codereview.stackexchange", "id": 45313, "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++, strings, c++20", "url": null }
timer, swiftui Title: Moving Timer from a View to a ViewModeller-class? Question: I have a Timer in my View right now, but I want to move it outside to my ViewModel-class. I have experimented a bit and came up with a working solution. The code works and produces expected output, however I'm not sure if I have done everything in a proper way, so I would like some input on my code. Would you do it in another way? Is it better to have the Timer in the view and call viewModel.fetchData() in a .onRecieve()-modifier? I still haven't decided on the layout of my final app. It will either be a TabView or a NavigationView and I want the timer to fetch data no matter in which subview I'm in at the moment. Maybe putting the timer and fetch-function in the view model is completely wrong (should it be in the model?). I'm feeling a bit lost with the MVVM-pattern. I'm also not very familiar with the Combine-framework, as you may see in the code. The purpose of the code is to fetch data every n minute (in my code I check every second to speed things up for testing). If data is available I want to add it to a @Published property (simulating this by adding data every 5:th second). This is my view: import SwiftUI struct ContentView: View { @StateObject var vm = ViewModel() var body: some View { VStack { List(vm.items, id: \.self) { item in Text(item) } } .padding() } } And my ViewModel: import Foundation import Combine
{ "domain": "codereview.stackexchange", "id": 45314, "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": "timer, swiftui", "url": null }
timer, swiftui And my ViewModel: import Foundation import Combine @MainActor final class ViewModel: ObservableObject { @Published var items: [String] = [] private let timer: Publishers.Autoconnect<Timer.TimerPublisher>? private var cancellable: AnyCancellable? init() { timer = Timer.TimerPublisher(interval: 1, runLoop: .main, mode: .default).autoconnect() self.startTimer() } private func fetchData(_ timerInterval: TimeInterval) async throws { print("timer fired") let ts = UInt32(timerInterval) if ts % 5 == 0 { print("New data available") items.append("Item \(ts)") } } private func startTimer() { cancellable = timer?.sink { [weak self] t in Task { try! await self?.fetchData(t.timeIntervalSince1970) } } } deinit { cancellable?.cancel() } } Answer: On the broader question of whether the timer should be pulled out of the view, itself, I would tend to agree. It begs the question, though, whether it really belongs in a view model, either. If this “try every five minutes” really is tied to this view, then fine, the view model is a reasonable choice. But, I wonder if it might better located to some broader network/api service object, not the view model. It depends upon whether this “try every five minutes” logic is really unique to this view and should only be performed while this view is presented, or whether it is something that the app might be trying whether this particular view was presented or not. Setting that aside, a couple of tactical observations in your code snippet: You do not need to save the timer publisher, itself. You only need the cancellable produced by sink. You do not need to cancel on deinit. When the cancellable falls out of scope, it cancels the publisher for you.
{ "domain": "codereview.stackexchange", "id": 45314, "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": "timer, swiftui", "url": null }
timer, swiftui You never want to use try! unless you know, for a fact, that it can never fail; i.e., you never want your app crash just because a network request fails. As a stylistic matter, I really like putting private implementation methods in a separate extension. It affords better code folding, a more easily understood Xcode jump bar, and logical segregation of methods. This is largely a matter of opinion, but I would do not start asynchronous tasks in the init of the view model, but rather have the view launch it (say, in its .task view modifier). I would also advise either sticking with Combine (e.g., use TimerPublisher, but then use URLSession dataTaskPublisher) or adopt Swift concurrency (e.g., use AsyncTimerSequence and then the async URLSession method data(from:delegate:) or data(for:delegate:)) E.g., a Swift concurrency rendition might look like: import Foundation import AsyncAlgorithms @MainActor final class ViewModel: ObservableObject { @Published private(set) var products: [Product] = [] @Published private(set) var error: Error? func startTimer() async { for await _ in AsyncTimerSequence(interval: .seconds(5), clock: .continuous) { do { products = try await productsFromNetwork() } catch { self.error = error } } } } // MARK: - Private implementation extension ViewModel { func productsFromNetwork() async throws -> [Product] { let url = URL(string: "https://dummyjson.com/products")! let (data, _) = try await URLSession.shared.data(from: url) let payload = try JSONDecoder().decode(ProductsResponse.self, from: data) return payload.products } } Technically, one can mix and match Combine and Swift concurrency, but it feels a bit muddled. I might advise picking one tech stack or the other. (I personally gravitate to Swift concurrency, nowadays.)
{ "domain": "codereview.stackexchange", "id": 45314, "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": "timer, swiftui", "url": null }
timer, swiftui Not that it is terribly relevant, but this is the model I used for that dummyjson.org endpoint: // MARK: - ProductsResponse struct ProductsResponse: Decodable { let products: [Product] let total, skip, limit: Int } // MARK: - Product struct Product: Decodable, Identifiable, Hashable { let id: Int let title, description: String let price: Int let discountPercentage, rating: Double let stock: Int let brand, category: String let thumbnail: String let images: [String] } And this was the View: struct ContentView: View { @StateObject var viewModel = ViewModel() var body: some View { VStack { if let error = viewModel.error { Text(error.localizedDescription) } List(viewModel.products) { product in Text(product.description) } } .padding() .task { await viewModel.startTimer() } } }
{ "domain": "codereview.stackexchange", "id": 45314, "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": "timer, swiftui", "url": null }
java, algorithm, sudoku Title: Generic Algorithm X implementation with dancing links (DLX) Question: This is a generic implementation of Knuth's "Algorithm X" using dancing links. The whole code with a "mandatory" sudoku solver can be found at gitlab. Regarding the scope of the review, I am an experienced programmer and I think I "should" know what I am doing, therefore you should not consider any issue to be too small to mention. If you are a less experienced programmer and don't understand something in the code, that means the code is not good enough and you should consider bring it up. The Code In order to separate the constraint generation from the algorithm itself, the implementation uses a ColumnMapper. The column mapper provides the constraints that each value has. For example, in a sudoku solver the value would be "placing number 1 at column 3 in row 5" and the mapper returns the columns for constraints imposed by the sudoku column, row and box restrictions. package fi.iki.asb.wheel.algorithm.dlx; /** * Interface for mapping a value that represents a row in the * DLX matrix to indexes of columns where the value has constraints. */ @FunctionalInterface public interface ColumnMapper<T> { /** * Get indexes of columns where the given value has constraints. * After all rows have been added to the DLX matrix, the column * indexes must form a single continuous series where all * columns have at least one constraint. * * @return Unique set of integers, sorted in ascending order. */ int[] from(T rowValue); }
{ "domain": "codereview.stackexchange", "id": 45315, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, sudoku", "url": null }
java, algorithm, sudoku } The algorithm itself provides two public methods: addRow(...) for adding rows to the matrix and search(...) for searching for the solution. The search method requires a consumer that is used to deliver results to the caller and provides an option for an "emergecy brake" that can be used to stop the algorithm before it has completed the execution. Please note that the abstract data types used are not part of the review. You should consider them to work as a data structure bearing it's name should. I may post a separate review for those later. package fi.iki.asb.wheel.algorithm.dlx; import fi.iki.asb.wheel.adt.IndexedCollection; import fi.iki.asb.wheel.adt.Set; import fi.iki.asb.wheel.adt.impl.ArrayBackedList; import fi.iki.asb.wheel.adt.impl.HashSet; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import fi.iki.asb.wheel.adt.RandomAccessCollection; /** * Generic implementation of Knuth's Algorithm X using dancing links. * * <p>This class is <i>not</i> thread safe.</p> * * @param <T> The type associated to constraints. */ public class DLX<T> { /** * A constraint node in the matrix. */ private class Node { final Column column; final T value; Node up, down, left, right; Node(Column column, T value) { this.column = column; this.value = value; up = down = left = right = this; } } /** * Column header in the matrix. */ private class Column extends Node { /** * Number of nodes in this column. */ int size = 0; public Column() { super(null, null); } } // =================================================================== // private final ColumnMapper<T> columnMapper; private final Column head; private final ArrayBackedList<Column> columns;
{ "domain": "codereview.stackexchange", "id": 45315, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, sudoku", "url": null }
java, algorithm, sudoku private final Column head; private final ArrayBackedList<Column> columns; public DLX(ColumnMapper<T> columnMapper) { this.columnMapper = columnMapper; this.columns = new ArrayBackedList<>(); head = new Column(); } // =================================================================== // // Matrix initialization code. /** * Add a row with the given value. */ public void addRow(T value) { // Needed to link nodes horizontally. Node previousNode = null; // Get relevant columns from the mapper. final int[] columns = columnMapper.from(value); for (int columnIndex: columns) { final Column column = getOrCreateColumn(columnIndex); final Node newNode = new Node(column, value); // Add new node to the column. newNode.down = column; newNode.up = column.up; column.up.down = newNode; column.up = newNode; column.size++; // Add new node to the row. if (previousNode != null) { newNode.right = previousNode; newNode.left = previousNode.left; previousNode.left.right = newNode; previousNode.left = newNode; } previousNode = newNode; } } /** * Create a new column with the given index. If the matrix does not yet * contain all columns preceding <code>columnIndex</code>, the missing * columns will be created. * * @param columnIndex Zero indexed column index. */ private Column getOrCreateColumn(int columnIndex) { while (columns.size() <= columnIndex) { final Column newColumn = new Column(); newColumn.left = head.left; newColumn.right = head; head.left.right = newColumn; head.left = newColumn; columns.add(newColumn); }
{ "domain": "codereview.stackexchange", "id": 45315, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, sudoku", "url": null }
java, algorithm, sudoku return columns.get(columnIndex); } // =================================================================== // // The DLX solution. /** * Search for exact cover solution with no emergency brake. */ public void search( RandomAccessCollection<T> initialSolution, Consumer<RandomAccessCollection<T>> solutionConsumer) { search(initialSolution, solutionConsumer, () -> false); } /** * Search for exact cover solution. * * @param initialSolution The row values that are known to be part * of the solution (for example the initial * numbers given in a sudoku puzzle). Can be * empty. * @param solutionConsumer The consumer which collects the results. * @param emergencyBrake A boolean supplier which is periodically * checked to prevent runaway execution. When * this supplier returns true, the execution * is stopped as soon as possible. This can be * used, for example, in conjunction with the * solutionConsumer to stop execution as soon * as a solution is found or to check if runtime * limit has been exceeded. */ public void search( RandomAccessCollection<T> initialSolution, Consumer<RandomAccessCollection<T>> solutionConsumer, BooleanSupplier emergencyBrake) { // Find the distinct set of columns that have constraints // that conflict with the initial solution and cover them. final IndexedCollection<Integer> hiddenColumns = collectHiddenColumns(initialSolution); for (int i = 0; i < hiddenColumns.size(); i++) { Column column = columns.get(hiddenColumns.get(i)); cover(column); }
{ "domain": "codereview.stackexchange", "id": 45315, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, sudoku", "url": null }
java, algorithm, sudoku final IndexedCollection<T> solution = new ArrayBackedList<>(); solution.addAll(initialSolution); recursiveSearch(solution, solutionConsumer, emergencyBrake); // Uncover the initial hidden columns in reverse order to // restore the matrix to original state. for (int i = hiddenColumns.size() - 1; i >= 0; i--) { Column column = columns.get(hiddenColumns.get(i)); uncover(column); } } private void recursiveSearch( IndexedCollection<T> solution, Consumer<RandomAccessCollection<T>> solutionConsumer, BooleanSupplier emergencyBrake) { // If there are no uncovered columns, the list contains a solution. if (head.right == head) { solutionConsumer.accept(solution); return; } if (emergencyBrake.getAsBoolean()) { return; } // Select and cover column. final Column column = findColumn(); cover(column); // For each row that has a constraint in this column, add the // row value to the result, cover all columns that are in conflict // with this row constraint and recurse. for (Node n0 = column.down; n0 != column; n0 = n0.down) { solution.add(n0.value); for (Node n1 = n0.right; n1 != n0; n1 = n1.right) { cover(n1.column); } recursiveSearch(solution, solutionConsumer, emergencyBrake); // Uncover changes made before recursion. for (Node n1 = n0.left; n1 != n0; n1 = n1.left) { uncover(n1.column); } solution.removeAt(solution.size() - 1); if (emergencyBrake.getAsBoolean()) { break; } } uncover(column); } private void cover(Column column) { column.left.right = column.right; column.right.left = column.left;
{ "domain": "codereview.stackexchange", "id": 45315, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, sudoku", "url": null }
java, algorithm, sudoku for (Node i = column.down; i != column; i = i.down) { for (Node j = i.right; j != i; j = j.right) { j.down.up = j.up; j.up.down = j.down; j.column.size--; } } } private void uncover(Column column) { for (Node i = column.up; i != column; i = i.up) { for (Node j = i.left; j != i; j = j.left) { j.column.size++; j.down.up = j; j.up.down = j; } } column.right.left = column; column.left.right = column; } /** * Find an uncovered column with the smallest non-zero number of * constraints. */ private Column findColumn() { Column smallest = null; Column candidate = (Column) head.right; while (candidate != head) { if (candidate.size == 0) { continue; } if (candidate.size == 1) { return candidate; } if (smallest == null || smallest.size > candidate.size) { smallest = candidate; } candidate = (Column) candidate.right; } return smallest; } /** * Collect hidden columns from the initial solution. */ private IndexedCollection<Integer> collectHiddenColumns( RandomAccessCollection<T> initialSolution) { // Gather columns that should be hidden. final Set<Integer> temp = new HashSet<>(); initialSolution.forEach(t -> { for (int columnIndex: columnMapper.from(t)) { temp.put(columnIndex); } return true; }); final IndexedCollection<Integer> hiddenColumns = new ArrayBackedList<>(temp.size()); hiddenColumns.addAll(temp); return hiddenColumns; } }
{ "domain": "codereview.stackexchange", "id": 45315, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, sudoku", "url": null }
java, algorithm, sudoku Answer: // If there are no uncovered columns, the list contains a solution. if (head.right == head) { solutionConsumer.accept(solution); return; } Having a dummy column header for the "header of the whole matrix" is completely normal in DLX, but it's easy to forget at this point in the code that that's what's going on. That could be noted here (and in findColumn where starting at head.right looks mysterious without this context). I noticed that findColumn ignores/skips columns with a size of zero. Encountering an empty column means that the current problem is unsoveable, so I expected that condition to be detected and reported to recursiveSearch so that it can backtrack, rather than recurse into subproblems that will also be unsolveable. findColumn can also return null if there is no non-empty column, and recursiveSearch does not handle that gracefully. It seems to me that you can remove the special case for size == 0, then findColumn would return an empty column if one exists, and recursiveSearch does handle that. cover and uncover are unexplained, those node manipulations may not be obvious to the general public.
{ "domain": "codereview.stackexchange", "id": 45315, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, sudoku", "url": null }
python, numpy Title: Covariance of random variables of Dirichlet distribution Question: I don't find an implementation in the library I work with of covariance function: I give a try at implementing it in Python: import numpy as np def covariance_dirichlet(X,alpha): cov_list = [] sigma = np.sum(alpha) for i in range(0,len(X)): for j in range(i+1,len(X)): if i == j: iter_val_num = np.multiply(X[i],sigma)-np.power(X[i],2)#**2 else: iter_val_num = -np.multiply(X[i],X[j])#a*b iter_res = iter_val_num/(sigma**2)*(sigma+1) cov_list.append(iter_res) return np.reshape(np.array(cov_list),(-1,len(X))) print(covariance_dirichlet([[0.2, 0.2, 0.6,0.8],[0.2, 0.2, 0.6,0.8]],[0.4, 5, 15,11])) Does this look right? Can it be simplified? Answer: Does this look right? No, for a few reasons. Primarily, X doesn't actually appear in the definition for the equation, so it doesn't make any sense to pass it into your function. Also, *(sigma+1) is on the wrong side of the quotient. Can it be simplified? Yes. Perform fundamental Numpy vectorisation. import numpy as np def covariance_dirichlet_slow(alpha: np.ndarray) -> np.ndarray: sigma = alpha.sum() n = alpha.size cov = np.empty((n, n)) for j in range(n): for k in range(n): if j == k: iter_val_num = alpha[j]*sigma - alpha[j]**2 else: iter_val_num = -alpha[j]*alpha[k] iter_res = iter_val_num / sigma**2 / (1 + sigma) cov[j, k] = iter_res return cov def covariance_dirichlet_fast(alpha: np.ndarray) -> np.ndarray: sigma = alpha.sum() alpha_coef = alpha/(sigma**2 * (1 + sigma)) diag = np.diag(alpha_coef*sigma) square = np.outer(alpha_coef, alpha) return diag - square
{ "domain": "codereview.stackexchange", "id": 45316, "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, numpy", "url": null }
python, numpy def test() -> None: alpha = np.array((0.4, 5, 15, 11)) expected = np.array([ [ 3.88165899e-04, -6.26074030e-05, -1.87822209e-04, -1.37736287e-04], [-6.26074030e-05, 4.13208860e-03, -2.34777761e-03, -1.72170358e-03], [-1.87822209e-04, -2.34777761e-03, 7.70071057e-03, -5.16511075e-03], [-1.37736287e-04, -1.72170358e-03, -5.16511075e-03, 7.02455062e-03], ]) actual_slow = covariance_dirichlet_slow(alpha) actual_fast = covariance_dirichlet_fast(alpha) assert np.allclose(expected, actual_slow, atol=0, rtol=1e-8) assert np.allclose(expected, actual_fast, atol=0, rtol=1e-8) if __name__ == '__main__': test()
{ "domain": "codereview.stackexchange", "id": 45316, "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, numpy", "url": null }
python, python-3.x, programming-challenge Title: Finding the number of "block chains" that are a certain length and begin with a certain string Question: I'm currently practicing for the british informatics olympiad by doing past papers. I was doing question 3 of the 2019 paper: A set of children’s blocks, each illustrated with a single different letter, have been chained together in a line. They have been arranged so that it is not possible to find three (not necessarily adjacent) letters,from left to right, that are in alphabetical order. Write a program that enumerates block-chains. Your program should input a single integer l (1 ≤ l ≤ 19) indicating that the blocks are illustrated with the first l letters of the alphabet, followed by a word p of between 1 and l uppercase letters indicating (in order) the leftmost letters of the block chain. p will only contain letters take from the first l letters of the alphabet and will not contain any duplicates. You should output a single integer giving the number of possible block-chains that begin with p. I wrote this code for the question: from itertools import permutations from string import ascii_uppercase def has_alphabetical_substring(s): for i in range(len(s)): for j in range(i + 1, len(s)): if ascii_uppercase.index(s[i]) > ascii_uppercase.index(s[j]): continue for k in range(j + 1, len(s)): if ascii_uppercase.index(s[j]) <= ascii_uppercase.index(s[k]): return True return False def find_legal_block_chains(l, p): combinations = list(permutations(ascii_uppercase[:l], l)) combinations = [combination for combination in combinations if all(combination[i] == p[i] for i in range(len(p)))] combinations = [combination for combination in combinations if not has_alphabetical_substring(combination)] return combinations l, p = input().split() print(len(find_legal_block_chains(int(l), p.upper())))
{ "domain": "codereview.stackexchange", "id": 45317, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, programming-challenge", "url": null }
python, python-3.x, programming-challenge l, p = input().split() print(len(find_legal_block_chains(int(l), p.upper()))) For example, if I input 4 CB, it prints 2. More tests which are required to pass can be found on the relevant marks page. I have tested it against the test cases in the run scheme, and it works, but it's slow and inefficient. I would be grateful to know any improvements that I could make to this program. Answer: Some changes that make your approach a bit better: You do not need the intermediate list of all possible combinations, you throw most of them away again anyway. You can use generator expressions instead, conserving huge amounts of memory: def find_legal_block_chains(l, p): combinations = permutations(ascii_uppercase[:l], l) combinations = ( combination for combination in combinations if all(combination[i] == p[i] for i in range(len(p))) ) combinations = ( combination for combination in combinations if not has_alphabetical_substring(combination) ) return list(combinations) The prefix is fixed. So there is no need to generate all length l possible block-chains only to throw away all of those which do not start with the prefix. Instead, add the prefix later. Also, you can special case len(p) == l: def find_legal_block_chains(l, p): if len(p) == l: return [(p,)] combinations = permutations(set(ascii_uppercase[:l]) - set(p), l - len(p)) combinations = ( tuple(p) + combination for combination in combinations if not has_alphabetical_substring(tuple(p) + combination) ) return list(combinations) Avoid making repeated lookups in string.ascii_uppercase, instead pre-compute a lookup table. Also, iterate over the characters instead of always using indexing: ASCII_TO_INDEX = {c: i for i, c in enumerate(ascii_uppercase)}
{ "domain": "codereview.stackexchange", "id": 45317, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, programming-challenge", "url": null }
python, python-3.x, programming-challenge ASCII_TO_INDEX = {c: i for i, c in enumerate(ascii_uppercase)} def has_alphabetical_substring(s): for i, c1 in enumerate(s): for j, c2 in enumerate(s[i + 1:], i + 1): if ASCII_TO_INDEX[c1] > ASCII_TO_INDEX[c2]: continue for c3 in s[j + 1:]: if ASCII_TO_INDEX[c2] <= ASCII_TO_INDEX[c3]: return True While this does speed up the runtime quite a bit, this is most notable if the prefix is longer. Runtimes on my machine for the first ten testcases: OP: 107 ms ± 1.34 ms generators: 108 ms ± 508 µs prefix: 23.5 ms ± 170 µs lookup table: 8.57 ms ± 41.2 µs And for the tenth test case ("12 LKJI", 1430): OP: OutOfMemoryError generator: > 1 min prefix: 448 ms ± 4.76 ms lookup table: 137 ms ± 1.08 ms All test cases, for reference: test = [ ("1 A", 1), ("2 AB", 1), ("2 BA", 1), ("4 C", 5), ("4 AB", 0), ("6 FED", 5), ("8 HGFEDCBA", 1), ("8 H", 429), ("8 FED", 28), ("8 FEH", 42), ("12 LKJI", 1430), ("13 MH", 13260), ("14 N", 742900), ("16 KHF", 5508), ("16 FEDCBA", 1), ("18 FRN", 0), ("18 QPON", 2674440), ("18 R", 129644790) ] The real solution to this problem is probably not found by optimizing this approach further, but by using combinatorics. E.g. there are \$l!\$ possible ways to arrange \$l\$ distinct letters, from which you then have to somehow subtract the illegal combinations. A possible approach is to start asking yourself how many possibilities there are in the case where only one letter is not covered by the prefix and try to expand it from there.
{ "domain": "codereview.stackexchange", "id": 45317, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, programming-challenge", "url": null }
algorithm, c, reinventing-the-wheel, image, numerical-methods Title: Two dimensional bicubic interpolation implementation in C Question: This is a follow-up question for Two dimensional bicubic interpolation implementation in Matlab and Two dimensional gaussian image generator in C. Besides the Matlab version code, I am attempting to make a C version two dimensional bicubic interpolation function BicubicInterpolation here. The experimental implementation BicubicInterpolation function implementation: RGB* BicubicInterpolation(const RGB* const image, const int originSizeX, const int originSizeY, const int newSizeX, const int newSizeY) { RGB* output; output = malloc(sizeof *output * newSizeX * newSizeY); if (output == NULL) { printf(stderr, "Memory allocation error!"); return NULL; } float ratiox = (float)originSizeX / (float)newSizeX; float ratioy = (float)originSizeY / (float)newSizeY; for (size_t y = 0; y < newSizeY; y++) { for (size_t x = 0; x < newSizeX; x++) { for (size_t channel_index = 0; channel_index < 3; channel_index++) { float xMappingToOrigin = (float)x * ratiox; float yMappingToOrigin = (float)y * ratioy; float xMappingToOriginFloor = floor(xMappingToOrigin); float yMappingToOriginFloor = floor(yMappingToOrigin); float xMappingToOriginFrac = xMappingToOrigin - xMappingToOriginFloor; float yMappingToOriginFrac = yMappingToOrigin - yMappingToOriginFloor;
{ "domain": "codereview.stackexchange", "id": 45318, "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": "algorithm, c, reinventing-the-wheel, image, numerical-methods", "url": null }
algorithm, c, reinventing-the-wheel, image, numerical-methods unsigned char* ndata; ndata = malloc(sizeof *ndata * 4 * 4); if (ndata == NULL) { printf(stderr, "Memory allocation error!"); return NULL; } for (int ndatay = -1; ndatay < 2; ndatay++) { for (int ndatax = -1; ndatax < 2; ndatax++) { ndata[(ndatay + 1) * 4 + (ndatax + 1)] = image[ clip(yMappingToOriginFloor + ndatay, 0, originSizeY - 1) * originSizeX + clip(xMappingToOriginFloor + ndatax, 0, originSizeX - 1) ].channels[channel_index]; } } unsigned char result = BicubicPolate(ndata, xMappingToOriginFrac, yMappingToOriginFrac); output[ y * newSizeX + x ].channels[channel_index] = result; free(ndata); } } } return output; } The other used functions: unsigned char BicubicPolate(const unsigned char* const ndata, const float fracx, const float fracy) { float x1 = CubicPolate( ndata[0], ndata[1], ndata[2], ndata[3], fracx ); float x2 = CubicPolate( ndata[4], ndata[5], ndata[6], ndata[7], fracx ); float x3 = CubicPolate( ndata[8], ndata[9], ndata[10], ndata[11], fracx ); float x4 = CubicPolate( ndata[12], ndata[13], ndata[14], ndata[15], fracx ); float output = clip_float(CubicPolate( x1, x2, x3, x4, fracy ), 0.0, 255.0); return (unsigned char)output; } float CubicPolate(const float v0, const float v1, const float v2, const float v3, const float fracy) { float A = (v3-v2)-(v0-v1); float B = (v0-v1)-A; float C = v2-v0; float D = v1; return D + fracy * (C + fracy * (B + fracy * A)); }
{ "domain": "codereview.stackexchange", "id": 45318, "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": "algorithm, c, reinventing-the-wheel, image, numerical-methods", "url": null }