text
stringlengths
1
2.12k
source
dict
beginner, rust, emulator Title: 6502 Emulator in Rust Question: This is my first attempt at writing a "large program", and I think that I've got the foundations for the emulator down. However, as I'm still a beginner, I might have made some questionable design choices (too many functions/too verbose/inefficient and so on), so I'd like to know if I can make the code more readable and/or efficient. For now, I implemented only Immediate, Absolute, and Zero Page addressing modes, and only for LDA. I just waited to post this before going on and having to modify more code for a new design. main.rs use cpu::CPU; mod cpu; mod instruction; mod flags; fn main() { let mut cpu = CPU::new(); // values to load cpu.ram[0xA00B] = 0x0A; cpu.ram[0x00DD] = 0x80; // 0xA9 -> Load 0x80 into a // 0xAD -> Load content of 0xA00B into a // 0xA5 -> Load content of 0x00DD into a cpu.run(vec![0xA9, 0x80, 0xAD, 0x0B, 0xA0, 0xA5, 0xDD]); } β€Ž cpu.rs use crate::{instruction::{Instruction, AddrMode}, flags::{Flags, FLAGS}}; pub struct CPU { a: u8, p: Flags, pc: u16, pub ram: [u8; 0xffff], // unneeded, but it makes it harder to make mistakes + easier to format for a vector of states curr_instr: Instruction, // for printing the operative address in the log function op_addr: u16 } impl CPU { pub fn new() -> Self { CPU { a: 0, p: Flags::new(), pc: 0, ram: [0; 0xffff], curr_instr: Instruction::new(), op_addr: 0 } } // just for formatting in the print_state() function fn get_flag_str(&self, flag: FLAGS) -> &str { match flag { FLAGS::Z => { if self.p.z == true { return "T"; } else { return "F"; } } FLAGS::N => { if self.p.n == true { return "T"; } else { return "F"; } }
{ "domain": "codereview.stackexchange", "id": 43854, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, rust, emulator", "url": null }
beginner, rust, emulator _ => { return "U"; } } } pub fn print_state(&self) { println!("┏━━━━━━━━━━━━━━━━━━━━━┓"); println!("┃ CPU STATE ┃"); println!("┃ ┃"); println!("┃ REGISTERS: ┃"); println!("┃ A: {:#04X?} ┃", self.a); println!("┃ PC: {:#06X?} ┃", self.pc); println!("┃ ┃"); println!("┃ FLAGS: ┃"); println!("┃ C: {} ┃", self.get_flag_str(FLAGS::C)); println!("┃ Z: {} ┃", self.get_flag_str(FLAGS::Z)); println!("┃ I: {} ┃", self.get_flag_str(FLAGS::I)); println!("┃ D: {} ┃", self.get_flag_str(FLAGS::D)); println!("┃ V: {} ┃", self.get_flag_str(FLAGS::V)); println!("┃ N: {} ┃", self.get_flag_str(FLAGS::N)); println!("┃ ┃"); println!("┃ INSTRUCTION: ┃"); println!("┃ MNEMONIC: {} ┃", self.curr_instr.mnemonic); println!("┃ ADDR MODE: {} ┃", self.curr_instr.addr_mode.get_addr_mode_string(self.curr_instr.opcode)); println!("┃ OP ADDR: {:#06X?} ┃", self.op_addr); println!("┃ OPCODE: {:#04X?} ┃", self.curr_instr.opcode); println!("┗━━━━━━━━━━━━━━━━━━━━━┛"); } fn read_byte(&self, addr: u16) -> u8 { self.ram[addr as usize] } fn write_byte(&mut self, addr: u16, data: u8) { self.ram[addr as usize] = data } fn read_word(&self, addr: u16) -> u16 { let hi = self.read_byte(addr + 1); let lo = self.read_byte(addr); (hi as u16).wrapping_shl(8) | lo as u16 }
{ "domain": "codereview.stackexchange", "id": 43854, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, rust, emulator", "url": null }
beginner, rust, emulator (hi as u16).wrapping_shl(8) | lo as u16 } fn fetch_address(&mut self, mode: AddrMode) { match mode { AddrMode::IMM => { self.op_addr = self.pc + 1; self.pc += 2; } AddrMode::ABS => { self.op_addr = self.read_word(self.pc + 1); self.pc += 3; } AddrMode::ZPG => { self.op_addr = 0x0000 | (self.read_byte(self.pc + 1)) as u16; self.pc += 2; } } } fn execute(&mut self) { let opcode = self.read_byte(self.pc); self.curr_instr.fetch_instruction(opcode); self.fetch_address(self.curr_instr.addr_mode); match self.curr_instr.mnemonic.as_str() { "LDA" => { self.a = self.read_byte(self.op_addr); self.p.toggle_flags(self.a, vec![FLAGS::Z, FLAGS::N]); } "BRK" => { std::process::exit(0); } _ => { println!("Mnemonic unrecognized {}", self.curr_instr.mnemonic.as_str());} } } fn load(&mut self, program: Vec<u8>) { let mut addr = 0x0000; for data in program { self.write_byte(addr, data); addr += 1; } } pub fn run(&mut self, program: Vec<u8>) { self.load(program); loop { self.execute(); self.print_state(); } } } β€Ž flags.rs pub enum FLAGS { C, Z, I, D, V, N } pub struct Flags { pub c: bool, pub z: bool, pub i: bool, pub d: bool, // b flag pub v: bool, pub n: bool } impl Flags { pub fn new() -> Self { Flags { c: false, z: false, i: false, d: false, v: false, n: false } }
{ "domain": "codereview.stackexchange", "id": 43854, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, rust, emulator", "url": null }
beginner, rust, emulator fn toggle_zero_flag(&mut self, value: u8) { if value == 0 { self.z = true; } else { self.z = false; } } fn toggle_negative_flag(&mut self, value: u8) { if value & 0b1000_0000 != 0 { self.n = true; } else { self.n = false; } } pub fn toggle_flags(&mut self, value: u8, flags: Vec<FLAGS>) { for flag in flags { match flag { FLAGS::Z => { self.toggle_zero_flag(value) } FLAGS::N => { self.toggle_negative_flag(value) } _ => { println!("Flag still not implemented") } } } } } β€Ž instruction.rs #[derive(Copy, Clone)] pub enum AddrMode { IMM, ABS, ZPG } impl AddrMode { pub fn get_addr_mode_string(&self, opcode: u8) -> String { match opcode { 0xA9 | 0x00 => { String::from("IMM") } 0xAD => { String::from("ABS") } 0xA5 => { String::from("ZPG") } _ => { String::from("IMM") } } } } pub struct Instruction { pub opcode: u8, pub mnemonic: String, pub addr_mode: AddrMode } impl Instruction { pub fn new() -> Self { Instruction { opcode: 0x00, mnemonic: String::from("NOP"), addr_mode: AddrMode::IMM } }
{ "domain": "codereview.stackexchange", "id": 43854, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, rust, emulator", "url": null }
beginner, rust, emulator fn set_instruction(&mut self, new_opcode: u8, new_mnemonic: String, new_addr_mode: AddrMode) { self.opcode = new_opcode; self.mnemonic = new_mnemonic; self.addr_mode = new_addr_mode; } fn fetch_mnemonic(&self, opcode: u8) -> String { match opcode { 0xA9 | 0xAD | 0xA5 => { String::from("LDA") } 0x00 => { String::from("BRK") } _ => { todo!() } } } fn fetch_addr_mode(&self, opcode: u8) -> AddrMode { match opcode { 0xA9 => { AddrMode::IMM } 0xAD => { AddrMode::ABS } 0xA5 => { AddrMode::ZPG } // TODO: should be implied 0x00 => { AddrMode::IMM } _ => { todo!() } } } pub fn fetch_instruction(&mut self, opcode: u8) { let new_opcode = opcode; let new_mnemonic = self.fetch_mnemonic(opcode); let new_addr_mode = self.fetch_addr_mode(opcode); // set the current instruction with new data self.set_instruction(new_opcode, new_mnemonic, new_addr_mode); } } The instructions that I have implemented all work as intended, but I'm afraid the code isn't all that good :( Thanks in advance for the feedback Answer: This is an attempt at my answer. Since I am not familiar with the 6502, I can only comment on more obvious code smells. I already left a comment under your post regarding clippy; I will therefore not reiterate its output here. I'm confident you can work through this yourself. :) I must say that I am impressed -- for a beginner, this is already quite good code! You have short and concise functions with descriptive names -- that's nice!
{ "domain": "codereview.stackexchange", "id": 43854, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, rust, emulator", "url": null }
beginner, rust, emulator Naming You have named quite some of structs with all-caps. The convention in rust is that structs and enums use SnakeCase. Seeing your main start with CPU::new() will confuse people who first see your code, since ALLCAPS is reserved for constants and statics. This affects CPU, FLAGS, the fields of AddrMode, and likely more. Incomplete abstraction, publicness The field CPU.ram is public. Structs with public fields can be an indicator for incomplete abstraction. You make use of the public field in main, to initialize the RAM. But you aleady have a nice write_byte method that you could use. Make that public, and then use it in main. let mut cpu = Cpu::new(); // values to load cpu.write_byte(0xA00B, 0x0A); cpu.write_byte(0x00DD, 0x80); Missing abstraction, primitive obsession, magic numbers From what I can understand, your cpu.run gets a vector of instructions and address words. Apparently 0x80, 0xDD, and (0x0B, 0xA0) are words, and the other are instructions / opcodes. Your words also seem to be either 16 bit or 32 bit wide, but as a user I don't see when one or the other applies unless I already understand the architecture. Providing the opcodes as u8 values is a missing abstraction, as well as primitive obession (using primities instead of value-objects). You actually want to allow only certain opcodes. I would suggest defining a pub enum OpCodes somewhere. Now you would have a vector of opcodes and addresses, which is not good. But hey, we are missing another abstraction that can help! Every opcode and address belong together and form ... something (I'm missing the right word -- would you call that an instruction?). So make a pub struct Instruction { opcode: OpCodes, data: u16 }. Feed those into your CPU. This is also the point where you should deal with 16- and 32-bit words. The method's signature should be this. impl Cpu { pub fn run(&mut self, program: Vec<Instruction>) { todo!() } }
{ "domain": "codereview.stackexchange", "id": 43854, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, rust, emulator", "url": null }
beginner, rust, emulator Since the opcodes are also not used by any identifier, this makes them magic numbers. fn get_flag_str can be written a lot shorter. You don't need to compare a bool to true, just use the bool. Also, booleans can be used in match expressions. And you don't need return statements in the last instruction of blocks and in match arms, so we can get rid of those. impl Cpu { fn get_flag_str(&self, flag: Flags) -> &str { match flag { Flags::Z => match self.p.z { true => "T", false => "F", }, Flags::N => match self.p.n { true => "T", false => "F", }, _ => "U", } } } You now also see that you use the exact same logic twice to convert a bool to a str of length 1. That's a function. impl Cpu { fn get_flag_str(&self, flag: FLAGS) -> &str { match flag { FLAGS::Z => bool_to_str(self.p.z), FLAGS::N => bool_to_str(self.p.n), _ => "U", } } } fn bool_to_str(value: bool) -> &'static str { match value { true => "T", false => "F", } } Furthermore, it seems you don't need really need a &str, since the result is always of length 1. Just use a char. derive Debug For libraries in Rust, it is convention that every struct and enum gets a Debug implementation. You have an application, but it still makes sense, because you can then easily throw a dbg! in your code and show the state of whatever object you are interested in. And luckily in Rust: you don't need to implement this yourself. Just change your declaration like this, and you are done. #[derive(Debug)] pub struct Cpu { ... }
{ "domain": "codereview.stackexchange", "id": 43854, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, rust, emulator", "url": null }
beginner, rust, emulator formatting Use the integrated formatter, rustfmt, to format your code. The moment you start collaborating with other programmers, you don't need to fight over indentation, whitespace, etc. Just use it, and everyone can read your code more easily since the formatting is closer than to what they would expect. Missing tests Your code does not include any tests. That is a problem, since after a refactor I cannot be sure that I did not break anything. This like read_word would likely be a good candidate to introduce some tests. I think I will leave it here. There's probably more to be said when you dive into the actual implementation. I will leave that to others. :) https://en.wikipedia.org/wiki/Magic_number_(programming)
{ "domain": "codereview.stackexchange", "id": 43854, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, rust, emulator", "url": null }
c#, .net, blazor Title: Finding exceptions and optimisations in weather forecast service Question: When creating a new Blazor project, there is a page called FetchData which gives an example of a razor page using a service to pull data to a page. I set myself a challenge to improve on the service, so that instead of a random label being assigned to a temperature for a forecast, it separates the label categories evenly across the range of temperatures. Here is the original code for the service: namespace MyBlazorApp.Data { public class WeatherForecastService { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; public Task<WeatherForecast[]> GetForecastAsync(DateTime startDate) { return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = startDate.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }).ToArray()); } } } And here is my new code: namespace MyBlazorApp.Data { public class WeatherForecastService { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; public Task<WeatherForecast[]> GetForecastAsync(DateTime startDate) { var minTemp = -10; var maxTemp = 40; return Task.FromResult(Enumerable.Range(0, 14).Select(index => getWeatherForecast(startDate, minTemp, maxTemp, index)).ToArray()); } public WeatherForecast getWeatherForecast(DateTime startDate, int minTemp, int maxTemp, int index) { maxTemp += (maxTemp - minTemp) % Summaries.Length;
{ "domain": "codereview.stackexchange", "id": 43855, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, blazor", "url": null }
c#, .net, blazor var rng = Random.Shared.Next(minTemp, maxTemp); var categorySize = (maxTemp - minTemp) / (Summaries.Length); var pointer = (rng + (0 - minTemp)) / categorySize; if (pointer >= Summaries.Length) { pointer = Summaries.Length - 1; } return new WeatherForecast { Date = startDate.AddDays(index), TemperatureC = rng, Summary = Summaries[pointer] }; } } } The code seems to work fine, but I feel that the error handling as well as the code optimization, readability and simplicity can be improved. Any tips on how I can look to find these improvements myself would also be extremely helpful. I changed some of the numbers to feel more appropriate to the context, but ideally the solution should work no matter what variables are set. In summary, I am trying to find a solution to the problem in the absolute best way possible, as a way of giving an example of what perfect code looks like. Answer: The GetForecastAsync method Since you always call it with DateTime.Now from FetchData.razor you should consider to remove startDate as a parameter Nothing indicates that this method should be async, so you could convert it to back to sync You could replace the OnInitializedAsync override with the following code: protected override void OnInitialized() => forecasts = ForecastService.GetForecastForTwoWeeks(); The GetForecastAsync could be replaced with this: public WeatherForecast[] GetForecastForTwoWeeks() => Enumerable.Range(0, 14) .Select(daysSinceStart => GetWeatherForecast(DateTime.Now.AddDays(daysSinceStart))) .ToArray();
{ "domain": "codereview.stackexchange", "id": 43855, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, blazor", "url": null }
c#, .net, blazor Since 14 is hard-coded inside the method I would suggest to add this constraint/restriction to the method name (GetForecastForTwoWeeks) Since minTemp and maxTemp are constants and used only inside the GetWeatherForecast I've moved them from here The startDate and index are always used together inside the GetWeatherForecast to calculate the new Date So, rather than passing them separately you could pass the calculated date The getWeatherForecast method I would suggest to use C# standard naming guideline and name it with Pascal Case (GetWeatherForecast) I would also suggest to make it private if it is used only by the GetForecastForTwoWeeks method You could rewrite the getWeatherForecast like this const int MinTemperature = -10, MaxTemperature = 40; static readonly int AdjustedMaxTemperature = MaxTemperature + (MaxTemperature - MinTemperature) % Summaries.Length; static readonly int CategorySize = (AdjustedMaxTemperature - MinTemperature) / Summaries.Length; private static WeatherForecast GetWeatherForecast(DateTime date) { var temperature = Random.Shared.Next(MinTemperature, AdjustedMaxTemperature); var summaryIndex = (temperature - MinTemperature) / CategorySize; return new () { Date = date, TemperatureC = temperature, Summary = Summaries[summaryIndex] }; } Temp can abbreviate multiple terms (like temporarily, temperature, etc.) so, it might make sense to avoid abbreviating here I would advise you to avoid overwriting method's parameter value (maxTemp += ...) The adjusted maximum temperature and the category size are always the same So, they could be calculated only once BTW the AdjustedMaxTemperature is the same as the MaxTemperature since (MaxTemperature - MinTemperature) % Summaries.Length is 0 + (0 - minTemp) can be simplified to -minTemp This pointer >= Summaries.Length condition check is not needed, it will never be true rng does not mean anything, whereas temperature is more meaningful/expressive IMHO
{ "domain": "codereview.stackexchange", "id": 43855, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, blazor", "url": null }
c#, .net, blazor The most concise version I can think of now (which is still readable): private const int MinTemperature = -10, MaxTemperature = 40; private static readonly int AdjustedMaxTemperature = MaxTemperature + (MaxTemperature - MinTemperature) % Summaries.Length; private static readonly int CategorySize = (AdjustedMaxTemperature - MinTemperature) / Summaries.Length; public WeatherForecast[] GetForecastForTwoWeeks() => (from daysSinceStart in Enumerable.Range(0, 14) let temperature = Random.Shared.Next(MinTemperature, AdjustedMaxTemperature) let summaryIndex = (temperature - MinTemperature) / CategorySize select new WeatherForecast { Date = DateTime.Now.AddDays(daysSinceStart), TemperatureC = temperature, Summary = Summaries[summaryIndex] }) .ToArray();
{ "domain": "codereview.stackexchange", "id": 43855, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, blazor", "url": null }
java, beginner, object-oriented Title: Library system in Java with OOP Question: I am practicing designing OOP projects. And this is my first OOP design. I need some reviews for the code and the design please. Here is what they call UML. The code. import java.util.HashMap; public class Library { private static HashMap<Book, Boolean> store = new HashMap<Book, Boolean>(); public static HashMap<Book, Boolean> getStore() { return store; } public static boolean isBookExist(Book book) { if(store.containsKey(book)) return store.get(book); return false; } } public class Book { private String name, author; Book(String name, String author) { this.name = name; this.author = author; } String getName() { return name; } String getAuthor() { return author; } } public class Action { void readBook(Book book) { if(Library.isBookExist(book)) System.out.println("An user is reading book: \"" + book.getName() + "\" for the author: " + book.getAuthor()); else System.out.println("Book \"" + book.getName() + "\" for the author: " + book.getAuthor() + " is not exist"); } } public class AdminAction extends Action { protected void addBook(Book book) { if(Library.isBookExist(book)) { System.out.println("This book is already in the library"); return; } Library.getStore().put(book, true); System.out.println("Book: \"" + book.getName() + "\" for the author: " + book.getAuthor() + "is added to the library"); } protected void removeBook(Book book) { if(!Library.isBookExist(book)) { System.out.println("This book is not in the library"); return; } Library.getStore().remove(book); System.out.println("Book: \"" + book.getName() + "\" for the author: " + book.getAuthor() + "is removed from the library"); } }
{ "domain": "codereview.stackexchange", "id": 43856, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, object-oriented", "url": null }
java, beginner, object-oriented public class User extends Action { private String name; User (String name) { this.name = name; } public String getName() { return name; } public void changeName(String newName) { this.name = name; } } public class Admin extends AdminAction { private String name; Admin(String name) { this.name = name; } public String getName() { return name; } public void changeName(String newName) { this.name = name; } } public class LibrarySystem { public static void main(String[] args) { Admin admin = new Admin("Omar"); Admin admin2 = new Admin("Ahmed"); User user = new User("user1"); User user2 = new User("user2"); Book book = new Book("Introduction to algorithms", "Omar"); Book book2 = new Book("Clean Code", "Ghada"); Book book3 = new Book("Clean Arch", "Waled"); Book book4 = new Book("Head First", "Hend"); user.readBook(book); admin2.addBook(book); admin2.addBook(book2); admin2.addBook(book3); admin.addBook(book4); user2.readBook(book); user.readBook(book); user.readBook(book2); admin2.removeBook(book); user.readBook(book); user2.readBook(book); user.readBook(book4); } }
{ "domain": "codereview.stackexchange", "id": 43856, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, object-oriented", "url": null }
java, beginner, object-oriented Answer: It is not a good idea to hold a map of books to booleans in this case. Why would we want to store a false when we can just store nothing at all? Use a set instead. There's static abuse here. Library needs to be instantiated and should not contain statics. The members of Library should be immutable (final). Book is simple enough, and should be immutable, so should be a record. isBookExist is better-phrased hasBook. Grammar: An user -> A user. You need to make better use of string formatting favoured over string concatenation. Action as a class doesn't make a lot of sense, nor do its verbs addBook etc. Since these verbs mutate the library, they should be written in the library class. As a rudimentary form of access control, if you want only administrators to be able to add and remove books, require that the method call accept an instance of an administrative user. Library administration systems don't technically care whether their clients read the books; only whether the books have been loaned - so some terminology needs to change. Most errors should raise exceptions rather than print, on the inside of business logic; then at the point of call decide whether to let the exceptions fall through or catch and print them. A User allowing a name to be get and set through boilerplate accessor methods is no functionally different than simply having a public member variable, so do that. Suggested import java.util.HashMap; import java.util.HashSet; public class Main { public static class LibraryException extends RuntimeException { public LibraryException(String message) { super(message); } } public record Book(String name, String author) { @Override public String toString() { return "\"%s\" for the author: %s".formatted(name, author); } } public static class User { public String name; public User(String name) { this.name = name; }
{ "domain": "codereview.stackexchange", "id": 43856, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, object-oriented", "url": null }
java, beginner, object-oriented public User(String name) { this.name = name; } @Override public String toString() { return name; } } public static class Admin extends User { public Admin(String name) { super(name); } } public static class Library { private final HashSet<Book> store = new HashSet<>(); private final HashMap<Book, User> loans = new HashMap<>(); public boolean hasBook(Book book) { return store.contains(book); } public void needBook(Book book) { if (!hasBook(book)) throw new LibraryException("Book %s is not in the library".formatted(book)); } public void addBook(Admin user, Book book) { if (!store.add(book)) throw new LibraryException("Book %s is already in the library".formatted(book)); System.out.printf("Book %s is added to the library%n", book); } public void removeBook(Admin user, Book book) { needBook(book); loans.remove(book); store.remove(book); System.out.printf("Book %s is removed from the library%n", book); } public void loanBook(User user, Book book) { needBook(book); if (loans.containsKey(book)) throw new LibraryException("Another user has loaned book %s".formatted(book)); loans.put(book, user); System.out.printf("User %s has loaned book %s%n", user, book); } } public static void main(String[] args) { Admin admin = new Admin("Omar"); Admin admin2 = new Admin("Ahmed"); User user = new User("user1"); User user2 = new User("user2"); Book book = new Book("Introduction to algorithms", "Omar"); Book book2 = new Book("Clean Code", "Ghada"); Book book3 = new Book("Clean Arch", "Waled"); Book book4 = new Book("Head First", "Hend"); Library library = new Library();
{ "domain": "codereview.stackexchange", "id": 43856, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, object-oriented", "url": null }
java, beginner, object-oriented Library library = new Library(); try { library.loanBook(user, book); } catch (LibraryException e) { System.out.println(e); } library.addBook(admin2, book); library.addBook(admin2, book2); library.addBook(admin2, book3); library.addBook(admin, book4); library.loanBook(user2, book); try { library.loanBook(user, book);} catch (LibraryException e) { System.out.println(e); } library.loanBook(user, book2); library.removeBook(admin2, book); try { library.loanBook(user, book); } catch (LibraryException e) { System.out.println(e); } try { library.loanBook(user2, book); } catch (LibraryException e) { System.out.println(e); } library.loanBook(user, book4); } } Output Main$LibraryException: Book "Introduction to algorithms" for the author: Omar is not in the library Book "Introduction to algorithms" for the author: Omar is added to the library Book "Clean Code" for the author: Ghada is added to the library Book "Clean Arch" for the author: Waled is added to the library Book "Head First" for the author: Hend is added to the library User user2 has loaned book "Introduction to algorithms" for the author: Omar Main$LibraryException: Another user has loaned book "Introduction to algorithms" for the author: Omar User user1 has loaned book "Clean Code" for the author: Ghada Book "Introduction to algorithms" for the author: Omar is removed from the library Main$LibraryException: Book "Introduction to algorithms" for the author: Omar is not in the library Main$LibraryException: Book "Introduction to algorithms" for the author: Omar is not in the library User user1 has loaned book "Head First" for the author: Hend
{ "domain": "codereview.stackexchange", "id": 43856, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, object-oriented", "url": null }
c++, array, unit-testing Title: Unit testing for a multi-dimensional array class Question: I have designed a class bunji::Tensor which is a multi-dimensional array. I have designed it to have a similar interface to a multi-dimensional std::vector, just that the bunji::Tensor constructor takes in an std::vector in its constructor which defines the dimensions, i.e. bunji::Tensor<double, 3> my_tensor({10, 4, 2}); Creates a 3 dimensional tensor of doubles, with dimensions x=10, y=4, and z=2. I have made some tests for this tensor using the google/googletest testing framework. My tests are below. #include "tensor.hpp" #include <gtest/gtest.h> void test_manual_1d(const std::size_t x) { bunji::Tensor<int, 1> tensor({x}); for (std::size_t i = 0; i < x; ++i) { EXPECT_EQ(tensor[i], 0); tensor[i] = i+1; } for (std::size_t i = 0; i < x; ++i) { EXPECT_EQ(tensor[i], i+1); } } void test_manual_2d(const std::size_t x, const std::size_t y) { bunji::Tensor<int, 2> tensor({x, y}); for (std::size_t i = 0; i < x; ++i) { for (std::size_t j = 0; j < y; ++j) { EXPECT_EQ(tensor[i][j], 0); tensor[i][j] = (i+1) * (j+1); } } for (std::size_t i = 0; i < x; ++i) { for (std::size_t j = 0; j < y; ++j) { EXPECT_EQ(tensor[i][j], (i+1) * (j+1)); } } } void test_manual_3d(const std::size_t x, const std::size_t y, const std::size_t z) { bunji::Tensor<int, 3> tensor({x, y, z}); for (std::size_t i = 0; i < x; ++i) { for (std::size_t j = 0; j < y; ++j) { for (std::size_t k = 0; k < z; ++k) { EXPECT_EQ(tensor[i][j][k], 0); tensor[i][j][k] = (i+1) * (j+1) * (k+1); } } }
{ "domain": "codereview.stackexchange", "id": 43857, "lm_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++, array, unit-testing", "url": null }
c++, array, unit-testing for (std::size_t i = 0; i < x; ++i) { for (std::size_t j = 0; j < y; ++j) { for (std::size_t k = 0; k < z; ++k) { EXPECT_EQ(tensor[i][j][k], (i+1) * (j+1) * (k+1)); } } } } void test_manual_4d(const std::size_t x, const std::size_t y, const std::size_t z, const std::size_t v) { bunji::Tensor<int, 4> tensor({x, y, z, v}); for (std::size_t i = 0; i < x; ++i) { for (std::size_t j = 0; j < y; ++j) { for (std::size_t k = 0; k < z; ++k) { for (std::size_t l = 0; l < v; ++l) { EXPECT_EQ(tensor[i][j][k][l], 0); tensor[i][j][k][l] = (i+1) * (j+1) * (k+1) * (l+1); } } } } for (std::size_t i = 0; i < x; ++i) { for (std::size_t j = 0; j < y; ++j) { for (std::size_t k = 0; k < z; ++k) { for (std::size_t l = 0; l < v; ++l) { EXPECT_EQ(tensor[i][j][k][l], (i+1) * (j+1) * (k+1) * (l+1)); } } } } } template<std::size_t Dimensions, class Callable> void nd_for_loop(std::size_t begin, std::size_t end, Callable &&c) { for(size_t i = begin; i != end; ++i) { if constexpr(Dimensions == 1) { c(i); } else { auto bind_argument = [i, &c](auto... args) { c(i, args...); }; nd_for_loop<Dimensions-1>(begin, end, bind_argument); } } } TEST(tensor, tensor_manual) { nd_for_loop<1>(0, 8500, test_manual_1d); nd_for_loop<2>(0, 100, test_manual_2d); nd_for_loop<3>(0, 24, test_manual_3d); nd_for_loop<4>(0, 12, test_manual_4d); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
{ "domain": "codereview.stackexchange", "id": 43857, "lm_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++, array, unit-testing", "url": null }
c++, array, unit-testing Answer: The biggest issue with your test suite is the fact that you had to manually write four versions to handle tensors of up to four dimensions. You should be able to write generic code to test arbitrary-dimension tensors. Ideally, all test_manual_*() functions should be replaced with: template<typename... Dims> void test(const Dims&... dims) { bunji::Tensor<int, sizeof...(Dims)> tensor({dims...}); ... } Now the question is: how to implement an arbitrarily-nested for-loop in a generic way? The solution is to store the indices in a std::vector or std::array, and treat this as a multidimensional index. Then you can create a function to increment this: template<std::size_t N> static bool next(std::array<std::size_t, N>& indices, const std::array<std::size_t, N>& dims) { for (std::size_t i = 0; i < N; ++i) { if (++indices[i] != dims[i]) return true; indices[i] = 0; } return false; } The way you use it is like so: template<typename... Dims> static void test(const Dims&... dims) { constexpr std::size_t N = sizeof...(Dims); bunji::Tensor<int, N> tensor({dims...}); std::array<std::size_t, N> indices = {}; std::array<std::size_t, N> dims_arr = {dims...}; do { ... } while (next<N>(indices, dims_arr)); } The next issue is how to generically apply [] multiple times. A recursive template function can be used here, similar to how nd_for_loop() works: template<std::size_t N, std::size_t I = N - 1, typename T> static auto& get(T& tensor, const std::array<std::size_t, N>& indices) { if constexpr (I == 0) { return tensor[indices[0]]; } else { return get<N, I - 1>(tensor[indices[I]], indices); } } Then inside the do-while-loop above you can write: auto& value = get<N>(tensor, indices); EXPECT_EQ(value, 0); value = std::accumulate(indices.begin(), indices.end(), 1, std::multiplies<int>());
{ "domain": "codereview.stackexchange", "id": 43857, "lm_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++, array, unit-testing", "url": null }
c++, array, unit-testing There are some variations possible on this theme regarding how exactly you pass the dimensions to the various functions. Maybe pass a std::array to test() as well, instead of using a variable number of arguments? That would simplify nd_for_loop().
{ "domain": "codereview.stackexchange", "id": 43857, "lm_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++, array, unit-testing", "url": null }
performance, c, cython, radix-sort Title: Improving performance of radix sort Question: I am trying to optimize the following (now C) radix sort code for use in my game engine library. The basis for this code was inspired by this youtube video on a C++ implementation called skasort that used templating to sort STL containers. The current first pass code sorts in-place in most-significant-byte (MSB) order and is designed to handle [u]int[8/16/32/64]_t types as well as float/f32, double/f64 and char * strings of variable lengths. Here is the raw C code (header-only) I wrote that my cython library is wrapping: #include <stdint.h> #include <stdbool.h> #define RADIX 256 #define RADIX_THRESHOLD 128 #define CMP_CHECK(a, b, cmp_type) \ cmp_type a_i = *(cmp_type *)a; \ cmp_type b_i = *(cmp_type *)b; \ if(a_i < b_i) \ { \ return -1; \ } \ else if(a_i > b_i) \ { \ return 1; \ } \ else \ { \ return 0; \ } \ #define CMP_FUNC(a, b, cmp_type, cmp_suffix) \ int cmp_func_##cmp_suffix(const void *a, const void *b) \ { \ CMP_CHECK(a, b, cmp_type) \ } \ typedef enum RadixSortType { RADIX_SORT_TYPE_U8, RADIX_SORT_TYPE_I8, RADIX_SORT_TYPE_U16, RADIX_SORT_TYPE_I16, RADIX_SORT_TYPE_U32, RADIX_SORT_TYPE_I32, RADIX_SORT_TYPE_U64, RADIX_SORT_TYPE_I64, RADIX_SORT_TYPE_F32, RADIX_SORT_TYPE_F64, RADIX_SORT_TYPE_STR, } RadixSortType; typedef int (* CmpFuncC)(const void *, const void *); typedef uint8_t (* RadixKeyFuncC)(void *item, size_t byte_offset); typedef struct RadixPartitionTableC { size_t counts[RADIX]; size_t prefix_sums[RADIX + 1]; size_t shifted_sums[RADIX + 1]; } RadixPartitionTableC; void table_clear(RadixPartitionTableC *table) { memset(table->counts, 0, sizeof(size_t) * RADIX); memset(table->prefix_sums, 0, sizeof(size_t) * (RADIX + 1)); memset(table->shifted_sums, 0, sizeof(size_t) * (RADIX + 1)); }
{ "domain": "codereview.stackexchange", "id": 43858, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, cython, radix-sort", "url": null }
performance, c, cython, radix-sort void item_swap(void *items, size_t a, size_t b, size_t size) { uint8_t *a_ptr = (uint8_t *)items + (a * size); uint8_t *b_ptr = (uint8_t *)items + (b * size); uint8_t tmp; for(size_t i = 0; i < size; i++) { tmp = a_ptr[i]; a_ptr[i] = b_ptr[i]; b_ptr[i] = tmp; } } CMP_FUNC(a, b, uint8_t, u8) CMP_FUNC(a, b, int8_t, i8) CMP_FUNC(a, b, uint16_t, u16) CMP_FUNC(a, b, int16_t, i16) CMP_FUNC(a, b, uint32_t, u32) CMP_FUNC(a, b, int32_t, i32) CMP_FUNC(a, b, uint64_t, u64) CMP_FUNC(a, b, int64_t, i64) CMP_FUNC(a, b, float, f32) CMP_FUNC(a, b, double, f64) int cmp_func_str(const void *a, const void *b) { return strcmp(*(char **)a, *(char **)b); } uint8_t radix_key_func_u8(void *item, size_t byte_offset) { return ((uint8_t *)item + byte_offset)[0]; } uint8_t radix_key_func_i8(void *item, size_t byte_offset) { return ((uint8_t *)item + byte_offset)[0] + 128; } uint8_t radix_key_func_u16(void *item, size_t byte_offset) { return ((uint8_t *)item + byte_offset)[0]; } uint8_t radix_key_func_i16(void *item, size_t byte_offset) { uint16_t value = ((uint16_t *)item)[0] + 32768; return ((uint8_t *)&value + byte_offset)[0]; } uint8_t radix_key_func_u32(void *item, size_t byte_offset) { return ((uint8_t *)item + byte_offset)[0]; } uint8_t radix_key_func_i32(void *item, size_t byte_offset) { uint32_t value = ((int32_t *)item)[0] + (int32_t)2147483648; return ((uint8_t *)&value + byte_offset)[0]; } uint8_t radix_key_func_u64(void *item, size_t byte_offset) { return ((uint8_t *)item + byte_offset)[0]; } uint8_t radix_key_func_i64(void *item, size_t byte_offset) { uint64_t value = ((int64_t *)item)[0] + (int64_t)9223372036854775808; return ((uint8_t *)&value + byte_offset)[0]; }
{ "domain": "codereview.stackexchange", "id": 43858, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, cython, radix-sort", "url": null }
performance, c, cython, radix-sort uint8_t radix_key_func_f32(void *item, size_t byte_offset) { uint32_t value = ((uint32_t *)item)[0]; uint32_t mask = -(int32_t)(value >> (uint32_t)31) | (uint32_t)2147483648; uint32_t shifted_value = value ^ mask; return ((uint8_t *)(&shifted_value) + byte_offset)[0]; } uint8_t radix_key_func_f64(void *item, size_t byte_offset) { uint64_t value = ((uint64_t *)item)[0]; uint64_t mask = -(int64_t)(value >> (uint64_t)63) | (uint64_t)9223372036854775808; uint64_t shifted_value = value ^ mask; return ((uint8_t *)(&shifted_value) + byte_offset)[0]; } uint8_t radix_key_func_str(void *item, size_t byte_offset) { return (((uint8_t **)item)[0] + byte_offset)[0]; }
{ "domain": "codereview.stackexchange", "id": 43858, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, cython, radix-sort", "url": null }
performance, c, cython, radix-sort void c_radix_sort(void *items, size_t item_size, size_t start, size_t end, size_t start_offset, RadixSortType type_, RadixKeyFuncC key_func) { size_t byte_offset; size_t num_bytes; bool flip_byte_order = true; bool use_null_term = false; CmpFuncC cmp_func; switch(type_) { case RADIX_SORT_TYPE_U8: byte_offset = 0; num_bytes = sizeof(uint8_t); key_func = radix_key_func_u8; cmp_func = cmp_func_u8; break; case RADIX_SORT_TYPE_I8: byte_offset = 0; num_bytes = sizeof(int8_t); key_func = radix_key_func_i8; cmp_func = cmp_func_i8; break; case RADIX_SORT_TYPE_U16: byte_offset = 1; num_bytes = sizeof(uint16_t); key_func = radix_key_func_u16; cmp_func = cmp_func_u16; break; case RADIX_SORT_TYPE_I16: byte_offset = 1; num_bytes = sizeof(int16_t); key_func = radix_key_func_i16; cmp_func = cmp_func_i16; break; case RADIX_SORT_TYPE_U32: byte_offset = 3; num_bytes = sizeof(uint32_t); key_func = radix_key_func_u32; cmp_func = cmp_func_u32; break; case RADIX_SORT_TYPE_I32: byte_offset = 3; num_bytes = sizeof(int32_t); key_func = radix_key_func_i32; cmp_func = cmp_func_i32; break; case RADIX_SORT_TYPE_U64: byte_offset = 7; num_bytes = sizeof(uint64_t); key_func = radix_key_func_u64; cmp_func = cmp_func_u64; break; case RADIX_SORT_TYPE_I64: byte_offset = 7; num_bytes = sizeof(int64_t); key_func = radix_key_func_i64; cmp_func = cmp_func_i64; break; case RADIX_SORT_TYPE_F32:
{ "domain": "codereview.stackexchange", "id": 43858, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, cython, radix-sort", "url": null }
performance, c, cython, radix-sort cmp_func = cmp_func_i64; break; case RADIX_SORT_TYPE_F32: byte_offset = 3; num_bytes = sizeof(float); key_func = radix_key_func_f32; cmp_func = cmp_func_f32; break; case RADIX_SORT_TYPE_F64: byte_offset = 7; num_bytes = sizeof(double); key_func = radix_key_func_f64; cmp_func = cmp_func_f64; break; case RADIX_SORT_TYPE_STR: byte_offset = 0; num_bytes = sizeof(char *); flip_byte_order = false; use_null_term = true; key_func = radix_key_func_str; cmp_func = cmp_func_str; break; } c_radix_sort_byte( items, item_size, start, end, start_offset, byte_offset, num_bytes, flip_byte_order, use_null_term, key_func, cmp_func ); }
{ "domain": "codereview.stackexchange", "id": 43858, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, cython, radix-sort", "url": null }
performance, c, cython, radix-sort inline void c_radix_sort_byte(void *items, size_t item_size, size_t start, size_t end, size_t start_offset, size_t byte_offset, size_t num_bytes, bool flip_byte_order, bool use_null_term, RadixKeyFuncC key_func, CmpFuncC cmp_func) { void *item_ptr; uint8_t item; size_t total; size_t prefix_sum; size_t shifted_sum; size_t a, b; RadixPartitionTableC table; size_t count; size_t table_start; size_t table_end; int8_t byte_order = flip_byte_order ? -1 : 1; table_clear(&table); for(size_t i = start; i < end; i++) { item_ptr = ((uint8_t *)items) + (i * item_size); item = key_func(item_ptr, byte_offset); table.counts[item] += 1; } if(use_null_term) { table.counts[0] = 0; } total = 0; for(size_t i = 0; i < RADIX; i++) { total += table.counts[i]; table.prefix_sums[i + 1] += total; table.shifted_sums[i] = table.prefix_sums[i + 1]; } for(size_t i = start; i < end; i++) { while(true) { item_ptr = ((uint8_t *)items) + (i * item_size); item = key_func(item_ptr, byte_offset); prefix_sum = table.prefix_sums[item]; shifted_sum = table.shifted_sums[item]; if(prefix_sum == shifted_sum) { break; } a = i; b = start + prefix_sum; item_swap(items, a, b, item_size); table.prefix_sums[item] += 1; } }
{ "domain": "codereview.stackexchange", "id": 43858, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, cython, radix-sort", "url": null }
performance, c, cython, radix-sort if(!flip_byte_order && byte_offset == num_bytes && !use_null_term) { return; } else if(flip_byte_order && byte_offset == 0 && !use_null_term) { return; } else { total = 0; for(size_t i = 0; i < RADIX; i++) { count = table.counts[i]; table_start = start + total; table_end = start + total + count; total += count; if(count >= RADIX_THRESHOLD) { c_radix_sort_byte( items, item_size, table_start, table_end, start_offset, byte_offset + byte_order, num_bytes, flip_byte_order, use_null_term, key_func, cmp_func ); } else if(count > 1) { qsort( items + (item_size * table_start) + start_offset, table_end - table_start, item_size, cmp_func ); } } } } The benchmarking test I have is written in cython and runs radix sorts on each of the supported types (with the char * test being on random alphanumeric strings ranging from 20-50 chars in length), on a custom vector-like container from n=2^1 to n=2^24 items. I can add the benchmarking code if needed; in the meantime, the code for the game engine repo can be found here. The performance of this code is slower than I would like, ranging from 5x faster in the simple uint8_t case to about 0.9x the speed of the radix sort in the worst cases where the sort code needs to be recursively called (the 64-bit types and the variable length strings). I have the following questions:
{ "domain": "codereview.stackexchange", "id": 43858, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, cython, radix-sort", "url": null }
performance, c, cython, radix-sort The code swaps items in-place, leading to a bunch of memcpy calls when items need to be swapped. Would pointer swapping and sorting out of place provide a meaningful performance benefit? This would come at the cost of allocating additional heap memory, which I was striving to avoid based on that above lecture. I have heard about "loop unrolling" being a possible technique to improve performance. How would I go about implementing this? Would SIMD be needed to do this? Any resources on this would be helpful. I would like to generalize this to a series of passes based on struct members to do more complex sorts based on these primitive types (e.g. sorting players by distance from a target, alphabetizing user names, etc.). I would appreciate any ideas for a convenient, user-friendly API that could handle arbitrary structs. The code is essentially already C-code. Would rewriting in C and making a cython wrapper provide any meaningful performance improvement to help the compiler optimize further? The code is already being compiled with reasonable compiler arguments in gcc ( -std=c11, -O3, -ffast-math, -march=native). This point is moot now that the code has been rewritten in C for both convenience (macros to deduplicate code) and reviewability (cython is a niche language). The code is still being compiled with the same flags and the performance is essentially unchanged.
{ "domain": "codereview.stackexchange", "id": 43858, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, cython, radix-sort", "url": null }
performance, c, cython, radix-sort As requested by @Reinderien, this is the complete gcc command that is invoked when the radix sort is compiled by gcc: building 'pyorama.algs.radix_sort' extension gcc -Wno-unused-result -Wsign-compare -DNDEBUG -march=x86-64 -mtune=generic -O2 -pipe -fwrapv -D__USE_MINGW_ANSI_STDIO=1 -D_WIN32_WINNT=0x0601 -DNDEBUG -march=x86-64 -mtune=generic -O2 -pipe -fwrapv -D__USE_MINGW_ANSI_STDIO=1 -D_WIN32_WINNT=0x0601 -DNDEBUG -DCIMGUI_DEFINE_ENUMS_AND_STRUCTS=True -DCGLTF_IMPLEMENTATION=True -DSTB_IMAGE_IMPLEMENTATION=True -DSTBI_FAILURE_USERMSG=True -DCGLM_CLIPSPACE_INCLUDE_ALL=True -DCGLM_ALL_UNALIGNED=True -I./pyorama/algs -I./pyorama/libs/include -IC:/msys64/mingw64/include/python3.9 -c ./pyorama/algs/radix_sort.c -o build/temp.mingw_x86_64-3.9/./pyorama/algs/radix_sort.o -w -std=c11 -O3 -ffast-math -march=native And here is a link to the results (.csv) as well as a graph of the data: Answer: Some general review: We're missing an include of <string.h> for memset(). There are some constants that aren't obviously correct, such as: uint64_t value = ((int64_t *)item)[0] + (int64_t)9223372036854775808; It's clearer to use -INT64_MIN there, and similarly in the other functions. If we're on a 2's complement machine, we might generate faster code with ((uint64_t*)item)[0] ^ ((uint64_t)1 << 63). But I'd want to read the compiler's output to be certain. This expression looks weird: ((uint8_t *)item + byte_offset)[0]; Surely that's the same as ((uint8_t *)item)[byte_offset]?
{ "domain": "codereview.stackexchange", "id": 43858, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, cython, radix-sort", "url": null }
performance, c, cython, radix-sort ((uint8_t *)item + byte_offset)[0]; Surely that's the same as ((uint8_t *)item)[byte_offset]? Performance aspects: I think that if you want to increase performance, the next thing to do is to actually build separate sort functions for the different types, rather than indirecting through the key-functions. You could do that by writing macros, but I think it will be easier to repeatedly compile a single source file, using preprocessor to substitute the varying parts (either by multiple includes from one translation unit, or as individual translation units - you can use Make to orchestrate that quite effectively). I wouldn't bother trying to unroll loops by hand - these ones look amenable to intelligent unrolling by your compiler. Consider experimenting with the code-generation options that affect loop unrolling, of course.
{ "domain": "codereview.stackexchange", "id": 43858, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, c, cython, radix-sort", "url": null }
python, python-3.x, game, tkinter, minesweeper Title: Tkinter Minesweeper Clone V2 Question: Intro Having spent quite a bit of time learning Python, I thought it was time to work on something. However, an Google search for "python projects 2022" came up with projects I had already completed. Looking through my projects, however, I came across this. (link). I decided to test my abilities and rewrote the code. Please review, thanks! What I am looking for Any best practices or performance flaws in my code. Proper separation of code into functions. Proper usage of type hinting in my functions. Code formating, spacing, and logical breaks in my code. A better emoji for my mine: currently using (maybe switch to images?) The code import random import tkinter as tk import tkinter.messagebox as msgbox from typing import List, Literal, Tuple # TODO # improve astethics and change colors # add colors of numbers class Main: def __init__(self): self.status_bar_on = True self.game_started = False self.gameover = False self.cols = 30 self.rows = 16 self.flags = 80 self.original_flags = self.flags self.time = 0 self.widget_board = [[0 for _ in range(self.cols)] for _ in range(self.rows)] self.setupTkinter() self.generateBoard() def run(self) -> Literal[None]: '''Run the GUI application: call tk.Tk.mainloop.''' self.window.after(200, self.updateTimer) self.window.mainloop() def gameOver(self, won: bool, bad: bool = False) -> Literal[None]: ''' GUI game over function. Called by Main.checkWon. Shows a popup message and also displays all mines: self.showBombs. ''' self.showBombs() if bad: msgbox.showinfo(title = 'Minesweeper', message = f'You lost!') self.gameover = True return
{ "domain": "codereview.stackexchange", "id": 43859, "lm_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, game, tkinter, minesweeper", "url": null }
python, python-3.x, game, tkinter, minesweeper if won: msgbox.showinfo(title = 'Minesweeper', message = f'You won in {self.timer} seconds!') self.gameover = True else: self.window.after(100, self.gameOver(won, bad = True)) def checkWon(self) -> Literal[None]: ''' Checks the board for a wins. Uses the following formula: (amount of opened cells) + (mines) == (total tiles) to check. Calls Main.gameOver when a win is detected. ''' opened_cells = 0 for widget in self.board_frame.winfo_children(): if widget.cget('text').isnumeric(): opened_cells += 1 if (self.rows * self.cols) == opened_cells + self.original_flags: self.gameOver(won = True) def showBombs(self) -> Literal[None]: ''' Iterates through the game frame's widgets: (winfo_children) and finds widgets that correspond to mines. When one is found, if it was correctly marked with a flag, it is marked with a green background. Otherwise, with a red background. ''' for row_index, row in enumerate(self.game_board): for item_index, item in enumerate(row): if item == '\N{BOMB}': widget = self.widget_board[row_index][item_index] if widget.cget('text') == ' ': widget.config(text = '\N{BOMB}', bg = 'red') elif widget.cget('text') == '\u2691': widget.config(bg = 'dark green') for widget in self.board_frame.winfo_children(): if widget.cget('text') == '\u2691': if widget.cget('bg') != 'dark green': widget.config(bg = 'red')
{ "domain": "codereview.stackexchange", "id": 43859, "lm_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, game, tkinter, minesweeper", "url": null }
python, python-3.x, game, tkinter, minesweeper def setupTkinter(self) -> Literal[None]: ''' An encapsulating function with Tkinter setup and layouting. Generates the main window along with the status widgets, and frames. ''' self.window = tk.Tk() self.window.geometry('1125x590') self.window.title('Minesweeper') self.window.config(bg = 'blue') self.status_bar = tk.Frame(self.window, height = 50) self.status_bar.config(bg = 'blue') self.board_frame = tk.Frame(self.window) self.board_frame.config(bg = 'black') self.time_variable = tk.StringVar(self.status_bar, value = 'βŒ› 0') self.flags_variable = tk.StringVar(self.status_bar, value = f' {self.flags}') self.time_label = tk.Label(self.status_bar, textvariable = self.time_variable, font = ('Courier', 30), bg = 'blue') self.flags_label = tk.Label(self.status_bar, textvariable = self.flags_variable, font = ('Courier', 30), bg = 'blue') self.generateBoardWidgets(self.board_frame) if self.status_bar_on: self.status_bar.pack(fill = tk.BOTH, expand = tk.NO, pady = 5) self.board_frame.pack(fill = tk.BOTH, expand = tk.YES) self.time_label.pack(side = tk.LEFT, padx = 5, expand = tk.YES) self.flags_label.pack(side = tk.RIGHT, padx = 5, expand = tk.YES) def generateBoardWidgets(self, board_frame: tk.Frame) -> Literal[None]: ''' Generates the tk.Label widgets in the board frame (board_frame). Iterates through required rows and columns to generate tk.Label widgets. Also binds the three buttons to the respective functions. '''
{ "domain": "codereview.stackexchange", "id": 43859, "lm_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, game, tkinter, minesweeper", "url": null }
python, python-3.x, game, tkinter, minesweeper for row in range(self.rows): for col in range(self.cols): widget = tk.Label( board_frame, text = ' ', fg = 'white', width = 1, font = ('Courier', 25), bg = 'gray') widget.bind('<Button-1>', self.handleLeftClick) widget.bind('<Button-2>', self.handleRightClick) widget.bind('<Button-3>', self.handleMiddleClick) widget.grid(row = row, column = col, padx = 2, pady = 2, sticky = tk.NSEW) tk.Grid.rowconfigure(board_frame, row, weight=1) tk.Grid.columnconfigure(board_frame, col, weight=1) self.widget_board[row][col] = widget def floodfill(self, location, first = False) -> Literal[None]: ''' Flood fills the tiles where an 0 is clicked on. This opens all connected groups of zero, and a border around this. Uses the neighbors from Main.getNeighbors and calls openNeighbors to actually open the tiles. ''' if first: self.stack = [] neighbors = self.getNeighbors(*location, [self.rows, self.cols]) self.openNeighbors(*location) for neighbor_loc in neighbors: if neighbor_loc in self.stack: continue item = self.game_board[neighbor_loc[0]][neighbor_loc[1]] if item == 0: self.stack.append(neighbor_loc) self.floodfill(neighbor_loc) def openNeighbors(self, y, x) -> Literal[None]: ''' Opens the neighbors of an tile. Used by the middle click function (Main.handleMiddleClick) and the floodfill (Main.floodfill) ''' neighbors = self.getNeighbors(y, x, [self.rows, self.cols])
{ "domain": "codereview.stackexchange", "id": 43859, "lm_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, game, tkinter, minesweeper", "url": null }
python, python-3.x, game, tkinter, minesweeper neighbors = self.getNeighbors(y, x, [self.rows, self.cols]) for neighbor_location in neighbors: item = self.game_board[neighbor_location[0]][neighbor_location[1]] widget = self.widget_board[neighbor_location[0]][neighbor_location[1]] if item == '\N{BOMB}' and widget.cget('text') != '\u2691': self.gameOver(won = False) if widget.cget('text') != ' ': continue widget.config(text = str(item)) if item == 0: self.floodfill(neighbor_location, first = True) def handleLeftClick(self, event = None) -> Literal[None]: ''' Tkinter event handling for left mouse button. Will regenerate boards on the first move if the first move is on a mine. Also floodfills the first move. ''' if self.gameover or event.widget.cget('text') != ' ': return widget = event.widget row, col = widget.grid_info()['row'], widget.grid_info()['column'] game_board_item = self.game_board[row][col] if not self.game_started: while game_board_item != 0: self.generateBoard() game_board_item = self.game_board[row][col] self.floodfill([row, col], first = True) widget.config(text = str(game_board_item)) if type(game_board_item) != int: self.gameOver(won = False) self.game_started = True self.checkWon() def handleMiddleClick(self, event = None) -> Literal[None]: ''' Tkinter event handling for middle click (mouse). Calls Main.openNeighbors. ''' if self.gameover: return widget = event.widget
{ "domain": "codereview.stackexchange", "id": 43859, "lm_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, game, tkinter, minesweeper", "url": null }
python, python-3.x, game, tkinter, minesweeper if self.gameover: return widget = event.widget row, col = widget.grid_info()['row'], widget.grid_info()['column'] self.openNeighbors(row, col) def handleRightClick(self, event = None) -> Literal[None]: ''' Tkinter event handling for right mouse button. Toggles an flag on the tile if it is not opened. ''' if self.gameover or event.widget.cget('text') not in (' ', '\u2691') or self.flags <= 0: return widget = event.widget if event.widget.cget('text') == '\u2691': widget.config(text = ' ') self.flags += 1 else: widget.config(text = '\u2691') self.flags -= 1 self.flags_variable.set(f' {self.flags}') def updateTimer(self) -> Literal[None]: ''' An function that calls itself to update an timer. Stops once the game is over, and starts on the first click. ''' if self.gameover: return if self.game_started: self.time += 1 self.time_variable.set(f'βŒ› {self.time}') self.window.after(1000, self.updateTimer) def generateBoard(self) -> Literal[None]: ''' Generates the Minesweeper game board. Places mines, and updates the numbers of neighbors by +1. Can be called multiple times to regenerate boards. ''' self.game_board = [[0 for _ in range(self.cols)] for _ in range(self.rows)] all_locations = [] for x in range(16): for y in range(30): all_locations.append((x, y)) sample = random.sample(all_locations, self.flags) for location in sample: self.setBomb(*location)
{ "domain": "codereview.stackexchange", "id": 43859, "lm_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, game, tkinter, minesweeper", "url": null }
python, python-3.x, game, tkinter, minesweeper for location in sample: self.setBomb(*location) def setBomb(self, y, x) -> Literal[None]: ''' Sets a spot on the game board to a bomb and increments the neighboring values. ''' self.game_board[y][x] = '\N{BOMB}' neighbors = self.getNeighbors(y, x, [self.rows, self.cols]) for neighbor_location in neighbors: item = self.game_board[neighbor_location[0]][neighbor_location[1]] if type(item) == int: self.game_board[neighbor_location[0]][neighbor_location[1]] += 1 def getNeighbors(self, y, x, board_shape) -> List[Tuple[int, int]]: ''' Returns a list of the indexes of neighboring tiles. (diagonals included) ''' neighbors = list() neighbors.append((y, x - 1)) neighbors.append((y, x + 1)) neighbors.append((y - 1, x)) neighbors.append((y - 1, x - 1)) neighbors.append((y - 1, x + 1)) neighbors.append((y + 1, x)) neighbors.append((y + 1, x + 1)) neighbors.append((y + 1, x - 1)) neighbors = [i for i in neighbors if i[0] in range(board_shape[0]) and i[1] in range(board_shape[1])] return neighbors if __name__ == '__main__': app = Main() app.run()
{ "domain": "codereview.stackexchange", "id": 43859, "lm_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, game, tkinter, minesweeper", "url": null }
python, python-3.x, game, tkinter, minesweeper return neighbors if __name__ == '__main__': app = Main() app.run() Answer: The choice of your function boundaries is actually pretty reasonable, but the same is not true of your class bounds. You've made a classic god class. Separate this into a business logic class that only deals with the inner representation of the board and game state, and a presentation class that only deals with tkinter. All of your member variables (and their types, when ambiguous) should be first set in the constructor. Literal[None] is an interesting choice. I'd even say it's more technically true than what people usually do, which is -> None. If you wanted to be pedantic, import NoneType from types; but this is not necessary and you should instead simply write -> None. Formal validators like mypy will understand it. __init__ returns -> None. Use lower_snake_case for your method names. It's more typical to triple-double-quote """ rather than triple-single-quote ''' for docstrings. You have a mix of \u and literal Unicode emojis sprinkled through your strings. Some of them render on my IDE font and some don't (like the triangular flag), so you're better off being consistent and declaring all Unicode constants like BLACK_FLAG = '\u2691' In getNeighbors, delete all of your append()s and write one list literal.
{ "domain": "codereview.stackexchange", "id": 43859, "lm_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, game, tkinter, minesweeper", "url": null }
python, performance, python-3.x, programming-challenge, time-limit-exceeded Title: Euler Project: Sums of Digit Factorials Question: MY CODE: import time import math import sys def sums(n): r = 0 while n: r, n = r + n % 10, n // 10 return r def f(n): r=0 s1=0 while n: r, n = n % 10, n // 10 s1=s1+math.factorial(int(r)) return s1 def sf(n): return sums(f(n)) def g(i): p=1 while True: if sf(p)==i: return p p=p+1 def sg(i): return sums(g(i)) def ssg(n): s=0 for i in range(1,n+1): s=s+sg(i) return s q=int(sys.stdin.readline()) out=[] for i in range(q): n1,m1=(sys.stdin.readline()).split() n=int(n1) m=int(m1) v=ssg(n) out.append(v%m) for i in out: print(i) This code was made for Euler Project 254: Define f(n) as the sum of the factorials of the digits of n. For example, f(342) = 3! + 4! + 2! = 32. Define sf(n) as the sum of the digits of f(n). So sf(342) = 3 + 2 = 5. Define g(i) to be the smallest positive integer n such that sf(n) = i. Though sf(342) is 5, sf(25) is also 5, and it can be verified that g(5) is 25. Define sg(i) as the sum of the digits of g(i). So sg(5) = 2 + 5 = 7. Further, it can be verified that g (20) is 267 and βˆ‘β€‰sg(i) for 1 ≀ i ≀ 20 is 156. What is βˆ‘β€‰sg(i) for 1 ≀ i ≀ 150? Input Format The first line of each test file contains a single integer q, which is the number of queries per test file. lines follow, each containing two integers separated by a single space: n and m of the corresponding query. Output Format Print exactly q lines, each containing a single integer, which is the answer to the corresponding query. **Sample Input ** 2 3 1000000 20 1000000 Sample Output 8 156 MY PROBLEM This code is not fast enough for all their test cases so, my code was rejected as answer. (They did not specify which test cases they are testing on it.) So, how efficiency of this code could be increased? Thanks PS: output is n modulo m for each entry
{ "domain": "codereview.stackexchange", "id": 43860, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, programming-challenge, time-limit-exceeded", "url": null }
python, performance, python-3.x, programming-challenge, time-limit-exceeded Answer: First of all, why do you answer multi queries? The problem asks only to find the summation of sg from 1 to 150. The real bottleneck in your solution is this function: def g(i): p=1 while True: if sf(p)==i: return p p=p+1 its growth rate is very big and the loop is unbounded. If you tried to bound it to 100 for example you will find it becomes too fast. def g(i): p=1 while True: if sf(p)==i: return p if p == 100: break p=p+1
{ "domain": "codereview.stackexchange", "id": 43860, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, programming-challenge, time-limit-exceeded", "url": null }
python, performance, python-3.x, programming-challenge, time-limit-exceeded This function will not give us the right answer for sure but it tells us that this function is the bottleneck and make the code too slow. The real problem is how to calculate g(i) fast. I will give you some ideas and hints: g(n) is the sum of digits that give us n and form the minimum possible number and at the same time can be represented in the form of $$A1!+A2!+..+Ax!$$ for example: (5 = 1 + 2 + 2) -> ( 122 = 120 + 2 ) -> ( 5! = 120 and 2! = 2 ) so ( 2! + 5! ) gives us 5 i.e. g(5) = 25 and as f(n) calculates the factorial of each digit so we have factorial of digits from 1 to 9 only. If we calculated the different combinations of sums of factorial digits from 1 to 9 (I think we can make something faster but this is just a start and you can find some algorithm to follow instead of trying all the combinations which will also be too slow) and store the minimum of them (i.e. the minimum number they can form by adding them) in an array for each digit from 1 to 150. then we will loop throw the array from 1 to 150 and sum .. this will be too fast. I think this is enough to start going and invest some effort in this path. I already solved this problem 2 years before. But I will NEVER share the solution and I ask everyone not to share the solutions of projecteuler problems because this is against the conditions of the website. If you can't solve it. You should give it some time or learn some needed topics but never ask anyone for the solution. at most, you can take some hints to help you work on the problems. This moment really worth and by taking other people solution you will lose this moment
{ "domain": "codereview.stackexchange", "id": 43860, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, python-3.x, programming-challenge, time-limit-exceeded", "url": null }
python, beginner, hangman Title: Hangman game succesfully built Question: I have completed the Hangman game. Can somebody look at the code and see what I've done wrong? What should I add to improve it? Are there any bugs in it? import random word_list = ['sleep','window'] get_word = random.randint(0,len(word_list)-1) get_word = word_list[get_word] result = ["_"] * len(get_word) x = "_" * len(get_word) print(x) attempts = 5 guessed = [] missed = [] while attempts != 0: print("Enter a letter: ") guess = input() if len(guess) == 1: for index,value in enumerate(get_word): if guess == value: result[index] = value print("You guessed right") else: if guess not in get_word: attempts -= 1 missed.append(guess) print("Sorry the letter ", guess , "is not in the word." ,"Now you have" , attempts , "attempts") if attempts == 0: print("You didn't guess the word.The word was" , get_word) print("".join(result),"\nMissed letters are: ", missed , "\t") if "_" not in result: result = "".join(result) if result == get_word: print("Congratulations! You guessed all the letters") break
{ "domain": "codereview.stackexchange", "id": 43861, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, hangman", "url": null }
python, beginner, hangman Answer: PEP-8 First off, as mentioned by GregOliveira in the comments, by PEP-8 you don't need the entire program indented (and indeed, it won't run as written). You do, however, need spaces before/after operators, after commas, etc. Getting a linter such as pylint or flake8 will highlight these and make writing good code easier. Also, your variable names are not terribly clear get_word (sounds more like a verb) might be target_word for example. Handling input Because we're taking input from the user, we want to make sure we're handling it appropriately. Currently you are testing the bare input and merely checking whether it is 1 character. We need to consider carefully about what we consider valid input and not, for example, punish the player for entering an upper-case letter, entering the same guess multiple times, entering a character which isn't a letter at all. Instead of: guess = input("Enter a letter: ") if len(guess) == 1: We could do: from string import ascii_lowercase # Or we could define our own set of valid characters [...] while True: guess = input("Enter a letter:") guess = guess.lower() # Handle capital letters by downcasing all of them if len(guess) != 1: print(f"Invalid guess '{guess}', must be a single character") elif guess not in ascii_lowercase: print(f"Invalid guess '{guess}', must be one of {', '.join(ascii_lowercase)}") elif guess in missed or guess in result: print(f"Invalid guess '{guess}', already guessed.") else: break N.B. This is also a good opportunity to use a function. Python Functions The Python module random contains the random.choice function (try running the help(random) function in the Python shell to see what functions things have). This function selects one element from a sequence (i.e. your list), so: get_word = random.randint(0, len(word_list)-1) get_word = word_list[get_word] Becomes get_word = random.choice(word_list)
{ "domain": "codereview.stackexchange", "id": 43861, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, hangman", "url": null }
python, beginner, hangman Becomes get_word = random.choice(word_list) You also have what appears to be some remnants of old code floating around. E.g. x = "_" * len(get_word) print(x) Where later, you use the more Pythonic: print("".join(result),"\nMissed letters are: ", missed , "\t") ^ "".join(result) The input function takes a prompt argument: input(prompt=None, /) Read a string from standard input. The trailing newline is stripped. The prompt string, if given, is printed to standard output without a trailing newline before reading input. If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError. On *nix systems, readline is used if available. Instead of: print("Enter a letter: ") guess = input() We can simply use guess = input("Enter a letter: ") Functionality In this part: for index,value in enumerate(get_word): if guess == value: result[index] = value print("You guessed right") else: You align the else with the for which is probably not what you intend. else on the for is executed if the for loop exits naturally rather than through a break statement. Which in your case it always does. What you probably intend is: if guess in get_word: print("You guessed right") # This also allows us to avoid printing this multiple times for each time the character appears in the word for index,value in enumerate(get_word): if guess == value: result[index] = value else: attempts -= 1 missed.append(guess) print("Sorry the letter ", guess , "is not in the word." ,"Now you have" , attempts , "attempts") if attempts == 0: print("You didn't guess the word.The word was" , get_word) However, we can use this to test whether we have used up all our attempts (since we break on success): while attempts > 0: [...] <if correct>: break else: print("You didn't guess the word. The word was" , get_word)
{ "domain": "codereview.stackexchange", "id": 43861, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, hangman", "url": null }
python, beginner, hangman Cleaning up We also don't really need to check whether _ is in our result before testing its validity, we can just straight up test whether we have the right answer. We can also use f-strings to clean up some of the print statements. print("Sorry the letter ", guess, "is not in the word.", "Now you have", attempts, "attempts") Becomes: print(f"Sorry the letter {guess} is not in the word. You have {attempts} attempts remaining.") Putting it all together If we put all these things together, we end up with something that looks like: """ Play a simple hangman game """ import sys import random from string import ascii_lowercase WORD_LIST = ['sleep', 'window'] def get_user_guess() -> str: while True: guess = input("Enter a letter:").lower() if len(guess) != 1: print(f"Invalid guess '{guess}', must be a single character") elif guess not in ascii_lowercase: print(f"Invalid guess '{guess}', must be one of {', '.join(ascii_lowercase)}") elif guess in missed or guess in result: print(f"Invalid guess '{guess}', already guessed.") elif not guess: # Handle user giving up to_quit = input("Giving up? [y/N]") if to_quit.lower() == "y": sys.exit() else: break return guess target_word = random.choice(WORD_LIST) result = ["_"] * len(target_word) print("".join(result)) attempts = 5 guessed = [] missed = [] while attempts > 0: guess = get_user_guess() if guess in target_word: print("You guessed right") for index, value in enumerate(target_word): if guess == value: result[index] = value else: attempts -= 1 missed.append(guess) print(f"Sorry the letter {guess} is not in the word." f"You have {attempts} attempts remaining.") print("".join(result))
{ "domain": "codereview.stackexchange", "id": 43861, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, hangman", "url": null }
python, beginner, hangman print("".join(result)) if "".join(result) == target_word: print("Congratulations! You guessed all the letters") break print(f"Missed letters are: {', '.join(missed)}.") else: print(f"You didn't guess the word. The word was {target_word}.")
{ "domain": "codereview.stackexchange", "id": 43861, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, hangman", "url": null }
java, game, backtracking, battleship Title: Putting as many ships on a square board as possible Question: Github repository Origanally I wrote a program that let you play battleship against the computer. Pretty easy: create a number of ships generate random cells for all the ships let the user try to guess I implemented a way to place as many ships as possible: If I have a 3x3 board and I want to place 4 ships that are 2 cells long, there are only few placements that allow the maximum number of ships in the board. Example correct placement: |1|1|O| |2|2|4| |3|3|4| Example wrong placement: |0|1|1| |2|2|0| |0|3|3| Code(full code on github): public void prepareGame(){ if (!(field_size*field_size/ship_length >= ship_numbers)){ System.out.println("Error: Game numbers are invalid"); System.exit(0); } for (int i = 0; i < ship_numbers; i++) { Ships.add(new Ship(); } ArrayList<String> toTest; int leftToPlace = ship_numbers; for (Ship ship : Ships){ System.out.println("generating cells for "+ship); while(true){ toTest = generateCells(); if (!checkShips(toTest)){ if(backtrackShips(toTest, leftToPlace)){ ship.setShip(toTest); System.out.println("success for "+ship+" "+toTest); System.out.println(); leftToPlace--; break; } } } } } private boolean backtrackShips(ArrayList<String> toBacktrack, int shipsToPlace){ boolean backtrack_result = false; ArrayList<String> cells; ArrayList<ArrayList<String>> givenCells = new ArrayList<>(); for (int i = 0; i < (ship_numbers - shipsToPlace); i++) { givenCells.add(Ships.get(i).getCells()); } //System.out.println("backtracking: "+toBacktrack); //System.out.println("given cells before backtrack: "+ givenCells); givenCells.add(toBacktrack); shipsToPlace--;
{ "domain": "codereview.stackexchange", "id": 43862, "lm_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, game, backtracking, battleship", "url": null }
java, game, backtracking, battleship for (int i = 0; i < shipsToPlace; i++) { for (int j = 0; j < 1000; j++) { cells = generateCells(); // check if cells lap over already chosen cells for (ArrayList<String> list : givenCells) { if (Collections.disjoint(list, cells)) { backtrack_result = true; } else if (!Collections.disjoint(list, cells)) { backtrack_result = false; break; } } if(backtrack_result) { givenCells.add(cells); break; } } } if (shipsToPlace == 0) { //base-case backtrack_result = true; } //System.out.println("given cells after backtrack: "+ givenCells); return backtrack_result; } public boolean checkShips(ArrayList<String> cells){ boolean result = false; for (Ship ship : Ships){ if (!Collections.disjoint(cells, ship.getCells())){ result = true; } } return result; } If you want to know the Ship Class: package src; import java.util.ArrayList; public class Ship { ArrayList<String> cells = new ArrayList<>(); public void setShip(ArrayList<String> cells){ this.cells = cells; } public ArrayList<String> getCells(){ return this.cells; } public String checkYourself(String stringTip){ String result = "Miss"; if (this.cells.contains(stringTip)){ result = "Hit"; this.cells.remove(stringTip); } if (this.cells.isEmpty()) { result = "submerged"; } return result; } } I have basically two questions. Is this backtracking? Where can I optimize the code? Edit: changed naming of ships.
{ "domain": "codereview.stackexchange", "id": 43862, "lm_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, game, backtracking, battleship", "url": null }
java, game, backtracking, battleship Answer: Code style The formatting and naming is inconsistent and violates common Java conventions, but these things are also very easy to fix. All IDEs and some advanced text editors have features to quickly format the whole code, as well as to easily rename identifiers in all occurrences at once. Many style guides can be found online for most programming languages and I would recommend choosing one and applying it consistently. Some examples: if (something) { vs. if(something){ and similar variations. I would expect the first one in all cases as the de-facto standard format, but your chosen style guide should set the rules. Rather than fixing these individually, I would recommend using the IDEs auto-formatting feature to fix the format of the whole file, as well as to be intentional with the correct format already while typing it. ship_numbers should be shipNumbers, etc. Generally Java uses camel case for variable names. Naming Clear names are important to ensure that you and others understand the intent of the code and to avoid misunderstandings that can easily lead to bugs or just make it very tedious to maintain the code. Some examples: checkShips : What exactly does this method check? What does if (checkShips(cells)) tell me? Looking at the implementation, and knowing the game, it seems like the intent is to check for a collision, so something like isCollision would be much clearer. isOccupied would be another possible option. In general, I do not recommend wording boolean methods as commands, because of how if (checkShips()) or even if (checkCollision()) sounds. A further improvement, in my opinion, would be to pass the ships as another argument to the method, so that it reads like doesCollide(cells, ships), because it is more explicit and tells the reader the whole context. Otherwise it is implicit regarding what can collide with those cells.
{ "domain": "codereview.stackexchange", "id": 43862, "lm_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, game, backtracking, battleship", "url": null }
java, game, backtracking, battleship setShips (within the Ship class): It is already within the context of a ship, so what would ship.setShip(cells) mean? Since the method actually sets the cells of the ship, setCells would make more sense. (The fact that having a setter at all might be problematic is a separate, more high-level point which I will not cover in this review, but potentially in a separate one with updated code.) shipNumbers : Even after reading the code I am still not completely sure what this means. The names should make it easier to understand the context of the code, rather than requiring context to decipher their meaning. maxNumberOfShips might be clearer, assuming that my interpretation is correct. toTest : To test what? Some suggestions: In the context of checkShips(), toCheck might be a slight improvement. cellsToCheck would be clearer. candidateCells makes sense in this case, since they are randomly generated and then checked against some rules (in this case having no collisions with existing ships). randomCells is less explicit about the intended use, but more explicit about its own meaning/origin. Simplicity/readability checkShips() Current version: public boolean checkShips(ArrayList<String> cells){ boolean result = false; for (Ship ship : Ships){ if (!Collections.disjoint(cells, ship.getCells())){ result = true; } } return result; } Suggestion 1: There is no need to iterate over all ships if the result is never reset to false again. Instead we can simply return true after the first match, and return false by default. Thus it already becomes much easier to reason about what can be returned in what case, since you can be sure that the return value is not being altered again afterwards. public boolean checkShips(ArrayList<String> cells) { for (Ship ship : Ships) { if (!Collections.disjoint(cells, ship.getCells())){ return true; } } return false; } Suggestion 2:
{ "domain": "codereview.stackexchange", "id": 43862, "lm_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, game, backtracking, battleship", "url": null }
java, game, backtracking, battleship Suggestion 2: The functional approach using Java streams is even less error prone, shorter and easier to understand. public boolean checkShips(ArrayList<String> cells) { return ships.stream() .anyMatch(ship -> { !Collections.disjoint(cells, ship.getCells()) }); } Suggestion 3: Assuming we renamed the method to isCollision and passed the ships as argument, as suggested earlier, we can extract a second method with the same name but for a single ship, thus reducing the number of things done by each method per abstraction level. public boolean isCollision(List<String> cells, List<Ship> ships) { return ships.stream() .anyMatch(ship -> isCollision(cells, ship)); } private boolean isCollision(List<String> cells, Ship ship) { return !Collections.disjoint(cells, ship.getCells()); } Debugging and commented-out code //System.out.println("backtracking: "+toBacktrack);
{ "domain": "codereview.stackexchange", "id": 43862, "lm_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, game, backtracking, battleship", "url": null }
java, game, backtracking, battleship Debugging and commented-out code //System.out.println("backtracking: "+toBacktrack); These statements seem to have been used for debugging, but they clutter the code and make it harder to read. I recommend removing them and using an actual debugger instead. Of course there is nothing wrong with quickly adding a print statement temporarily to quickly check something, but it should be removed again before regarding the code as finished. This applies to commented-out code in general: If it is not needed anymore, it should be deleted. If it is simply commented out, how will you know later on whether it can be deleted or should be uncommented? Like most people, you would probably not be sure and ignore it, and thus it resides in the code base forever as a piece of commented-out code that does not add any value. Next steps There are (as is often the case) many more things that can be improved, but I would keep it at that for a first code review iteration focusing on lower level problems that are rather easy to fix and also easy to prevent in future code. Feel free to post a follow-up with an updated version of the code. Further iterations could cover more high-level concepts like design, OOP, layering etc.
{ "domain": "codereview.stackexchange", "id": 43862, "lm_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, game, backtracking, battleship", "url": null }
python, python-3.x, validation, iterator Title: Dont let duplicated values in Iterator return of a function Question: I'm trying to build a function to return an Iterator with no duplicated float values, its working, but there is a better way of handling this duplicated values? from collections import deque from collections.abc import Iterator from locale import atof def get_non_repeated_numbers(n: int) -> Iterator[float]: """ Yields n float values to return Iterator :param n: int :return: Iterator[float] """ numbers = deque() for i in range(n): while True: try: number = atof( input(f'Enter the {i + 1}ΒΊ number:\n-> ') ) if number not in numbers: numbers.append(number) yield number break else: raise ValueError except ValueError: print('Invalid number! Try again...\n') Answer: Overall pretty reasonable. Use a set() instead of a deque() so that you have O(1) amortised time complexity for insertion and membership checks. Since you have to build up a set anyway: if it's unimportant to process the numbers as they come in (which it probably isn't, but you haven't shown us) and the order of the numbers doesn't matter, just drop the iterator and return the set. If the order is important, you could build up and then return the keyset of an OrderedDict (or a regular dict that guarantees insertion order preservation for sufficiently modern Python).
{ "domain": "codereview.stackexchange", "id": 43863, "lm_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, validation, iterator", "url": null }
python, performance Title: list possible combinations of pairs of actions for stocks Question: What do you suggest to make this code faster? This code gets all possible combinations of actions for a certain number of stocks in pairs in the format [action, volume]. One action element would be something like [[action1,volume1],[action2,volume2],[action3,volume3]] where the actions are either 0 (i.e. Sell) or 1 (i.e. Buy) and elements with volume = 0 correspond to Hold. The volumes values will go from 0 to max_transactions, which does the function of a ceiling for the max transactions enabled per step. The use cases will be something like num_stocks=5 and max_transactions = 100 which takes more than one hour. import more_itertools import numpy as np from copy import deepcopy from enum import Enum class Actions(Enum): Sell = 0 Buy = 1 Hold = 2 def get_possible_actions(num_stocks, max_transactions): actions = [i for i in range(len(Actions)-1)]*num_stocks # in this env we have only Sell and Buy in the action combos list, because Hold will be represented by the elements with vol=0 volumes = [i for i in range(max_transactions+1)]*num_stocks # we have a plus 1 here to include the elements with vol=0, the elements that represent hold of each stock act_combos = list(more_itertools.distinct_permutations(actions,num_stocks)) vol_combos = list(more_itertools.distinct_permutations(volumes,num_stocks)) possible_actions = [] for i in range(len(act_combos)): act_combo = deepcopy(act_combos[i]) for j in range(len(vol_combos)): vol_combo = deepcopy(vol_combos[j]) action = [] for z in range(num_stocks): action.append([act_combo[z],vol_combo[z]]) # each combination has the len of num_stocks, because it represents a chosen action for each stock, and to each stock will have # associated a pair [action,volume] possible_actions.append(action)
{ "domain": "codereview.stackexchange", "id": 43864, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance", "url": null }
python, performance return possible_actions Answer: I mean it won't solve your problem entirely because your problem as specified is so large, it will take a long time (see RootTwo's comments). (Also, I'm not sure why you would say more_itertools is C, the source is available) However, in general, you should be using generators for these large tasks, which is what itertools returns by default. "Generators" are iterables which only create the result on demand, so they (usually) don't take up much storage (allocation takes time) and they can be drawn from only as much as you need (rather than having to all exist first), though only once per generator (they do not store their history). Your function seems to just be doing: def get_possible_actions(num_stocks: int, max_transactions: int): actions = (i for i in range(len(Actions)-1) for _ in range(num_stocks)) volumes = (i for i in range(max_transactions+1) for _ in range(num_stocks)) # N.B. will not be sorted, will create a tuple the size of the Cartesian product (i.e. n_actions*max_transactions*num_stocks**2) return more_itertools.distinct_combinations(itertools.product(actions, volumes), num_stocks) With the generator we can loop over them: for elem in get_possible_actions(2, 3): print(elem) ... Transform them (filter also returns a generator): q = filter(lambda x: x[2] == 3, get_possible_actions(2, 3)) Or even transform them into a list when we've set up the final structure (requires generating all the values at once): acts = list(get_possible_actions(2, 3))
{ "domain": "codereview.stackexchange", "id": 43864, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance", "url": null }
c, linked-list Title: Intrusive linked list in C Question: I've been working on an intrusive linked list for the past few days for a personal project and I would like to have some feedback on it. :) Personally, I would have preferred to make List and ListNode opaque. However, (I may be wrong here) that means I can only use pointers to them which would mean I have to use ListNode ** to calculate offsets correctly and that makes things complicated... list.h #ifndef LIST_H_INCLUDED_ #define LIST_H_INCLUDED_ #include <stdbool.h> #include <stddef.h> #define INIT_LIST_NODE (ListNode) { \ .next = NULL, \ .prev = NULL, \ } #define list_new(type, member, ...) list_new_(offsetof(type, member), __VA_ARGS__) typedef struct ListNode_ ListNode; struct ListNode_ { ListNode *next; ListNode *prev; }; typedef struct { void (*dtor)(void *); } ListVtable; typedef struct { ListNode *head; size_t offset; ListVtable *vtable; } List; List *list_new_(const size_t offset, ListVtable *vtable); bool list_is_empty(List *list); size_t list_size(List *list); void *list_get(List *list, const size_t pos); void list_insert(List *list, void *data, const size_t pos); void list_prepend(List *list, void *data); void list_append(List *list, void *data); void list_remove(List *list, const size_t pos); void list_delete(List **list); #endif list.c strict_malloc does the same thing as xmalloc would. #include "list.h" #include "memory.h" #include <assert.h> #include <stdbool.h> #include <stdlib.h> ListNode *new_sentinel_node(void) { ListNode *node = strict_malloc(sizeof(*node)); node->next = NULL; node->prev = NULL; return node; } static ListNode *init_sentinel_nodes(void) { ListNode *head_sentinel = new_sentinel_node(); ListNode *tail_sentinel = new_sentinel_node(); head_sentinel->next = tail_sentinel; tail_sentinel->prev = head_sentinel; return head_sentinel; }
{ "domain": "codereview.stackexchange", "id": 43865, "lm_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, linked-list", "url": null }
c, linked-list List *list_new_(const size_t offset, ListVtable *vtable) { List *list = strict_malloc(sizeof(*list)); list->head = init_sentinel_nodes(); list->offset = offset; list->vtable = vtable; return list; } static inline bool is_sentinel_node(ListNode *node) { return node->next == NULL || node->prev == NULL; } static inline ListNode *front_node(List *list) { return list->head->next; } bool list_is_empty(List *list) { return is_sentinel_node(front_node(list)); } static inline ListNode *get_node(List *list, void *data) { return (ListNode *) (((char *) data) + list->offset); } static inline void *get_container(List *list, ListNode *node) { return (void *) (((char *) node) - list->offset); } size_t list_size(List *list) { ListNode *current_node = front_node(list); size_t size = 0; while (!is_sentinel_node(current_node)) { size++; current_node = current_node->next; } return size; } void *list_get(List *list, const size_t pos) { ListNode *current_node = front_node(list); assert(pos < list_size(list)); for (size_t i = 0; i < pos && !is_sentinel_node(current_node->next); i++) { current_node = current_node->next; } return get_container(list, current_node); } static bool contains_node(List *list, ListNode *node) { ListNode *current_node = list->head; while (current_node != NULL) { if (current_node == node) { return true; } current_node = current_node->next; } return false; } void list_insert(List *list, void *data, const size_t pos) { ListNode *current_node = front_node(list); ListNode *node = get_node(list, data); assert(pos <= list_size(list)); assert(!contains_node(list, node));
{ "domain": "codereview.stackexchange", "id": 43865, "lm_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, linked-list", "url": null }
c, linked-list assert(pos <= list_size(list)); assert(!contains_node(list, node)); for (size_t i = 0; i < pos && !is_sentinel_node(current_node); i++) { current_node = current_node->next; } node->prev = current_node->prev; current_node->prev->next = node; node->next = current_node; current_node->prev = node; } void list_prepend(List *list, void *data) { list_insert(list, data, 0); } void list_append(List *list, void *data) { list_insert(list, data, list_size(list)); } static void delete_node(List *list, ListNode *node) { if (is_sentinel_node(node)) { free(node); return; } if (list->vtable->dtor != NULL) { list->vtable->dtor(get_container(list, node)); } } void list_remove(List *list, const size_t pos) { if (list_is_empty(list)) { return; } ListNode *current_node = front_node(list); assert(pos < list_size(list)); for (size_t i = 0; i < pos && !is_sentinel_node(current_node->next); i++) { current_node = current_node->next; } current_node->prev->next = current_node->next; current_node->next->prev = current_node->prev; delete_node(list, current_node); } void list_delete(List **list) { ListNode *current_node = (*list)->head; while (current_node != NULL) { ListNode *next_node = current_node->next; delete_node(*list, current_node); current_node = next_node; } FREE_AND_NULL(list); } demo.c #include "list.h" #include <stdio.h> #include <stdlib.h> struct dummy { int *x; ListNode node; }; struct dummy *new_dummy(int x) { struct dummy *d = malloc(sizeof(*d)); d->x = malloc(sizeof(int)); *d->x = x; d->node = INIT_LIST_NODE; return d; } void free_dummy(void *d) { struct dummy *tmp = d; free(tmp->x); free(tmp); } int main(void) { List *dummy_list = list_new(struct dummy, node, &(ListVtable) { .dtor = free_dummy, });
{ "domain": "codereview.stackexchange", "id": 43865, "lm_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, linked-list", "url": null }
c, linked-list for (int i = 0; i < 10; i++) { list_append(dummy_list, new_dummy(i)); }; for (int i = 0; i < 5; i++) { list_remove(dummy_list, 0); } for (size_t i = 0; i < list_size(dummy_list); i++) { struct dummy *tmp = list_get(dummy_list, i); printf(" %d ", *tmp->x); } printf("\n"); list_delete(&dummy_list); return EXIT_SUCCESS; } Answer: You are quite right that intrusive linked list and opaque data-structure are mutually exclusive. That is, you could hide all the list-stuff in each node behind a pointer, but the extra-allocation negates all advantages of being intrusive. Your intrusive linked list is quite limited, as you only allow membership in a single one. By all means, have a name for the default one, but allow the user to name it himself so there is no conflict for multiples. Put all the list-type dependent stuff in the same place, instead of part with the head-pointer, and part in referenced data. Actually, read on. Too much automation by dynamic data means too much inefficiency. For an intrusive linked list, it contravenes the rationale for having one at all. Let the user provide the name on each use, and only provide dereferencing, linking, unlinking, and iterating, not anything else. Make it a circular linked list, potentially including the origin which is not part of an element, and you can avoid most special cases. In the end, your intrusive linked list will be header-only, consisting of a single type and less than a handful macros.
{ "domain": "codereview.stackexchange", "id": 43865, "lm_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, linked-list", "url": null }
c++, beginner, object-oriented, linked-list Title: Linked List implemented in C++ Question: I have a linked list code in C++: #include <string> #include <iostream> using namespace std; class Node { public: string name; int age; Node *next; Node(string name, int age) { this->name = name; this->age = age; this->next = nullptr; } }; class List { private: Node *head; int size; public: List() { this->head = nullptr; this->size = 0; } void insert(string name, int age) { Node *nodenew = new Node(name, age); nodenew->next = nullptr; if (this->head == nullptr) { this->head = nodenew; } else { Node *auxi = this->head; while (auxi->next != nullptr) { auxi = auxi->next; } auxi->next = nodenew; } this->size = this->size + 1; } void print() { if (this->head == nullptr) { cout << "List is empty"<<endl; } Node *auxi = this->head; cout<<to_string(this->size)+" users in the linked list"<<endl; while (auxi != nullptr) { cout << auxi->name << ", " << auxi->age << endl; auxi = auxi->next; } } void deleteList(){//this method Node* prev = this->head; this->size = 0; while (this->head) { this->head = head->next; delete(prev); prev = this->head; } } };
{ "domain": "codereview.stackexchange", "id": 43866, "lm_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, object-oriented, linked-list", "url": null }
c++, beginner, object-oriented, linked-list int main() { List linkedList; linkedList.insert("David", 56); linkedList.insert("Susan", 25); linkedList.insert("Kim", 41); linkedList.insert("Charles", 23); linkedList.print(); linkedList.deleteList(); //inserting data again after deleting all data in the linked list linkedList.insert("Bob", 20); linkedList.insert("James", 75); linkedList.insert("Carl", 36); linkedList.insert("Andy", 78); linkedList.deleteList(); linkedList.print(); return 0; } I get in console the correct output: 4 users in the linked list David, 56 Susan, 25 Kim, 41 Charles, 23 List is empty 0 users in the linked list But, I think should be some way to improve my deleteList() method. This method get empty my linked list object. I tried to make it more efficient, but I couldn't. I hope you can help me with that or anything more in my linked list code, thanks. Answer: Defeating namespacing Don't using namespace std; ever! It pollutes your local namespace. If the standard ever added std::Node, std::List, std::linkedList or any other of your identifiers, your code will break. Leave all std:: namespace identifiers in the std:: namespace. It is permissible to pull a few std:: namespace identifiers into your local namespace on a case by case basis. Eg) #include <string> #include <iostream> using std::string; using std::cout; class Node { ... By explicitly pulling in only the ones you are using, you won't run into any surprises when something new is added to the standard. As mentioned by Toby Speight: In the using examples, consider showing that using std::cout; could (should) have tighter scope, as it's only used within the print() function. I think that's better practice than bringing it into top-level scope. #include <string> #include <iostream> using std::string; class Node { ... }; class List { ... void print() { using std::cout; ... } ... }; ...
{ "domain": "codereview.stackexchange", "id": 43866, "lm_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, object-oriented, linked-list", "url": null }
c++, beginner, object-oriented, linked-list class List { ... void print() { using std::cout; ... } ... }; ... This is extremely important when it comes to header files. You certainly would not want to force someone who uses your header file have unnecessary identifiers dragged into their scope. For example, if you were to separate your interface and implementations, your interface might look like: custom_node_list.h: #include <string> class Node { using std::string; public: string name; int age; Node *next; Node(string name, int age); }; class List { using std::string; private: Node *head; int size; public: List(); void insert(string name, int age); void print(); void deleteList(); }; Now string is only an alias for std::string when inside the Node and List class namespaces. Someone using your classes for their own needs could define their own string without confusion. Don't endl When you want a newline, you almost never want << std::endl; since that does two different things. it adds the \n to the output stream, and it flushes the stream The latter operation use usually unnecessary, and can significantly degrade the performance of your program due to unnecessary flushing. Simply use cout << "List is empty\n"; Unnecessary string conversion The to_string(this->size) in cout<<to_string(this->size)+" users in ... is unnecessary. You don't have to combine the integer and the string into one larger string for output. Simply emit both into the stream one after the other: cout << this->size << " users in the linked list\n"; deleteList efficiency To your main concern: you're writing to memory unnecessarily: this->head = head->next;
{ "domain": "codereview.stackexchange", "id": 43866, "lm_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, object-oriented, linked-list", "url": null }
c++, beginner, object-oriented, linked-list If you were deleting just the head node, the above operation would be necessary. However, after deleting the head node, you will be deleting the next head node, and then the next, and so on., each time updating the this memory structure for each step. The final state will be: this->head = nullptr; this->size = 0; there is no need for the intermediate writes. void deleteList() { Node* node = this->head; while (node) { Node *next = node->next; delete node; node = next; } this->head = nullptr; this->size = 0; }
{ "domain": "codereview.stackexchange", "id": 43866, "lm_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, object-oriented, linked-list", "url": null }
performance, strings, linux, assembly, amd64 Title: Remove leading zeroes from the beginning of a string Question: I want to remove leading zeroes (for a big integer library I'm currently making) in numbers represented as char arrays. I chose assembly for speed, but in order to simplify making the algorithm and all, I decided to write it in C first. Here's the algorithm, written in C. void remove_leading_zeroes(char *number) { char *answer = (char *)malloc(strlen(number) + 1); bool encounteredNonZero = false; size_t ptr = 0; for (size_t i = 0; i < strlen(number); i++) { if (number[i] != '0') encounteredNonZero = true; if (encounteredNonZero) { answer[ptr] = number[i]; ptr++; } } if (!encounteredNonZero) { answer[ptr] = '0'; ptr++; } answer[ptr] = 0; strcpy(number, answer); free(answer); } Also, just before translating to assembly, I like to rename variables with their register equivalents in assembly. This makes it easier for me to translate. Here's the code for that (again C). void remove_leading_zeroes(char *rdi) { char *rsp = (char *)malloc(strlen(rdi) + 1); bool cl = false; size_t r8 = 0; size_t r9 = 0; do { if (rdi[r9] != '0') cl = true; if (cl) { rsp[r8] = rdi[r9]; r8++; } r9++; } while (r9 < strlen(rdi)); if (!cl) { rsp[r8] = '0'; r8++; } rsp[r8] = 0; r9 = 0; do { rdi[r9] = rsp[r9]; r9++; } while (r9 < r8); rdi[r9] = 0; free(rsp); } And finally, the assembly code I wrote. I'm an amateur, so any suggestions on how to make this faster, or any good practice I missed would be awesome. extern strlen section .text global _remove_leading_zeroes _remove_leading_zeroes: ; Input: ; - char *number -> rdi. The result will be stored in the same string. ; Registers used: ; - rax ; - rcx ; - rdx ; - r8 ; - r9
{ "domain": "codereview.stackexchange", "id": 43867, "lm_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, strings, linux, assembly, amd64", "url": null }
performance, strings, linux, assembly, amd64 ; Registers used: ; - rax ; - rcx ; - rdx ; - r8 ; - r9 push rbp mov rbp, rsp call strlen inc rax sub rsp, rax dec rax xor cl, cl xor r8, r8 xor r9, r9 _remove_leading_zeroes_loop_1: cmp byte [rdi + r9], 48 jz _after_remove_leading_zeroes_if_1 mov cl, 1 _after_remove_leading_zeroes_if_1: test cl, cl jz _after_remove_leading_zeroes_if_2 mov dl, byte [rdi + r9] mov byte [rsp + r8], dl inc r8 _after_remove_leading_zeroes_if_2: inc r9 cmp r9, rax js _remove_leading_zeroes_loop_1 test cl, cl jnz _after_remove_leading_zeroes_if_3 mov byte [rsp + r8], 48 inc r8 _after_remove_leading_zeroes_if_3: mov byte [rsp + r8], 0 xor r9, r9 _remove_leading_zeroes_loop_2: mov dl, byte [rsp + r9] mov byte [rdi + r9], dl inc r9 cmp r9, r8 js _remove_leading_zeroes_loop_2 mov byte [rdi + r9], 0 leave ret (I use my own strlen function which only modifies rcx)
{ "domain": "codereview.stackexchange", "id": 43867, "lm_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, strings, linux, assembly, amd64", "url": null }
performance, strings, linux, assembly, amd64 Answer: For style and formatting, your asm is pretty good except for label names. Correctly indented, and some intro comments about register usage. But missing comments about even the major steps of the algorithm on any of the instructions or labels. It would also help to leave a blank line after the end of a loop, so it's easier to see that later code isn't going to jump back into it. It's a good place to put a comment about what invariants are now true, or what the next code does. As other answers point out, your algorithm is doing way too much work, using malloc/free (and in asm, effectively alloca) and copying your data twice, instead of just figuring out how far to memmove it. Beyond that, you have multiple other major and minor implementation details that could be more efficient. (Important background reading: https://agner.org/optimize/ has lots of important micro-optimization stuff, some of which I'm going to point out specifically. If you don't know what micro-uops (uops) are, go read Agner's asm optimization guide and micro-architecture guide. Also this SO Q&A and/or some of the links from my answer. Also a good idea to use compiler-generated asm as a starting-point for your hand-written asm, because compilers generally get the small details right, and might lay out the branching nicely. (If not you can try [[likely]] somewhere and try again).) Also, not using SIMD means you can at best check 1 byte at a time, not 16 or 32. SSE2 is baseline for x86-64, so any string processing like this should be using SIMD unless you expect strings to be tiny, like less than 8 bytes or so. (Or as a baby-steps learning exercise just to write correct scalar code, not useful for performance.) With some loop unrolling, scalar could possibly check 2 bytes per clock cycle, but branching on a SIMD compare takes more work. Still a big speedup available.
{ "domain": "codereview.stackexchange", "id": 43867, "lm_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, strings, linux, assembly, amd64", "url": null }
performance, strings, linux, assembly, amd64 You might hope that a good C compiler could optimize simple loops to use SIMD, but unfortunately existing compilers like GCC and clang can only auto-vectorize loops where the trip-count can be computed before the first iteration. i.e. not search loops with a data-dependent exit condition. (ICC can sometimes vectorize search loops, and sometimes even do a decent job at it IIRC.) So this is actually a problem where it does make sense to get your hands dirty and use SIMD intrinsics. There's little need to hand-write anything in assembly, though, especially for x86 where compilers do a good job with intrinsics. You might also hope that repe scasb would be efficient, but it's not, unfortunately. Only the unconditional rep movs and rep stos instructions have Fast Strings microcode. (See Why is this code using strlen heavily 6.5x slower with GCC optimizations enabled? for how GCC used to inline an inefficient strlen at -O1 or -O2 in some cases, vs. my simple example of a 16-byte-at-a-time SSE2 implementation that assumes an aligned buffer.) Use more concise label names, prefer NASM local labels like .else: Asm label names are private to the current file, like static function names or goto labels within a function in C. You don't need to make them globally unique since you're not using global foo to export them. It took me half a minute or so to figure out the naming pattern with labels like _after_remove_leading_zeroes_if_1 vs. _remove_leading_zeroes_loop_2. The "if" vs. "loop" part is a very small part of the label. It seems obvious in hindsight once you know where to look, but on reading the code for the first time, my reaction was "what is this mess of mostly-redundant long label names? Hard to see what jumps where". Then wondering why are there two different _2 labels, then finally seeing the if vs. while naming (which also apparently go with _after_remove... vs. _remove... for no apparent reason since the last label in the function isn't named "after".
{ "domain": "codereview.stackexchange", "id": 43867, "lm_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, strings, linux, assembly, amd64", "url": null }
performance, strings, linux, assembly, amd64 Meaningful label names are tricky, so yeah you might sometimes just give up and number them from a common base. In NASM, .bar: following a non-dot label like foo: is the same as foo.bar:, so it lets you use short label names but still avoid name conflicts with the rest of your file. So you could have asm like remove_leading_zeroes: ; in Linux ELF, C names don't get leading underscores ... je .no_lz ; else fall through
{ "domain": "codereview.stackexchange", "id": 43867, "lm_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, strings, linux, assembly, amd64", "url": null }
performance, strings, linux, assembly, amd64 .find_nonzero: ... jne .find_nonzero .strmove: ; in-place strcpy to fill the gap ... jne .strmove .no_lz: ; return without copying anything ret Make two loops instead of branching inside loops do { if (rdi[r9] != '0') cl = true; if (cl) { rsp[r8] = rdi[r9]; r8++; } r9++; } while (r9 < strlen(rdi));
{ "domain": "codereview.stackexchange", "id": 43867, "lm_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, strings, linux, assembly, amd64", "url": null }
performance, strings, linux, assembly, amd64 This is searching for the first non-'0' byte in the input string, and then copying the rest of the string to another buffer. There's no reason to put those two things into one loop, and force yourself to write asm that branches inside each iteration to figure out what to do that iteration. It wastes at least one uop every iteration, and one side of the if is going to have an extra taken branch every iteration for that phase. (Taken branches are more expensive for the front-end, since code-fetch isn't contiguous and branch prediction has to provide a correct prediction of the new place to fetch from early enough to avoid a bubble. Also, on Haswell and later, predicted-taken jump uops can only execute on port 6; the other ALU port that can check branch predictions can only handle predicted-not-taken branches.) There's no upside; it would be more efficient to make a simple search loop, and then strcpy (manually implemented or not). If you need some extra logic to detect the case of an all-zero string, that logic can be outside any loops. Small static code-size is nice, but fewer instructions inside loops is usually more important. I think the simplest way to handle the possibility of an input like "0000" or the empty string is to copy the first byte unconditionally, before doing anything else. That also lets the CPU get started on getting write access to the output buffer, in case it was cold in cache or TLB, letting out-of-order exec hide latency. Normally not a factor for stack space, it's usually hot in cache. (If you can't allocate the output buffer until after reading all of the input to calculate the size, that's unfortunate. Depending on your allocator, over-allocating and then using realloc to give back a chunk at the end might be ok.)
{ "domain": "codereview.stackexchange", "id": 43867, "lm_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, strings, linux, assembly, amd64", "url": null }
performance, strings, linux, assembly, amd64 Of course this problem goes away when you're doing it in-place, not copying to a separate buffer. Once you make that other algorithmic change, you can't use ISO C strcpy since it has undefined behaviour if the src and dst overlap. So you would need to hand-roll your copy loop for that in asm, or in C use strlen and memmove, or intrinsics like _mm_cmpeq_epi8. Pure ISO C doesn't give you the building blocks you need to make an efficient version of this function, given limitations of current compilers, so the best you can portably do in C is glue together hand-written asm building blocks like strlen and memmove, even though that makes two passes over the data. (Perhaps cache-block it in 16KiB chunks with memchr instead of strlen, so you stop after 16K and can memmove while that part of the data is still hot in L1d cache.) In asm you can potentially do as well as the hand-written libc code, most simply by using a copy of it. https://codebrowser.dev/glibc/glibc/sysdeps/x86_64/multiarch/strlen-avx2.S.html shows a version of glibc's strlen; with minor changes you could adapt it or memchr to look for a non-match of '0'. (That would cover finding the terminating 0 byte). Or pick any other asm strlen or memchr you want. Most should be safe for the case where dst is at a lower address than src: reads will happen before writes so it should be reading pristine data.
{ "domain": "codereview.stackexchange", "id": 43867, "lm_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, strings, linux, assembly, amd64", "url": null }
performance, strings, linux, assembly, amd64 Depending on the input buffer, you might also have to worry about alignment, e.g. a 2 byte string in the last 2 bytes of a page, followed by an unmapped page. A 16-byte load would segfault. (Or if the next page is mapped, still be expensive, worst case even paging it in from disk if it didn't otherwise need to be touched.) See Is it safe to read past the end of a buffer within the same page on x86 and x64? - an aligned 16 or 32-byte load can never be split across a wider alignment boundary like 4k. So if your input buffer is always aligned, or always at least 32 bytes allocated, this is trivial: do the first 16-byte vector unaligned, then do (p + 32) & -32 and stay aligned from there.
{ "domain": "codereview.stackexchange", "id": 43867, "lm_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, strings, linux, assembly, amd64", "url": null }
performance, strings, linux, assembly, amd64 Micro-optimizations Some of these instructions are ones you won't need after algorithmic changes, but in other functions you might still want to do something similar. Some of them will still be needed in different forms. Prefer pointer-increments over indexed addressing modes cmp byte [rdi + r9], 48 / jz will decode to 3 uops for the front-end on Intel Skylake CPUs. Micro-fusion is defeated by the indexed addressing mode (2 registers), and macro-fusion of the cmp/jnz doesn't happen with cmp mem,imm (See What is instruction fusion in contemporary x86 processors?). This also saves registers; you just need an input and an output pointer. (And an end-pointer or a down-counter). The loop structure should be something like for(char *p = start, *endp = start+len ; p<endp ; p++) { stuff with *p; }. But of course in a do{}while() style like you're doing, with the conditional branch at the bottom. That's a very Good Thing. Generating endp = start+len just takes an LEA, and then the bottom of the loop is still a cmp/jne or jb. Otherwise you might use dec ecx/jnz or whatever for a loop like do{ p++ }while(--len);. Intel CPUs can macro-fuse dec/jnz, but AMD CPUs can only macro-fuse CMP or TEST. So it can save a uop inside the loop to do a pointer compare, at the cost of needing an LEA at the start. Of course this only applies to counted loops in the first place, and after the algorithmic changes you wouldn't have those, just search loops. But you'd still have pointers that you increment, first read-only for the first non-'0', then from there and from the start to copy, checking for a terminating 0. In a loop where you're going to want that byte in a register later (to store), you should just load it into a register now and test it there. movzx eax, byte [rdi] ; 1 uop, no false dependency on the old RAX cmp al, '0' ; macro-fused with jnz jnz ; 1 uop ; 2 total uops for the front-end, 2 for the back-end.
{ "domain": "codereview.stackexchange", "id": 43867, "lm_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, strings, linux, assembly, amd64", "url": null }
performance, strings, linux, assembly, amd64 (Write ASCII characters as character literals like '0', not 48) Also, use jb or ja for comparing pointers, or jl/jg for comparing signed integers. You did cmp r9, r8 js ... This is different from jl if the subtraction has signed overflow. That's normally not going to be a problem with 64-bit integers that work as offsets to an address, because the middle of the address space (around the signed-overflow wrapping point) is non-canonical. See Should pointer comparisons be signed or unsigned in 64-bit x86? For performance, js won't macro-fuse with cmp on Intel CPUs, but jl and jb will. Also, for human readers, jumping on less-than has the right semantic meaning of do{}while(r9<r8) like you wrote in your C source. Jumping if the subtraction result is negative (after wrapping) does not. Use movzx for byte loads, especially in loops movzx avoids false dependencies on CPUs more recent than Nehalem and first-generation Sandybridge. See Why doesn't GCC use partial registers?. Similarly, mov ecx, 1 or xor ecx,ecx for a boolean. Don't write partial registers if you don't need to. In fact, always xor-zero with 32-bit operand-size, even for registers that need a REX prefix to access, because early Silvermont CPUs only recognize xor r8d,r8d as a zeroing idiom, not xor r8,r8. See details in What is the best way to set a register to zero in x86 assembly: xor, mov or and? inc rax sub rsp, rax dec rax Normally you'd want to keep the stack aligned by 16, and there's no need to change RAX when you want that value later; you could add into a different register. lea rcx, [rax+1 + 15] ; rax+1 for the extra byte, and +15 as part of (x+15)&-16 to round up to the next multiple of 16 and rcx, -16 sub rsp, rcx ; alignas(16) char buf[rax+1]
{ "domain": "codereview.stackexchange", "id": 43867, "lm_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, strings, linux, assembly, amd64", "url": null }
performance, strings, linux, assembly, amd64 To save code-size, if your string will always be less than 4GiB you can use ecx for LEA and AND (32-bit operand-size is the default in x86-64 machine code with no prefixes). On a CPU without partial-register stalls, and cl, -16 would also work efficiently, since the only bits you're clearing are in the low byte so it works to leave the rest unmodified. Same as and rcx, -16 but without needing a REX prefix. push rbp mov rbp, rsp ... leave That is useful if you variably modify RSP. Otherwise don't do it. Once you fix the algorithm, there's no need to touch stack space.
{ "domain": "codereview.stackexchange", "id": 43867, "lm_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, strings, linux, assembly, amd64", "url": null }
c++, c++17, atomic Title: Flippable atomic boolean Question: I was trying to implement a boolean that can be atomically flipped. The suggestion on Stack Overflow is to use an integer. This would be my implementation. #include <atomic> #include <iostream> class flippable_atomic_bool { std::atomic<int> state; public: flippable_atomic_bool() : state(0){} explicit flippable_atomic_bool(bool init) : state(static_cast<int>(init)) {} explicit flippable_atomic_bool(const flippable_atomic_bool& other) = default; flippable_atomic_bool& operator =(const flippable_atomic_bool& other) = default; void flip() { state ^= static_cast<int>(true); } operator bool() const { return static_cast<bool>(state); } }; int main() { { flippable_atomic_bool a(true); std::cout << static_cast<bool>(a) << std::endl; a.flip(); std::cout << static_cast<bool>(a) << std::endl; } { flippable_atomic_bool a{false}; std::cout << static_cast<bool>(a) << std::endl; a.flip(); std::cout << static_cast<bool>(a) << std::endl; } } Outputs 1 0 0 1 Answer: The default constructor might be surprising to those familiar with std::atomic<T> in C++17, which default-constructs to an uninitialised state, rather than to a default T. That said, this behaviour is correct for C++20, so a good choice! There's no benefit to explicit copy-constructor - that can never be an implicit conversion. The defaulted copy constructor and assignment are misleading - since state is not copyable, this causes them to be deleted, so we should write = delete instead of = default or (better) just omit them. It's interesting that we write a literal 0 as initializer for state, but then use static_cast<int>(true) in the ^= implementation. Since bool and int are interconvertible, we can write the whole thing without casts (I compiled with g++ -Wconversion -Wuseless-cast, amongst other options):
{ "domain": "codereview.stackexchange", "id": 43868, "lm_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++, c++17, atomic", "url": null }
c++, c++17, atomic class flippable_atomic_bool { std::atomic<int> state; public: flippable_atomic_bool() : state{} {} explicit flippable_atomic_bool(bool init) : state{init} {} void flip() { state ^= 1; } operator bool() const { return state; } }; The test program doesn't demonstrate much of relevance. I would expect to show several threads toggling the atomic a few thousand times each, and demonstrate that the end state is consistent. It's not hard to do that, if we build using OpenMP: #include <iomanip> #include <iostream> int main() { auto a = flippable_atomic_bool{false}; #pragma omp parallel for num_threads(5) for (long i = 0; i < 100000001; ++i) { a.flip(); } std::cout << std::boolalpha << a << '\n'; return !a; } We could gain more confidence by running that race a few hundred times, and checking we always get the same result.
{ "domain": "codereview.stackexchange", "id": 43868, "lm_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++, c++17, atomic", "url": null }
c++, time-limit-exceeded, edit-distance Title: Find pairs of similar (by hamming distance) bit strings Question: I have a list of binary strings where each binary string max length is 15. I need to find list of integers which is count of similar (should differ by max 1 bit position) binary strings present in the list for each of the binary strings present in the list. This is current solution with time complexity of O(NΒ²) but getting TLE for larger inputs. #include <iostream> #include <string> #include <vector> bool is_similar(const long long num) { return num == 0 || (num & (num - 1)) == 0; } int main() { const std::vector<std::string> str_nums { "100", "110", "010", "011", "100" }; std::vector<long long> nums; for (const auto& str_num : str_nums) nums.push_back(std::stoll(str_num, nullptr, 2)); const int n = nums.size(); std::vector<int> answers(n); for (int i = 0; i < n - 1; ++i) { for (int j = i + 1; j < n; ++j) { if (is_similar(nums[i] ^ nums[j])) { ++answers[i]; ++answers[j]; } } } for (const auto answer : answers) std::cout << answer << ", "; std::cout << std::endl; } Is there an efficient way to do this? Answer: Toby Speight's answer already addresses improvements in your code style. This answer presents an improved algorithm that makes use of the fact that the strings are short. Consider, instead of iterating over all existing strings to check if they are similar, we can iterate over all similar strings to check if they exist. To do this, we need to store a mapping from each string to the number of times it appears (in my solution an unordered_map). Where n is the number of strings and l is the maximum length of each string, this solution has complexity O(n*l), compared to your original O(n*n+n*l). #include <iostream> #include <string> #include <vector> #include <unordered_map>
{ "domain": "codereview.stackexchange", "id": 43869, "lm_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++, time-limit-exceeded, edit-distance", "url": null }
c++, time-limit-exceeded, edit-distance int main() { const std::vector<std::string> str_nums { "100", "110", "010", "011", "100" }; std::vector<int> nums; std::unordered_map<int, int> nums_cnt; for (const auto& str_num : str_nums) { const int encoded_value = std::stoll(str_num, nullptr, 2); nums.push_back(encoded_value); nums_cnt[encoded_value] += 1; } const int n = nums.size(); std::vector<int> answers(n); for (int i = 0; i < n; i++) { // add strings that are exactly the same (but don't include this one) answers[i] += nums_cnt[nums[i]] - 1; for (int bit = 0; bit <= 15; bit++) { // add strings which differ exactly in this bit answers[i] += nums_cnt[nums[i] ^ (1 << bit)]; } } for (const auto answer : answers) std::cout << answer << ", "; std::cout << std::endl; }
{ "domain": "codereview.stackexchange", "id": 43869, "lm_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++, time-limit-exceeded, edit-distance", "url": null }
java, collections, wrapper Title: Class that wraps a collection and tracks if its elements were visited Question: The VisitedCollection is a collection wrapper for setting and tracking if elements were visited (removed in terms of the wrapper) I have concerns regarding: should equals and hashCode throw ConcurrentModificationException is underlying collection is changed is it ok that visiting is performed by Iterator.remove() method? Another option might be to introduce a new VisitedIterator interface with a special method for visiting (e.g. VisitedIterator.setVisited()). current implementation allows "removing" an element multiple times without throwing any errors. Does it break the Iterator contract? is the name VisitedCollection self-explanatory enough :-) package io.github.hextriclosan.algorithm.collections; import java.io.Serializable; import java.util.AbstractCollection; import java.util.Arrays; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Objects; public class VisitedCollection<E> extends AbstractCollection<E> implements Serializable { private static final long serialVersionUID = -1308309959111972266L; private static final int SIZE = Long.SIZE; private final Collection<? extends E> collection; private final long[] index; private int visitedCount; private final int underlyingCollectionExpectedSize; public VisitedCollection(Collection<? extends E> collection) { Objects.requireNonNull(collection, "collection"); this.collection = collection; this.index = new long[(collection.size() + SIZE - 1) / SIZE]; underlyingCollectionExpectedSize = collection.size(); } @Override public int size() { checkConsistency(); return collection.size() - visitedCount; } @Override public boolean isEmpty() { checkConsistency(); return visitedCount == collection.size(); }
{ "domain": "codereview.stackexchange", "id": 43870, "lm_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, collections, wrapper", "url": null }
java, collections, wrapper @Override public Iterator<E> iterator() { checkConsistency(); return new Itr(); } @Override public boolean add(E e) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends E> c) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } VisitedCollection<?> that = (VisitedCollection<?>) o; return collection.equals(that.collection) && Arrays.equals(index, that.index); } @Override public int hashCode() { int result = Objects.hash(collection); result = 31 * result + Arrays.hashCode(index); return result; } private void setVisited(int pos) { int i = pos / SIZE; int offset = pos % SIZE; index[i] |= 1L << offset; ++visitedCount; checkConsistency(); } private boolean isVisited(int pos) { int i = pos / SIZE; int offset = pos % SIZE; checkConsistency(); return (index[i] & (1L << offset)) != 0; } private void checkConsistency() { if (underlyingCollectionExpectedSize != collection.size()) { throw new ConcurrentModificationException(); } } private class Itr implements Iterator<E> { final Iterator<? extends E> it; E element; int counter; int lastReturnedPos = -1; int expectedVisitedCount = visitedCount; Itr() { it = collection.iterator(); computeNext(); } @Override public boolean hasNext() { return element != null; }
{ "domain": "codereview.stackexchange", "id": 43870, "lm_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, collections, wrapper", "url": null }
java, collections, wrapper @Override public boolean hasNext() { return element != null; } @Override public E next() { checkForComodification(); lastReturnedPos = counter - 1; final E current = element; computeNext(); return current; } @Override public void remove() { if (lastReturnedPos < 0) { throw new IllegalStateException(); } checkForComodification(); VisitedCollection.this.setVisited(lastReturnedPos); expectedVisitedCount = visitedCount; } private void computeNext() { while (it.hasNext()) { E next = it.next(); if (!VisitedCollection.this.isVisited(counter++)) { element = next; return; } } element = null; } final void checkForComodification() { if (visitedCount != expectedVisitedCount) { throw new ConcurrentModificationException(); } } } } ADDED VisitedCollection is an auxiliary class for SamplingIterator. On each iteration, this iterator randomly selects n elements from the collection preserving stable order until the entire collection is processed. package io.github.hextriclosan.algorithm.iterators; import io.github.hextriclosan.algorithm.collections.VisitedCollection; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.Random; public class SamplingIterator<E> implements Iterator<List<E>> { private final Collection<? extends E> collection; private final int sampleSize; private final Random random; private List<E> nextSample;
{ "domain": "codereview.stackexchange", "id": 43870, "lm_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, collections, wrapper", "url": null }
java, collections, wrapper private List<E> nextSample; public SamplingIterator(Collection<? extends E> collection, int sampleSize, Random random) { validate(collection, sampleSize, random); this.collection = new VisitedCollection<>(collection); this.sampleSize = sampleSize; this.random = random; sample(); } @Override public boolean hasNext() { return nextSample != null && !nextSample.isEmpty(); } @Override public List<E> next() { final List<E> result = nextSample; sample(); return result; } @Override public void remove() { throw new UnsupportedOperationException(); } private void sample() { Iterator<? extends E> iterator = collection.iterator(); int size = collection.size(); int n = Math.min(sampleSize, collection.size()); ArrayList<E> arrayList = new ArrayList<>(n); while (n > 0 && iterator.hasNext()) { int r = random.nextInt(size--); E next = iterator.next(); if (r < n) { arrayList.add(next); iterator.remove(); --n; } } nextSample = arrayList; } private void validate(Collection<? extends E> collection, int sampleSize, Random random) { Objects.requireNonNull(collection, "collection"); Objects.requireNonNull(random, "random"); if (sampleSize <= 0) { throw new IllegalArgumentException(); } } } Possible usage: var samplingIterator = new SamplingIterator<>(List.of('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'), 3, new Random()); samplingIterator.forEachRemaining(System.out::println); // prints out, for instance // [B, C, H] // [E, F, G] // [A, D]
{ "domain": "codereview.stackexchange", "id": 43870, "lm_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, collections, wrapper", "url": null }
java, collections, wrapper Answer: Ok, I'm going to review SamplingIterator instead, because I think that VisitedCollection is a bad path to be on. It appears to exist only to vend its iterator, which is broken in a few ways (incorrectly implements the interface, doesn't properly check consistency) and is a very convoluted way of shuffling a collection and iterating over the results. The validate method is small enough to be folded back into the constructor. It's easier on the reader to see the validation inline instead of having to jump someplace else to see the invariants. The sample method is effectively locating a random element in the underlying collection. The VisitedCollection class is intended to prevent sampling an element more than once. This work is not necessary, because we already have a data structure (a List with the order randomized) which will give you these properties. I feel like this code is toeing the line in terms of whether it honors the intent of the Iterator contract. I do not think Iterators are intended to change the type of the collection they're iterating over (E -> List). I would consider a helper method, or perhaps a classSampledCollection. I don't see the value in making SamplingIterator blow up with a ConcurrentModificationException if the underlying collection changes. I think it would be preferable to just take a snapshot of a collection and build a sampling from that. If the code were reworked to replace VisitedCollection with a shuffled list, it might look more like: public final class SamplingIterator<E> implements Iterator<List<E>> { private final List<? extends E> shuffledCollection; private final int sampleSize;
{ "domain": "codereview.stackexchange", "id": 43870, "lm_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, collections, wrapper", "url": null }
java, collections, wrapper private final List<? extends E> shuffledCollection; private final int sampleSize; public SamplingIterator(Collection<? extends E> collection, int sampleSize, Random random) { Objects.requireNonNull(collection, "collection"); Objects.requireNonNull(random, "random"); if (sampleSize <= 0) { throw new IllegalArgumentException(); } this.shuffledCollection = new ArrayList<>(collection); Collections.shuffle(shuffledCollection, random); this.sampleSize = sampleSize; } @Override public boolean hasNext() { return !shuffledCollection.isEmpty(); } @Override public List<E> next() { if (shuffledCollection.isEmpty()) { throw new NoSuchElementException(); } List<E> result = new ArrayList<>(); int resultSize = Math.min(sampleSize, shuffledCollection.size()); for (int i = 0; i < resultSize; i++) { result.add(shuffledCollection.remove(0)); } return result; } @Override public void remove() { throw new UnsupportedOperationException(); } } A static factory version might look like: public final class Sampling {
{ "domain": "codereview.stackexchange", "id": 43870, "lm_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, collections, wrapper", "url": null }
java, collections, wrapper A static factory version might look like: public final class Sampling { public static <E> List<List<E>> of(Collection<? extends E> collection, int sampleSize, Random random) { Objects.requireNonNull(collection, "collection"); Objects.requireNonNull(random, "random"); if (sampleSize <= 0) { throw new IllegalArgumentException(); } List<List<E>> resultList = new ArrayList<>(); List<? extends E> shuffledCollection = new ArrayList<>(collection); Collections.shuffle(shuffledCollection, random); while (!shuffledCollection.isEmpty()) { List<E> result = new ArrayList<>(); int resultSize = Math.min(sampleSize, shuffledCollection.size()); for (int i = 0; i < resultSize; i++) { result.add(shuffledCollection.remove(0)); } resultList.add(result); } return resultList; } } Depending on what other properties and methods a Sampling might have, it could also make sense to make a single Sample be its own class, and to instead be generating a List<Sample<E>> .
{ "domain": "codereview.stackexchange", "id": 43870, "lm_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, collections, wrapper", "url": null }
javascript Title: Extracting records of type "withdraw_rewards" from a multi-level data structure Question: Re-posting from StackOverflow as this is a place to review code that is already working. I would like to know if there is a better way to deal with nested forEach when it comes to dealing with objects with properties that are nested arrays themselves. My object (summarized): { ..., "tx_responses": [ { ... "logs" : [ { ..., "events": [ { "type": "coin_received", "attributes": [ { "key": "receiver", "value": "somesome" }, { "key": "amount", "value": "somesome" } ] }, ... { "type": "transfer", "attributes": [ { "key": "recipient", "value": "somesome" }, { "key": "sender", "value": "somesome" }, { "key": "amount", "value": "somesome" } ] }, { "type": "withdraw_rewards", "attributes": [ { "key": "amount", "value": "somesomesomehere" }, { "key": "validator", "value": "somesome" } ] }, ... ] } ], ...
{ "domain": "codereview.stackexchange", "id": 43871, "lm_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", "url": null }
javascript I am essentially trying to extract all { key: 'amount', value: 'somesomesomehere' } objects in the attributes array of the "type" : "withdraw_rewards" object in the events array. Currently this is the code I wrote to carry out my task: getWithdrawnAmounts: async(del_addr_) => { let withdrawnAmounts = []; const res = await axios.get("some_url_that_uses_del_addr_"); res.data.tx_responses.forEach(txr => { txr.logs.forEach(log => { log.events.forEach(evnt => { if (evnt.type == "withdraw_rewards") { evnt.attributes.forEach(attr => { if (attr.key == "amount") { withdrawnAmounts.push(attr); } }) } }) }) }); return withdrawnAmounts; } The code helps me to get what I need, but I was wondering if there is a better way to write my code so that I dont have to use so many nested .forEach methods. I was wondering if I should use .flat() or .flatMap() but I'm curious to know how would people approach this? Answer: The pipeline can be written simpler: replacing nested .forEach using .flatMap replacing conditionals inside .forEach using .filter Also, instead of appending to withdrawnAmounts in the deepest .forEach, you can make the pipeline return a filtered list. return res.data.tx_responses .flatMap(txr => txr.logs) .flatMap(log => log.events) .filter(evnt => evnt.type === "withdraw_rewards") .flatMap(evnt => evnt.attributes) .filter(attr => attr.key === "amount");
{ "domain": "codereview.stackexchange", "id": 43871, "lm_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", "url": null }
python Title: Using a Difference table to find the next element in a sequence Question: Recently I implemented a python code that predicts the next number of a sequence using a difference table (a little more on the subject here) def s(d,p=0): if (len(d) > 1): return s([i[0]-i[1] for i in zip(d[1:], d[:-1])],p+d[-1]) return p+d[-1] print(s(list(map(int, input().split(","))))) This code takes the input(by stdin), the sequence separated by comas, like: 1,2,3 and outputs what it thinks is the next digit 4 Is there any way to make this code better or simplify it even more by python means? Any comments, answers, or opinions would be greatly appreciated Answer: The other answer already mentioned to use descriptive names. It's the most important point to make it easier to understand the code. It's recommended to add more spaces around operators. Tools like PyCharm would format the posted code like this: def s(d, p=0): if (len(d) > 1): return s([i[0] - i[1] for i in zip(d[1:], d[:-1])], p + d[-1]) return p + d[-1] The parentheses in the if condition are unnecessary, drop them. Instead of checking if the sequence has a single element, you can make that condition based on if the sequence is empty, which would make the code a bit simpler: def s(d, p=0): if d: return s([i[0] - i[1] for i in zip(d[1:], d[:-1])], p + d[-1]) return p Be careful with recursive logic, if there are too many items in the input sequence, the call stack may become too deep and overflow. Consider writing in iterative style, especially when it's possible with little effort, and without sacrificing readability. Here's an alternative using iterative style (with the nice renames from the other answer): def predict(seq, prev=0): while seq: prev += seq[-1] seq = [b - a for a, b in zip(seq[:-1], seq[1:])] return prev
{ "domain": "codereview.stackexchange", "id": 43872, "lm_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", "url": null }
python return prev As @AJNeufeld pointed out in a comment, this can still be significantly better. The prev argument is not really meant to be used by callers, it was necessary in the recursive version to track the cumulative sum of differences, but in the iterative version it can be a local variable. It's also important to note that while zip(seq[:-1], seq[1:]) is elegantly written, it incurs the cost of list slicing (array copies). From Python 3.10, a more efficient and even more elegant solution is to use itertools.pairwise. Putting these tips together: def predict(seq): prev = 0 while seq: prev += seq[-1] seq = [b - a for a, b in itertools.pairwise(seq)] return prev
{ "domain": "codereview.stackexchange", "id": 43872, "lm_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", "url": null }
beginner, c, ascii-art Title: Drawing a pair of triangular walls for CS50 Mario Question: This is my code for the CS50 Mario (more comfortable). Answers can be found all over the net however I wrote this myself. I would like to refactor to its maximum potential (just for my own improvement I'm not enrolled or anything). A quick outline of the code: Firstly it asks for a valid input of an amount of rows to be built (an integer between 0 and 550) and then builds a Mario wall like this: # # ## ## ### ### I have chosen to create 2 functions and called them in the main function. Can this be be improved or refactored anymore or is this as good as it gets? #include <stdio.h> #include <stdlib.h> void build_wall(int num_rows); void get_rows(int n); int rows = 0; int spaces = 0; int bricks = 0; int main(void) { get_rows(rows); build_wall(rows); } void get_rows(int n) { do { printf("How many rows would you like? "); scanf("%d", &rows); printf("\n"); printf("You would like %d rows.\n", rows); } while (rows <= 0 || rows >=550); } void build_wall(int num_rows) { for (int i = 0; i < num_rows; i++) ///number of rows { for(spaces = 0; spaces < num_rows-i-1; spaces++ ) // first spaces { printf(" "); } for(bricks = 0; bricks < i+1; bricks++) // first wall bricks { printf("#"); } { printf(" "); //Middle spaces } for(bricks = 0; bricks < i+1; bricks++) // Second wall bricks { printf("#"); } printf("\n"); } }
{ "domain": "codereview.stackexchange", "id": 43873, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, ascii-art", "url": null }
beginner, c, ascii-art } Answer: Global variables are not called for here. Since it's such a simple program, there isn't a lot of value in pre-declaring your function signatures; just write out the full definitions in order of dependency (main last). I know it's convention, but I'm personally pretty against omitting return 0 from main; it's a matter of consistency. You do not check the result of your scan to see if the field was successfully read; you should do that. A higher-performance solution would form the art in memory and then display it with a single print, rather than issuing multiple printf calls. scanf is pretty broken; I'll leave you to Google. Below I show one method that is roughly sane. Suggested Here is one approach. Since you don't want to right-fill spaces, buffer size calculation requires a bit of geometry whose rationale I will leave as an exercise to the reader. Compile with this example makefile: export cflags=-std=c18 -Wall -D_POSIX_C_SOURCE=200809L all: mario mario: main.o gcc $$cflags -o $@ $< %.o: %.c makefile gcc $$cflags -o $@ $< -c clean: rm -f *.o mario #include <stdio.h> #include <stdlib.h> #include <string.h> // For https://cs50.harvard.edu/summer/2022/psets/1/mario/less/ static const int max_rows = 550, n_spaces = 2; static size_t get_rows() { size_t n_rows; for (;;) { printf("How many rows would you like? "); // POSIX only - https://www.man7.org/linux/man-pages/man3/getline.3.html char *buffer = NULL; size_t size = 0; if (getline(&buffer, &size, stdin) < 1) { free(buffer); continue; } char *end; n_rows = strtoul(buffer, &end, 10); free(buffer); if (end == buffer) fprintf(stderr, "Invalid number\n"); else if (n_rows > 0 && n_rows <= max_rows) return n_rows; fprintf(stderr, "Number out of range\n"); } }
{ "domain": "codereview.stackexchange", "id": 43873, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, ascii-art", "url": null }
beginner, c, ascii-art static char *allocate_wall(int n_rows, int *n_chars) { // left hashes, spaces, right hash, newline int xmin = n_rows + n_spaces + 1 + 1; // left and right hashes, spaces, newline int xmax = 2*n_rows + n_spaces + 1; *n_chars = (xmax*(xmax + 1) - xmin*(xmin-1))/2; // all printable characters then a null terminator int size = *n_chars + 1; char *buffer = malloc(size); if (buffer == NULL) { fprintf(stderr, "Failed to allocate buffer\n"); exit(1); } return buffer; } static void fill_wall(char *buffer, int n_rows, int n_chars) { // Start by filling with #, which is the most abundant character in the output memset(buffer, '#', n_chars); char *pwrite = buffer; for (int y = 0; y < n_rows; y++) { int leading_spaces = n_rows - y - 1; memset(pwrite, ' ', leading_spaces); pwrite += leading_spaces; int brick_width = y + 1; pwrite += brick_width; memset(pwrite, ' ', n_spaces); pwrite += n_spaces + brick_width; *pwrite = '\n'; pwrite++; } // Terminating null buffer[n_chars] = '\0'; } int main(void) { int n_rows = get_rows(); int n_chars; char *buffer = allocate_wall(n_rows, &n_chars); fill_wall(buffer, n_rows, n_chars); printf(buffer); free(buffer); return 0; } For giggles: adding -Ofast -march=native, increasing max_rows, putting 10000 into large-size and then time ./mario < large-size > /dev/null takes about 0.1 seconds to allocate, format and output 150,035,000 bytes of data. Under the same conditions, the original code takes about 2.715 seconds.
{ "domain": "codereview.stackexchange", "id": 43873, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, ascii-art", "url": null }
c++, algorithm, iterator, c++17 Title: General algorithm to calculate sums of all subsets of a given sequence of numbers Question: Background A recent question Print sums of all subsets made its way to the Hot Network Questions list. The problem is simple: Print sums of all subsets of a given set Given an array of integers, print sums of all subsets in it. Output sums can be printed in any order. Examples: Input : arr[] = {2, 3} Output: 0 2 3 5 Input : arr[] = {2, 4, 5} Output : 0 2 4 5 6 7 9 11 (Source) The OP used an exponential space algorithm. I didn't care about this too much in my answer, but later an answer by Will Ness noted that exponential space is not required. The better algorithm works like this: (to quote that answer) Instead, have your program create \$n\$ nested loops at run-time, in effect enumerating the binary encoding of \$2^n\$, and print the sums out from the innermost loop. In pseudocode: // {5, 4, 3} sum = 0 for x in {5, 0}: // included, not included sum += x for x in {4, 0}: sum += x for x in {3, 0}: sum += x print sum sum -= x sum -= x sum -= x I decided to implement this algorithm. Code I wrote the code in C++17. subset_sums is a generic algorithm which gives the results to an output iterator, so the user can choose to output the results or store them immediately, or customize the output format if they want, etc. I am influenced a lot by the Range-v3 library, so my algorithm uses iterator-sentinel pairs instead of the traditional iterator-iterator pairs, and it also supports projections. This code does not use the Range-v3 library, though. The identity function object type is standardized in C++20, so I rolled out my own version. #include <functional> #include <iterator> #include <utility> namespace util { struct identity { using is_transparent = int;
{ "domain": "codereview.stackexchange", "id": 43874, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, iterator, c++17", "url": null }
c++, algorithm, iterator, c++17 namespace util { struct identity { using is_transparent = int; template <typename T> constexpr T&& operator()(T&& arg) const noexcept { return std::forward<T>(arg); } }; } template <typename ForwardIt, typename Sentinel, typename OutputIt, typename Value, typename BinaryOp = std::plus<>, typename Proj = util::identity> OutputIt subset_sums(ForwardIt first, Sentinel last, OutputIt dest, Value init, BinaryOp bin = {}, Proj proj = {}) { if (first == last) return *dest++ = init; auto value = proj(*first++); dest = subset_sums(first, last, dest, init, bin, proj); return subset_sums(first, last, dest, bin(init, value), bin, proj); } template <typename ForwardIt, typename Sentinel, typename OutputIt> OutputIt subset_sums(ForwardIt first, Sentinel last, OutputIt dest) { using Value = typename std::iterator_traits<ForwardIt>::value_type; return subset_sums(first, last, dest, Value{}); } The (first, last, dest) version is a separate overload because the calculation of the value type is a bit complicated and I don't want to clutter the general version. Usage example The original problem: #include <iostream> #include <iterator> #include <vector> using number_t = long long; int main() { std::vector<number_t> nums{3, 1, 4}; subset_sums(nums.begin(), nums.end(), std::ostream_iterator<number_t>{std::cout, "\n"}); } Output: 0 4 1 5 3 7 4 8 Same problem, but with products instead of sums: #include <iostream> #include <iterator> #include <vector> using number_t = long long; int main() { std::vector<number_t> nums{3, 1, 4}; subset_sums(nums.begin(), nums.end(), std::ostream_iterator<number_t>{std::cout, "\n"}, number_t{1}, std::multiplies<>{}); } Output: 1 4 1 4 3 12 3 12 Possibly non-contiguous substrings in a string: #include <iostream> #include <iterator> #include <string>
{ "domain": "codereview.stackexchange", "id": 43874, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, iterator, c++17", "url": null }
c++, algorithm, iterator, c++17 int main() { std::string str = "review"; subset_sums(str.begin(), str.end(), std::ostream_iterator<std::string>{std::cout, "\n"}, std::string{}); } Output: (the initial empty line is intentional) w e ew i iw ie iew v vw ve vew vi viw vie view e ew ee eew ei eiw eie eiew ev evw eve evew evi eviw evie eview r rw re rew ri riw rie riew rv rvw rve rvew rvi rviw rvie rview re rew ree reew rei reiw reie reiew rev revw reve revew revi reviw revie review I have also tested with std::forward_list to make sure that the algorithm works with forward iterators. Answer: This is pretty slick modern C++. I like it. The recursion depth (equal to the input length) is unlikely to become a problem before the exponential explosion does. Naming the all the template types isn't strictly necessary, but I think that giving names to the types makes for clarity which isn't present in this alternative: template <typename ForwardIt> auto subset_sums(ForwardIt first, auto last, auto dest)
{ "domain": "codereview.stackexchange", "id": 43874, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, iterator, c++17", "url": null }
c++, algorithm, iterator, c++17 That said, if we're able to use C++20, we could be more specific than simply typename, and use Concepts to make the code more resilient against accidents. This also gives us a place to deduce the default Value type, removing the need for the overload (IMO): template <typename BinaryOp = std::plus<>, typename Proj = util::identity, std::forward_iterator ForwardIt, std::sentinel_for<ForwardIt> Sentinel, typename InputValue = std::invoke_result_t<Proj, typename std::iterator_traits<ForwardIt>::value_type>, typename Value = InputValue, std::output_iterator<std::invoke_result_t<BinaryOp, Value, InputValue>> OutputIt> OutputIt subset_sums(ForwardIt first, Sentinel last, OutputIt dest, Value init = {}, BinaryOp bin = {}, Proj proj = {}) { if (first == last) return *dest++ = init; auto value = proj(*first++); dest = subset_sums(first, last, dest, init, bin, proj); return subset_sums(first, last, dest, bin(init, value), bin, proj); } I'd consider adding (or even substituting) a version that accepts a std::ranges::range instead of an iterator-sentinel pair. There's a bug you're getting away with when using ostream iterator for output, but which bites when we try to store our results into a container instead. We can expose it like this: #include <array> #include <iostream> #include <iterator> int main() { using number_t = long long; std::array<number_t, 3> nums{3, 1, 4}; std::array<number_t, 60> results; auto it = subset_sums(nums.begin(), nums.end(), results.begin()); it = subset_sums(nums.begin(), nums.end(), it, number_t{1}, std::multiplies<>{}); std::copy(results.begin(), it, std::ostream_iterator<number_t>{std::cout, "\n"}); } The problem is return *dest++ = init;
{ "domain": "codereview.stackexchange", "id": 43874, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, iterator, c++17", "url": null }
c++, algorithm, iterator, c++17 The problem is return *dest++ = init; For most container iterators, that expression yields a reference to a value_type object, not the iterator itself. And using post-increment means we're returning the wrong position. It's equivalent to return *dest = init; This means we continually overwrite the same element, and return dest unmodified, thereby claiming we've written nothing. I suggest: if (first == last) { *dest++ = init; return dest; } I think that's clearer than the cutesy braceless version: if (first == last) return *dest++ = init, dest;
{ "domain": "codereview.stackexchange", "id": 43874, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, iterator, c++17", "url": null }
javascript Title: Calculate sum of values from checkboxes Question: I have a bunch of checkboxes with a data-amount attribute containing a value (positive or negative). My goal is to generate a running total as the user checks each box, and then output this later on. My code works - just curious for feedback as using filter, map and reduce seems overkill for something like this. Thanks const checkboxes = document.querySelectorAll('input[type=checkbox]'); const output = document.querySelector('.runningTotal'); checkboxes.forEach(function(checkbox) { checkbox.addEventListener('change', function() { const runningTotal = Array.from(checkboxes) .filter(i => i.checked) // remove unchecked checkboxes. .map(i => i.dataset.amount ??= 0) //extract the amount, or 0 .reduce((total, item) => { return total + parseFloat(item)}, 0) console.log(runningTotal) output.innerHTML = runningTotal; }) }); <input type="checkbox" data-amount="100"> 100 <input type="checkbox" data-amount="150"> 150 <input type="checkbox" data-amount="-50"> -50 <input type="checkbox" data-amount="10.50"> 10.50 <input type="checkbox" data-amount="0"> 0 <div class="runningTotal"></div> Answer: Your code is too complex. General points Use textContent when setting text in an HTMLElement rather than innerHTML which forces a reflow. Use a single listener rather than one for each clickable element. See rewrite. The nullish assignment is not required. i => i.dataset.amount ??= 0 is more efficient as i => i.dataset.amount ?? 0 as it does not modify the markup if amount is undefined. However I can not see why you vet the dataset values. Better to use Number to parse a string to a number. Prefer id to uniquely identify DOM elements.
{ "domain": "codereview.stackexchange", "id": 43875, "lm_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", "url": null }