text
stringlengths
1
2.12k
source
dict
java, homework, swing, sqlite, jdbc try { connect = DriverManager.getConnection(url); stat = connect.createStatement(); String str = "CREATE TABLE members (nr integer primary key AUTOINCREMENT, fName varchar(25), lName varchar(25), address varchar(35), tlf integer);"; stat.executeUpdate(str); try { String line; File mlm = new File("register.txt"); read = new Scanner(mlm); while (read.hasNext()) { line = read.nextLine(); String[] dB = line.split("[;]"); if (dB.length == 6) { int nr = parseInt(dB[0]); String fName = dB[1], lName = dB[2], address = dB[3]; int nr1 = parseInt(dB[4]); str = "INSERT INTO members VALUES (" + nr + ",'" + fName + "','" + lName + ",'" + address + ",'" + nr1 + ");"; stat.executeUpdate(str); } else { int nr = parseInt(dB[0]); String fName = dB[1], lName = dB[2], address = dB[3];
{ "domain": "codereview.stackexchange", "id": 43156, "lm_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, homework, swing, sqlite, jdbc", "url": null }
java, homework, swing, sqlite, jdbc str = "INSERT INTO members VALUES (" + nr + ",'" + fName + "','" + lName + ",'" + address + ",'" + null + ");"; stat.executeUpdate(str); } } } catch (FileNotFoundException fnf) { out.println("Not found!"); } finally { if (read != null) { read.close(); } } out.println("Connected"); } catch (SQLException exc) { out.println(exc.getMessage()); } finally { try { if (connect != null) { connect.close(); } } catch (SQLException ex) { out.println(ex.getMessage()); } } showMessageDialog(null, "Start: Creates the table"); } private static void showAllSurname() { String url = "jdbc:sqlite:members.db"; Connection connect = null; Statement stat = null; try { connect = DriverManager.getConnection(url); stat = connect.createStatement(); String str = "SELECT * FROM members ORDER BY lName"; ResultSet res = stat.executeQuery(str); int i = 0, j = i; while (res.next()) { i++; } String[][] lNameTab = new String[i][6]; res = stat.executeQuery(str); while (res.next()) { String nr = res.getString("nr"), lName = res.getString("lName"), fName = res.getString("fName"), address = res.getString("address"), tlf = res.getString("tlf"); lNameTab[j - i][0] = nr; lNameTab[j - i][1] = lName; lNameTab[j - i][2] = fName; lNameTab[j - i][3] = address; lNameTab[j - i][4] = tlf; i--; }
{ "domain": "codereview.stackexchange", "id": 43156, "lm_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, homework, swing, sqlite, jdbc", "url": null }
java, homework, swing, sqlite, jdbc String out = ""; for (i = 0; i < lNameTab.length; i++) { out += lNameTab[i][0] + "|" + lNameTab[i][1] + "|" + lNameTab[i][2] + "|" + lNameTab[i][3] + "|" + lNameTab[i][4] + "|" + lNameTab[i][5] + "|" + "\n"; } showMessageDialog(null, "1: All members, sorted by surname" + "\n" + out); } catch (SQLException exc) { System.out.println(exc.getMessage()); } finally { try { if (connect != null) { connect.close(); } } catch (SQLException exc) { System.out.println(exc.getMessage()); } } } private static void showAllTelephone() { String url = "jdbc:sqlite:members.db"; Connection connect = null; Statement stat = null; try { connect = DriverManager.getConnection(url); stat = connect.createStatement(); String str = "SELECT * FROM members ORDER BY tlf"; ResultSet res = stat.executeQuery(str); int i = 0, j = i; while (res.next()) { i++; } String[][] tlfTab = new String[i][6]; res = stat.executeQuery(str); while (res.next()) { String nr = res.getString("nr"), lName = res.getString("lName"), fName = res.getString("fName"), address = res.getString("address"), tlf = res.getString("tlf"); tlfTab[j - i][0] = nr; tlfTab[j - i][1] = lName; tlfTab[j - i][2] = fName; tlfTab[j - i][3] = address; tlfTab[j - i][4] = tlf; i--; } String out = ""; for (i = 0; i < tlfTab.length; i++) {
{ "domain": "codereview.stackexchange", "id": 43156, "lm_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, homework, swing, sqlite, jdbc", "url": null }
java, homework, swing, sqlite, jdbc String out = ""; for (i = 0; i < tlfTab.length; i++) { out += tlfTab[i][0] + "|" + tlfTab[i][1] + "|" + tlfTab[i][2] + "|" + tlfTab[i][3] + "|" + tlfTab[i][4] + "|" + tlfTab[i][5] + "|" + "\n"; } showMessageDialog(null, "2: All members, sorted by telephone" + "\n" + out); } catch (SQLException exc) { out.println(exc.getMessage()); } finally { try { if (connect != null) { connect.close(); } } catch (SQLException exc) { out.println(exc.getMessage()); } } } } Answer: Block form over statement form if (!dBfile.exists()) createNewTable(); This is a risky pattern. Say you (or someone else, perhaps a Python developer) want to add logging. So just add a log statement, right? if (!dBfile.exists()) log("No DB File found"); createNewTable(); But wait, does that do what was intended? Well, no, not in Java (a similar edit would work in Python). Instead of only creating the file if none exists, it will now always attempt to create a new table. Whereas if you had if (!dBfile.exists()) { createNewTable(); } Future edits would naturally do if (!dBfile.exists()) { // can add more statements here createNewTable(); // or here } If you feel that you absolutely must use the other form, consider if (!dBfile.exists()) createNewTable(); which is harder to edit badly. And is even shorter. If you're concerned about readability, I would point out that the block form is strictly more readable. Pluralize plurals showAllSurname(); This should be showAllSurnames();
{ "domain": "codereview.stackexchange", "id": 43156, "lm_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, homework, swing, sqlite, jdbc", "url": null }
java, homework, swing, sqlite, jdbc showAllSurname(); This should be showAllSurnames(); Not terribly important, but pedants like me will notice things like that. Remove redundancy int choice = 0; do { choice = showMenu(); if (choice != 0) { switch (choice) { case 1: showAllSurname(); break; case 2: showAllTelephone(); break; default: break; } } } while (choice != 0); This could be for (;;) { showMenu(); switch (parseMenuResponse()) { case 0: return; case 1: showAllSurnames(); break; case 2: showAllTelephones(); break; } } I removed the default case, as it had no effect. You can always add it back later if you want to do something with it. Note that it is not necessary to put a break in the last case. By convention, I will usually leave it out of the default case if it is last. There's no need to have an if and a while checking the same condition. This form uses the switch to process everything, even a 0 input. I separated the input fetching and parsing from the display. As a general rule, it is recommended to either have a side effect (e.g. displaying output) or a return value, not both. This is a particular case of the Single Responsibility Principle. try-with-resources try { String line; File mlm = new File("register.txt"); read = new Scanner(mlm); while (read.hasNext()) { line = read.nextLine(); String[] dB = line.split("[;]");
{ "domain": "codereview.stackexchange", "id": 43156, "lm_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, homework, swing, sqlite, jdbc", "url": null }
java, homework, swing, sqlite, jdbc if (dB.length == 6) { int nr = parseInt(dB[0]); String fName = dB[1], lName = dB[2], address = dB[3]; int nr1 = parseInt(dB[4]); str = "INSERT INTO members VALUES (" + nr + ",'" + fName + "','" + lName + ",'" + address + ",'" + nr1 + ");"; stat.executeUpdate(str); } else { int nr = parseInt(dB[0]); String fName = dB[1], lName = dB[2], address = dB[3]; str = "INSERT INTO members VALUES (" + nr + ",'" + fName + "','" + lName + ",'" + address + ",'" + null + ");"; stat.executeUpdate(str); } } } catch (FileNotFoundException fnf) { out.println("Not found!"); } finally { if (read != null) { read.close(); } } You could write this more briefly as try (Scanner read = new Scanner(new File("register.txt"))) { while (read.hasNext()) { String[] dB = read.nextLine().split("[;]"); int nr = parseInt(dB[0]); String fName = dB[1]; String lName = dB[2]; String address = dB[3]; str = "INSERT INTO members VALUES (" + nr + ", '" + fName + "', '" + lName + ", '" + address + "', "; if (dB.length == 6) { int nr1 = parseInt(dB[4]); str += nr1; } else { str += "NULL"; } str += ");"
{ "domain": "codereview.stackexchange", "id": 43156, "lm_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, homework, swing, sqlite, jdbc", "url": null }
java, homework, swing, sqlite, jdbc stat.executeUpdate(str); } } catch (FileNotFoundException fnf) { out.println("Not found!"); }
{ "domain": "codereview.stackexchange", "id": 43156, "lm_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, homework, swing, sqlite, jdbc", "url": null }
java, homework, swing, sqlite, jdbc Switching to the try-with-resources form eliminates the need for a finally block. Since you don't handle it other than to produce output, you might drop the catch block as well. I haven't examined your logic in great detail, but this seems like a fatal condition to me. Rather than catching the exception, it might be better to let it go. Then if this happens, your program crashes immediately. As is, you would continue on to attempt more processing. That processing will probably fail and cause more output. And it could cause side effects (e.g. modifications to your database). If you crash instead, you will know exactly where things went south and won't have to filter out additional information. Catching an exception that you don't handle is a well known anti-pattern. Try to only initialize one variable per line. The compiler won't care, but this way is easier to read. I'm not convinced of the utility of parsing a String into an int only to convert it back to a String. But it may have useful side effects and it will be easier to switch to parameterized queries later, so I left it. You don't need redundant code inside your if. If the same code is in both branches of the if, then try to factor it out of the if. Then only the different code will be there. Both shorter and easier to read. I removed the implicit conversion from null to the string "null" and replaced it with the explicit string "NULL". I simply find that to be more reliable and easier to follow. It also may save you from having a PHP developer convert it to an empty string, as that's the default behavior in PHP. Future things to do Read up on Connection.prepareStatement with parameters. When doing a query inside a loop, this will be more efficient than rebuilding the entire query every time.
{ "domain": "codereview.stackexchange", "id": 43156, "lm_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, homework, swing, sqlite, jdbc", "url": null }
java, homework, swing, sqlite, jdbc You could break out most of these methods into their own classes. The new classes could have fewer dependencies per class. In particular, you might migrate your database calls to Database Access Objects. This might help reduce some of the boilerplate in your methods.
{ "domain": "codereview.stackexchange", "id": 43156, "lm_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, homework, swing, sqlite, jdbc", "url": null }
performance, swift Title: Finding the longest prefix among words in a string separated by spaces (Swift) Question: Solving the problem Write a function that accepts a string of words with a similar prefix, separated by spaces, and returns the longest substring that prefixes all words. Sample input and output The string “swift switch swill swim” should return “swi”. The string “flip flap flop” should return “fl”. I have import Foundation func longestPrefix(of string: String) -> String { var longestPrefix = "" var prefixBeingChecked = "" let wordArray = string.components(separatedBy: " ") var firstWord = wordArray[0] for character in firstWord { prefixBeingChecked += String(character) for word in wordArray { if !word.hasPrefix(prefixBeingChecked) { return longestPrefix } } longestPrefix = prefixBeingChecked } return longestPrefix } print(longestPrefix(of: "swift switch swill swim")) But I'm not sure how I might improve on the quadratic time complexity. What would be a good way to improve performance? Answer: Some remarks: let wordArray = string.components(separatedBy: " ") produces an array of strings. A slightly more memory-efficient method is let wordArray = string.split(separator: " ") which produces an array of Substrings which share the character storage with the original string. The variable var firstWord = wordArray[0] is never mutated and should be defined as a constant with let. If we use split(separator:) then the array can be empty: guard let firstWord = wordArray.first else { return "" } In the inner loop for word in wordArray { ... } it is not necessary to check against the first word in the list, so one can replace that by for word in wordArray.dropFirst() { ... }
{ "domain": "codereview.stackexchange", "id": 43157, "lm_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, swift", "url": null }
performance, swift Is is not common practice in Swift to make the type part of the variable name, so I would replace wordArray by, e.g., words. A more efficient algorithm A more efficient solution has been described in Find the longest common starting substring in a set of strings on Stack Overflow, see also How to determine longest common prefix and suffix for array of strings? on Stack Overflow: Find the smallest and largest string in the array. Determine the common prefix of just those two strings. The first part requires only a linear traversal of the array, plus the cost of the string comparisons. There is a dedicated method commonPrefix(with:) for the second part. This leads to the following implementation: func longestCommonPrefix(of string: String) -> String { let words = string.split(separator: " ") guard let first = words.first else { return "" } var (minWord, maxWord) = (first, first) for word in words.dropFirst() { if word < minWord { minWord = word } else if word > maxWord { maxWord = word } } return minWord.commonPrefix(with: maxWord) }
{ "domain": "codereview.stackexchange", "id": 43157, "lm_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, swift", "url": null }
swift, community-challenge, sprite-kit Title: Swiftly turning wheels – The May 2017 Community Challenge Question: This is my attempt at the May 2017 Community Challenge in Swift, with a chain consisting of rigid links. I took this as an opportunity to learn SpriteKit, Apple's framework for 2D games. At least Xcode 8.3.2 with Swift 3 is required to compile the code. It runs on both macOS and iOS (instructions below). VectorUtils.swift – Some helper methods for vector calculations. import CoreGraphics let π = CGFloat.pi extension CGVector { init(from: CGPoint, to: CGPoint) { self.init(dx: to.x - from.x, dy: to.y - from.y) } func cross(_ other: CGVector) -> CGFloat { return dx * other.dy - dy * other.dx } var length: CGFloat { return hypot(dx, dy) } var arg: CGFloat { return atan2(dy, dx) } } Sprocket.swift – The type describing a single sprocket. import CoreGraphics
{ "domain": "codereview.stackexchange", "id": 43158, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift, community-challenge, sprite-kit", "url": null }
swift, community-challenge, sprite-kit Sprocket.swift – The type describing a single sprocket. import CoreGraphics struct Sprocket { let center: CGPoint let radius: CGFloat let teeth: Int var clockwise: Bool! var prevAngle: CGFloat! var nextAngle: CGFloat! var prevPoint: CGPoint! var nextPoint: CGPoint! init(center: CGPoint, radius: CGFloat) { self.center = center self.radius = radius self.teeth = Int((radius/2).rounded()) } init(_ triplet: (x: CGFloat, y: CGFloat, r: CGFloat)) { self.init(center: CGPoint(x: triplet.x, y: triplet.y), radius: triplet.r) } // Normalize angles such that // 0 <= prevAngle < 2π // and // prevAngle <= nextAngle < prevAngle + 2π (if rotating counter-clockwise) // prevAngle - 2π < nextAngle <= prevAngle (if rotating clockwise) mutating func normalizeAngles() { prevAngle = prevAngle.truncatingRemainder(dividingBy: 2 * π) nextAngle = nextAngle.truncatingRemainder(dividingBy: 2 * π) while prevAngle < 0 { prevAngle = prevAngle + 2 * π } if clockwise { while nextAngle > prevAngle { nextAngle = nextAngle - 2 * π } } else { while nextAngle < prevAngle { nextAngle = nextAngle + 2 * π } } } mutating func computeTangentPoints() { prevPoint = CGPoint(x: center.x + radius * cos(prevAngle), y: center.y + radius * sin(prevAngle)) nextPoint = CGPoint(x: center.x + radius * cos(nextAngle), y: center.y + radius * sin(nextAngle)) } } ChainDrive.swift - The type describing the complete chain drive system. Also contains the code to compute rotation directions, tangent angles/points, and the length of the various segments of the chain. import CoreGraphics
{ "domain": "codereview.stackexchange", "id": 43158, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift, community-challenge, sprite-kit", "url": null }
swift, community-challenge, sprite-kit struct ChainDrive { var sprockets: [Sprocket] var length: CGFloat! var period: CGFloat! var linkCount: Int! var accumLength: [(CGFloat, CGFloat)]! init(sprockets: [Sprocket]) { self.sprockets = sprockets computeSprocketData() computeChainLength() } init(_ triplets: [(CGFloat, CGFloat, CGFloat)]) { self.init(sprockets: triplets.map(Sprocket.init)) } mutating func computeSprocketData() { // Compute rotation directions: for i in 0..<sprockets.count { let j = (i + 1) % sprockets.count let k = (j + 1) % sprockets.count let v1 = CGVector(from: sprockets[j].center, to: sprockets[i].center) let v2 = CGVector(from: sprockets[j].center, to: sprockets[k].center) sprockets[j].clockwise = v1.cross(v2) > 0 } if !sprockets[0].clockwise { sprockets[1..<sprockets.count].reverse() for i in 0..<sprockets.count { sprockets[i].clockwise = !sprockets[i].clockwise } } // Compute tangent angles: for i in 0..<sprockets.count { let j = (i + 1) % sprockets.count let v = CGVector(from: sprockets[i].center, to: sprockets[j].center) let d = v.length let a = v.arg if sprockets[i].clockwise == sprockets[j].clockwise { var phi = acos((sprockets[i].radius - sprockets[j].radius)/d) if !sprockets[i].clockwise { phi = -phi } sprockets[i].nextAngle = a + phi sprockets[j].prevAngle = a + phi } else { var phi = acos((sprockets[i].radius + sprockets[j].radius)/d) if !sprockets[i].clockwise { phi = -phi } sprockets[i].nextAngle = a + phi
{ "domain": "codereview.stackexchange", "id": 43158, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift, community-challenge, sprite-kit", "url": null }
swift, community-challenge, sprite-kit phi = -phi } sprockets[i].nextAngle = a + phi sprockets[j].prevAngle = a + phi - π } } // Normalize angles and compute tangent points: for i in 0..<sprockets.count { sprockets[i].normalizeAngles() sprockets[i].computeTangentPoints() } } mutating func computeChainLength() { accumLength = [] length = 0 for i in 0..<sprockets.count { let j = (i + 1) % sprockets.count let l1 = length + abs(sprockets[i].nextAngle - sprockets[i].prevAngle) * sprockets[i].radius let l2 = l1 + CGVector(from: sprockets[i].nextPoint, to: sprockets[j].prevPoint).length accumLength.append((l1, l2)) length = l2 } let count = Int(length / (4 * π)) let p1 = length / CGFloat(count) let p2 = length / CGFloat(count + 1) if abs(p1 - 4 * π) <= abs(p2 - 4 * π) { period = p1 linkCount = count } else { period = p2 linkCount = count + 1 } } func linkCoordinatesAndPhases(offset: CGFloat) -> ([CGPoint], [CGFloat]) { var coords: [CGPoint] = [] var phases: [CGFloat] = [] var offset = offset var total = offset var i = 0
{ "domain": "codereview.stackexchange", "id": 43158, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift, community-challenge, sprite-kit", "url": null }
swift, community-challenge, sprite-kit repeat { let j = (i + 1) % sprockets.count let s: CGFloat = sprockets[i].clockwise ? -1 : 1 var phi = sprockets[i].prevAngle + s*offset / sprockets[i].radius phases.append(phi) while total <= accumLength[i].0 && coords.count < linkCount { coords.append(CGPoint(x: sprockets[i].center.x + cos(phi) * sprockets[i].radius, y: sprockets[i].center.y + sin(phi) * sprockets[i].radius)) phi += s * period / sprockets[i].radius total += period } var d = total - accumLength[i].0 let v = CGVector(from: sprockets[i].nextPoint, to: sprockets[j].prevPoint) while total <= accumLength[i].1 && coords.count < linkCount { coords.append(CGPoint(x: sprockets[i].nextPoint.x + d * v.dx / v.length, y: sprockets[i].nextPoint.y + d * v.dy / v.length)) d += period total += period } offset = total - accumLength[i].1 i = j } while coords.count < linkCount return (coords, phases) } } SprocketNode.swift – Defines a SKShapeNode subclass for drawing a single sprocket. import SpriteKit
{ "domain": "codereview.stackexchange", "id": 43158, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift, community-challenge, sprite-kit", "url": null }
swift, community-challenge, sprite-kit SprocketNode.swift – Defines a SKShapeNode subclass for drawing a single sprocket. import SpriteKit class SprocketNode: SKShapeNode { let radius: CGFloat let clockwise: Bool let teeth: Int init(sprocket: Sprocket) { self.radius = sprocket.radius self.clockwise = sprocket.clockwise self.teeth = sprocket.teeth super.init() let path = CGMutablePath() path.move(to: CGPoint(x: radius - 2, y: 0)) for i in 0..<teeth { let a1 = π * CGFloat(4 * i - 1)/CGFloat(2 * teeth) let a2 = π * CGFloat(4 * i + 1)/CGFloat(2 * teeth) let a3 = π * CGFloat(4 * i + 3)/CGFloat(2 * teeth) path.addArc(center: CGPoint.zero, radius: radius - 2, startAngle: a1, endAngle: a2, clockwise: false) path.addArc(center: CGPoint.zero, radius: radius + 2, startAngle: a2, endAngle: a3, clockwise: false) } path.closeSubpath() self.path = path self.lineWidth = 0 self.fillColor = SKColor(red: 0x86/255, green: 0x84/255, blue: 0x81/255, alpha: 1) // #868481 self.strokeColor = .clear self.position = sprocket.center do { let path = CGMutablePath() path.addEllipse(in: CGRect(x: -3, y: -3, width: 6, height: 6)) path.addEllipse(in: CGRect(x: -radius + 4.5, y: -radius + 4.5, width: 2 * radius - 9, height: 2 * radius - 9)) let node = SKShapeNode(path: path) node.fillColor = SKColor(red: 0x64/255, green: 0x63/255, blue: 0x61/255, alpha: 1) // #646361 node.lineWidth = 0 node.strokeColor = .clear self.addChild(node) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
{ "domain": "codereview.stackexchange", "id": 43158, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift, community-challenge, sprite-kit", "url": null }
swift, community-challenge, sprite-kit LinkNode.swift – Defines a SKShapeNode subclass for drawing a chain link. import SpriteKit class LinkNode: SKShapeNode { static let narrowWidth: CGFloat = 2 static let wideWidth : CGFloat = 6 let pitch: CGFloat init(pitch: CGFloat) { self.pitch = pitch super.init() let phi = asin(LinkNode.narrowWidth / LinkNode.wideWidth) let path = CGMutablePath() path.addArc(center: CGPoint(x: -pitch/2, y: 0), radius: LinkNode.wideWidth/2, startAngle: phi, endAngle: 2 * π - phi, clockwise: false) path.addLine(to: CGPoint(x: pitch/2, y: -LinkNode.narrowWidth/2)) path.addArc(center: CGPoint(x: pitch/2, y: 0), radius: LinkNode.narrowWidth/2, startAngle: -π/2, endAngle: π/2, clockwise: false) path.closeSubpath() self.path = path self.fillColor = .black self.lineWidth = 0 self.strokeColor = .clear } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func moveTo(leftPin: CGPoint, rightPin: CGPoint) { position = CGPoint(x: (leftPin.x + rightPin.x)/2, y: (leftPin.y + rightPin.y)/2) zRotation = CGVector(from: leftPin, to: rightPin).arg } } ChainDriveScene.swift – Defines a SKScene subclass for drawing and animating the chain drive. import SpriteKit typealias Triples = [(CGFloat, CGFloat, CGFloat)] // The system from the challenge: https://codereview.meta.stackexchange.com/a/7264 : let system0: Triples = [(0, 0, 16), (100, 0, 16), (100, 100, 12), (50, 50, 24), (0, 100, 12)]
{ "domain": "codereview.stackexchange", "id": 43158, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift, community-challenge, sprite-kit", "url": null }
swift, community-challenge, sprite-kit // Other systems from https://codegolf.stackexchange.com/q/64764: let system1: Triples = [(0, 0, 26), (120, 0, 26)] let system2: Triples = [(100, 100, 60), (220, 100, 14)] let system3: Triples = [(100, 100, 16), (100, 0, 24), (0, 100, 24), (0, 0, 16)] let system4: Triples = [(0, 0, 60), (44, 140, 16), (-204, 140, 16), (-160, 0, 60), (-112, 188, 12), (-190, 300, 30), (30, 300, 30), (-48, 188, 12)] let system5: Triples = [(0, 128, 14), (46.17, 63.55, 10), (121.74, 39.55, 14), (74.71, -24.28, 10), (75.24, -103.55, 14), (0, -78.56, 10), (-75.24, -103.55, 14), (-74.71, -24.28, 10), (-121.74, 39.55, 14), (-46.17, 63.55, 10)] let system6: Triples = [(367, 151, 12), (210, 75, 36), (57, 286, 38), (14, 181, 32), (91, 124, 18), (298, 366, 38), (141, 3, 52), (80, 179, 26), (313, 32, 26), (146, 280, 10), (126, 253, 8), (220, 184, 24), (135, 332, 8), (365, 296, 50), (248, 217, 8), (218, 392, 30)]
{ "domain": "codereview.stackexchange", "id": 43158, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift, community-challenge, sprite-kit", "url": null }
swift, community-challenge, sprite-kit class ChainDriveScene: SKScene { let chainDrive: ChainDrive let chainSpeed = 16 * π // speed (points/sec) var initialTime: TimeInterval! var sprocketNodes: [SprocketNode] = [] var linkNodes: [LinkNode] = [] class func newScene() -> ChainDriveScene { let system = ChainDrive(system0) return ChainDriveScene(system: system) } init(system: ChainDrive) { self.chainDrive = system let minx = system.sprockets.map { $0.center.x - $0.radius }.min()! - 15 let miny = system.sprockets.map { $0.center.y - $0.radius }.min()! - 15 let maxx = system.sprockets.map { $0.center.x + $0.radius }.max()! + 15 let maxy = system.sprockets.map { $0.center.y + $0.radius }.max()! + 15 super.init(size: CGSize(width: maxx - minx, height: maxy - miny)) self.anchorPoint = CGPoint(x: -minx/(maxx - minx), y: -miny/(maxy - miny)) self.scaleMode = .aspectFit } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setUpScene() { backgroundColor = .white sprocketNodes = chainDrive.sprockets.map(SprocketNode.init) for node in sprocketNodes { self.addChild(node) } let (coords, _) = chainDrive.linkCoordinatesAndPhases(offset: 0) for i in 0..<coords.count { let j = (i + 1) % coords.count let node = LinkNode(pitch: chainDrive.period) node.moveTo(leftPin: coords[i], rightPin: coords[j]) self.addChild(node) linkNodes.append(node) } } override func didMove(to view: SKView) { self.setUpScene() } override func update(_ currentTime: TimeInterval) { if initialTime == nil { initialTime = currentTime } let distance = CGFloat(currentTime - initialTime) * chainSpeed * speed
{ "domain": "codereview.stackexchange", "id": 43158, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift, community-challenge, sprite-kit", "url": null }
swift, community-challenge, sprite-kit } let distance = CGFloat(currentTime - initialTime) * chainSpeed * speed let k = Int(distance/chainDrive.period) % linkNodes.count let offset = distance.truncatingRemainder(dividingBy: chainDrive.period) let (coords, phases) = chainDrive.linkCoordinatesAndPhases(offset: offset) for i in 0..<linkNodes.count { let p1 = coords[i % coords.count] let p2 = coords[(i + 1) % coords.count] linkNodes[(i + linkNodes.count - k) % linkNodes.count].moveTo(leftPin: p1, rightPin: p2) } for i in 0..<phases.count { sprocketNodes[i].zRotation = phases[i] } } }
{ "domain": "codereview.stackexchange", "id": 43158, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift, community-challenge, sprite-kit", "url": null }
swift, community-challenge, sprite-kit The complete project is available on GitHub. Alternatively: In Xcode 8.3.2 (or later), create a new project from the "Cross-platform SpriteKit Game" template. Select "Include iOS Application" and/or "Include macOS Application". Add the above source files to the project. In the GameViewController.swift files, replace let scene = GameScene.newGameScene() by let scene = ChainDriveScene.newScene() Compile and run! The animation runs with approx 60 frames per second, both on a 1.2 GHz MacBook and on an iPhone 6s. To give you a rough impression of what it looks like, I took a screen recording with QuickTime Player and converted it to an animated GIF with ffmpeg and gifsicle: All feedback is welcome, such as (but not limited to): Can the geometrical computations be simplified? Are there any better type/variable/function names? There are several "implicitly unwrapped optional" properties in struct Sprocket. The reason is that these are computed (in func computeSprocketData()) after all sprockets have been initialized. Any suggestions on how to do this two-step initialization more elegantly? Initially I used a SKAction for rotating the sprockets, but did not find a way to animate the chain with SKActions. Therefore both sprockets and chain links are now updated in the update() method (which is called for each frame). Is there a better way to achieve the same result? Another idea was to use SKAction.followPath() to animate the chain links. That worked well for one link, but I could not figure out how to make the other links follow the same path with a delay. Is that possible? This is my first SpriteKit project, therefore any advice on how to make more idiomatic use of that framework is appreciated.
{ "domain": "codereview.stackexchange", "id": 43158, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift, community-challenge, sprite-kit", "url": null }
swift, community-challenge, sprite-kit Answer: Perhaps the fact that this has gone unanswered for quite some time is a testament to the quality of the code. It appears the code is separated well into individual files and indentation is consistent. Some could argue that there should be more comments, though the code is somewhat self-documenting as methods are named appropriately. Some variable names are a bit overly brief - e.g. var d within ChainDrive.swift (in multiple functions). In some cases this is assigned to the difference between twonumbers - for example: in the repeat loop within linkCoordinatesAndPhases() var d = total - accumLength[i].0 and then in the sub-sequent while loop values are added to it: d += period in other cases it is simply assigned to the length of a vector - e.g. in the loop within computeSprocketData() let v = CGVector(from: sprockets[i].center, to: sprockets[j].center) let d = v.length
{ "domain": "codereview.stackexchange", "id": 43158, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "swift, community-challenge, sprite-kit", "url": null }
c#, performance, .net Title: Reading big csv file C# Question: I'm trying to read quite big file with around 28 million of rows in the following way: var jobs = new ActionBlock<string[]>((jobs) => { //Some code }); var pool = ArrayPool<string>.Shared; var items = pool.Rent(1000); using (FileStream fs = File.Open("test.csv", FileMode.Open)) using (BufferedStream bs = new BufferedStream(fs)) using (StreamReader sr = new StreamReader(bs, Encoding.UTF8, true, 1024)) { var count = 0; string s; while ((s = sr.ReadLine()) != null) { items[count] = s; if (count++ == 999) { count = 0; jobs.Post(items); } } jobs.Complete(); } await jobs.Completion; pool.Return(items); I'm trying to read it by means of ReadLine with some pre-defined buffer. Now it takes around 17 seconds in average. Each line contains alike lines: 100.1.8.hah,2017-05-16,00:00:00,0.0,1054102.0,0001493152-17-005364,form8-k.htm,200.0,3767.0,0.0,0.0,0.0,9.0,0.0, How can I be sure is it slow and needs enhancements or it's quite appropriate ? If someone have some clues please let me know please ...
{ "domain": "codereview.stackexchange", "id": 43159, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, .net", "url": null }
c#, performance, .net Answer: Generally IO operations are the slowest. You potentially have an issue with your code. ActionBlock can be async or chained into other blocks. Because you are sharing the same array on each post the data will change. Typically ArrayPools should be used if you are in control over the entire lifetime and usage of the array. When pushing it out of the method you lose that control. You can also replace all the low level code of FileStream/BufferedStream/StreamReader with just File.ReadLines and if using .NET 6 could use Enumerable.Chunk to group them. Usually large files the biggest concern is loading too much in memory. While using the IEnumerable of File.ReadLines will only load into memory as it's demanded. If wanting to go more "async" to not block on readings could still use the StreamReader.ReadLineAsync and implement IAsyncEnumerable. Example of how changing ActionBlock can compile but at runtime have strange results. On my machine I do not always get the same results on both Console.Log var jobs = new ActionBlock<string[]>(async (jobs) => { var count = Interlocked.Increment(ref _count); if (count == 1) { Console.WriteLine(jobs[0]); } await Task.Delay(TimeSpan.FromSeconds(2)); if (count == 1) { Console.WriteLine(jobs[0]); } });
{ "domain": "codereview.stackexchange", "id": 43159, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, .net", "url": null }
c#, pdf Title: Adding a PDF file using iText7 Question: Can I improve this code and make it more beautiful? For example, I am using a switch statement and for each page but I only add edits to page 1 and page 2? byte[] b = null; MemoryStream stream = new MemoryStream(buffer); string _Number = "4.2021"; string _disclaimer = "Text"; using (MemoryStream returnMemoryStream = new MemoryStream()) { PdfReader = new PdfReader(stream); PdfDocument pdfDocument = new PdfDocument(PdfReader, new PdfWriter(returnMemoryStream)); int numberOfPages = pdfDocument.GetNumberOfPages(); for (int i = 1; i <= 2; i++) { PdfPage pdfPage = pdfDocument.GetPage(i); PdfCanvas canvasPage = new PdfCanvas(pdfPage); switch (i) { case 1: int versionpage1X = 735; int versionpage1Y = 248; canvasPage.BeginText() .SetFontAndSize(PdfFontFactory .CreateFont(StandardFonts.HELVETICA_BOLD), 34) .MoveText(versionpage1X, versionpage1Y) .SetFillColor(ColorConstants.WHITE) .ShowText(_versionNumber) .EndText(); break; case 2: int versionpage2X = 760; int versionpage2Y = 573;
{ "domain": "codereview.stackexchange", "id": 43160, "lm_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#, pdf", "url": null }
c#, pdf canvasPage.BeginText() .SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD), 21) .MoveText(versionpage2X, versionpage2Y) .SetFillColor(ColorConstants.WHITE) .ShowText(_versionNumber) .EndText(); float disclaimerpage2X = 75; float disclaimerpage2Y = 26; iText.Kernel.Geom.Rectangle rectangle = new iText.Kernel.Geom.Rectangle(disclaimerpage2X, disclaimerpage2Y, 883, 81); Canvas canvas = new Canvas(canvasPage, rectangle); Paragraph p = new Paragraph() .Add(_disclaimer) .SetFont(PdfFontFactory.CreateFont(StandardFonts.HELVETICA)) .SetFontColor(ColorConstants.BLACK) .SetFontSize(12) .SetTextAlignment(TextAlignment.LEFT); canvas.Add(p); canvas.Close(); //Image float mapimageX = 111.318f; float mapimageY = 130.791f; float mapimageWidth = 755.454f; float mapimageHeight = 432.094f; ImageData imageData = ImageDataFactory.Create(@"PathtoImage.png"); iText.Kernel.Geom.Rectangle imagerectangle = new iText.Kernel.Geom.Rectangle(mapimageX, mapimageY, mapimageWidth, mapimageHeight); canvasPage.AddImageFittedIntoRectangle(imageData, imagerectangle,true); break; }
{ "domain": "codereview.stackexchange", "id": 43160, "lm_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#, pdf", "url": null }
c#, pdf break; } } pdfDocument.Close(); b = returnMemoryStream.ToArray(); } Answer: Main I would suggest to extract the two case branches' code into separate methods. After that your top-level functionality could be simplified like this: using var originalPdfStream = new MemoryStream(buffer); using var modifiedPdfStream = new MemoryStream(); var pdfReader = new PdfReader(originalPdfStream); var pdfDocument = new PdfDocument(pdfReader, new PdfWriter(modifiedPdfStream)); EditFirstPage(pdfDocument); EditSecondPage(pdfDocument); pdfDocument.Close(); byte[] modifiedPdfInBytes = modifiedPdfStream.ToArray(); I've renamed your variables to better express the intent (like stream >> originalPdfStream) I've used C# 8's using declaration to reduce code indentation If you are using older C# version then you can only use here using statement First page void EditFirstPage(PdfDocument pdfDocument) { var canvasPage = new PdfCanvas(pdfDocument.GetFirstPage()); canvasPage.BeginText() .SetFontAndSize(PdfFontFactory.CreateFont(Common.Font), Page1.FontSize) .MoveText(Page1.Version.X, Page1.Version.Y) .SetFillColor(Common.FillColor) .ShowText(Common.VersionNumber) .EndText(); } I've moved all the hard-coded values into a dedicated class called Page1 Those constants that are shared between page 1 and 2 have been moved to a class called Common static class Common { public const string Font = StandardFonts.HELVETICA_BOLD; public static readonly Color FillColor = ColorConstants.WHITE; public const string VersionNumber = "4.2021"; } static class Page1 { public const int FontSize = 34; public static class Version { public const int X = 735, Y = 248; } }
{ "domain": "codereview.stackexchange", "id": 43160, "lm_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#, pdf", "url": null }
c#, pdf Second Page void EditSecondPage(PdfDocument pdfDocument) { var canvasPage = new PdfCanvas(pdfDocument.GetPage(2)); canvasPage.BeginText() .SetFontAndSize(PdfFontFactory.CreateFont(Common.Font), Page2.FontSize) .MoveText(Page2.Version.X, Page2.Version.Y) .SetFillColor(Common.FillColor) .ShowText(Common.VersionNumber) .EndText(); var rectangle = new Rectangle(Page2.Disclaimer.X, Page2.Disclaimer.Y, Page2.Disclaimer.Width, Page2.Disclaimer.Height); var canvas = new Canvas(canvasPage, rectangle); var paragraph = new Paragraph() .Add(Page2.Paragraph.Disclaimer) .SetFont(PdfFontFactory.CreateFont(Page2.Paragraph.Font)) .SetFontColor(Page2.Paragraph.FontColor) .SetFontSize(Page2.Paragraph.FontSize) .SetTextAlignment(TextAlignment.LEFT); canvas.Add(paragraph); canvas.Close(); ImageData imageData = ImageDataFactory.Create(Page2.MapImage.FileName); var imageRectangle = new Rectangle(Page2.MapImage.X, Page2.MapImage.Y, Page2.MapImage.Width, Page2.MapImage.Height); canvasPage.AddImageFittedIntoRectangle(imageData, imageRectangle, true); } I've renamed some variables and moved the hard-coded values into a dedicated class
{ "domain": "codereview.stackexchange", "id": 43160, "lm_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#, pdf", "url": null }
c#, pdf I've renamed some variables and moved the hard-coded values into a dedicated class static class Page2 { public const int FontSize = 21; public static class Version { public const int X = 760, Y = 573; } public static class Disclaimer { public const float X = 75, Y = 26; public const float Width = 883, Height = 81; } public static class MapImage { public const string FileName = "PathtoImage.png"; public const float X = 111.318f, Y = 130.791f; public const float Width = 755.454f, Height = 432.094f; } public static class Paragraph { public const string Disclaimer = "Text"; public const string Font = StandardFonts.HELVETICA; public static readonly Color FontColor = ColorConstants.BLACK; public const int FontSize = 12; } } The code which adds the version number to a specific page is redundant. You can define a helper method to that like this: void AddVersionNumber(PdfCanvas canvasPage, int fontSize, double x, double y) => canvasPage.BeginText() .SetFontAndSize(PdfFontFactory.CreateFont(Common.Font), fontSize) .MoveText(x, y) .SetFillColor(Common.FillColor) .ShowText(Common.VersionNumber) .EndText(); For the sake of completeness here is the full code using var originalPdfStream = new MemoryStream(buffer); using var modifiedPdfStream = new MemoryStream(); var pdfReader = new PdfReader(originalPdfStream); var pdfDocument = new PdfDocument(pdfReader, new PdfWriter(modifiedPdfStream)); EditFirstPage(pdfDocument); EditSecondPage(pdfDocument); pdfDocument.Close(); byte[] modifiedPdfInBytes = modifiedPdfStream.ToArray();
{ "domain": "codereview.stackexchange", "id": 43160, "lm_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#, pdf", "url": null }
c#, pdf pdfDocument.Close(); byte[] modifiedPdfInBytes = modifiedPdfStream.ToArray(); void AddVersionNumber(PdfCanvas canvasPage, int fontSize, double x, double y) => canvasPage.BeginText() .SetFontAndSize(PdfFontFactory.CreateFont(Common.Font), fontSize) .MoveText(x, y) .SetFillColor(Common.FillColor) .ShowText(Common.VersionNumber) .EndText(); void EditFirstPage(PdfDocument pdfDocument) => AddVersionNumber(new PdfCanvas(pdfDocument.GetFirstPage()), Page1.FontSize, Page1.Version.X, Page1.Version.Y); void EditSecondPage(PdfDocument pdfDocument) { var canvasPage = new PdfCanvas(pdfDocument.GetPage(2)); AddVersionNumber(canvasPage, Page2.FontSize, Page2.Version.X, Page2.Version.Y); var rectangle = new Rectangle(Page2.Disclaimer.X, Page2.Disclaimer.Y, Page2.Disclaimer.Width, Page2.Disclaimer.Height); var canvas = new Canvas(canvasPage, rectangle); var paragraph = new Paragraph() .Add(Page2.Paragraph.Disclaimer) .SetFont(PdfFontFactory.CreateFont(Page2.Paragraph.Font)) .SetFontColor(Page2.Paragraph.FontColor) .SetFontSize(Page2.Paragraph.FontSize) .SetTextAlignment(TextAlignment.LEFT); canvas.Add(paragraph); canvas.Close(); ImageData imageData = ImageDataFactory.Create(Page2.MapImage.FileName); var imageRectangle = new Rectangle(Page2.MapImage.X, Page2.MapImage.Y, Page2.MapImage.Width, Page2.MapImage.Height); canvasPage.AddImageFittedIntoRectangle(imageData, imageRectangle, true); } static class Common { public const string Font = StandardFonts.HELVETICA_BOLD; public static readonly Color FillColor = ColorConstants.WHITE; public const string VersionNumber = "4.2021"; } static class Page1 { public const int FontSize = 34; public static class Version { public const int X = 735, Y = 248; } }
{ "domain": "codereview.stackexchange", "id": 43160, "lm_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#, pdf", "url": null }
c#, pdf static class Page2 { public const int FontSize = 21; public static class Version { public const int X = 760, Y = 573; } public static class Disclaimer { public const float X = 75, Y = 26; public const float Width = 883, Height = 81; } public static class MapImage { public const string FileName = "PathtoImage.png"; public const float X = 111.318f, Y = 130.791f; public const float Width = 755.454f, Height = 432.094f; } public static class Paragraph { public const string Disclaimer = "Text"; public const string Font = StandardFonts.HELVETICA; public static readonly Color FontColor = ColorConstants.BLACK; public const int FontSize = 12; } } UPDATE #1 using statement vs using declaration Prior C#8 you can not use using declaration but you can use using statements using (var originalPdfStream = new MemoryStream(buffer)) using (var modifiedPdfStream = new MemoryStream()) { var pdfReader = new PdfReader(originalPdfStream); var pdfDocument = new PdfDocument(pdfReader, new PdfWriter(modifiedPdfStream)); EditFirstPage(pdfDocument); EditSecondPage(pdfDocument); pdfDocument.Close(); byte[] modifiedPdfInBytes = modifiedPdfStream.ToArray(); }
{ "domain": "codereview.stackexchange", "id": 43160, "lm_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#, pdf", "url": null }
c++, unit-testing, mathematics Title: Unit tests for a 2D Vector class Question: I'm writing a vector class for 2D geometry applications, and below is a rough draft for a unit test using Cpputest. I'm familiar with unit tests, but this is the first I've done for a purely mathematical class, and I'd really appreciate any insight or feedback no matter how small; even personal preference and knit-picking is welcome. #include "CppUTest/TestHarness.h" #include "../Mathos.hpp" #include <stdio.h> // Todo: Put padding (2 newlines) between tests. double const TOLERANCE = 0.000001; static void VECTORS_EQUAL(double x, double y, mat::Vector2D const &V, double tolerance) { DOUBLES_EQUAL(x, V.x, tolerance); DOUBLES_EQUAL(y, V.y, tolerance); } static void VECTORS_EQUAL(mat::Vector2D const &expect, mat::Vector2D const &actual, double tolerance) { VECTORS_EQUAL(expect.x, expect.y, actual, tolerance); } TEST_GROUP(VectorTestGroup) { }; TEST(VectorTestGroup, VectorSize) { CHECK_EQUAL(16, sizeof(mat::Vector2D)); } TEST(VectorTestGroup, VectorIsZeroByDefault) { mat::Vector2D U; VECTORS_EQUAL(0, 0, U, TOLERANCE); } TEST(VectorTestGroup, VectorCanBeCreatedFromValues) { // x is provided, no y mat::Vector2D U(1); VECTORS_EQUAL(1, 0, U, TOLERANCE); mat::Vector2D V(1, 2); VECTORS_EQUAL(1, 2, V, TOLERANCE); } TEST(VectorTestGroup, VectorCanBeCreatedFromVector) { mat::Vector2D U(mat::Vector2D(1, 2)); VECTORS_EQUAL(1, 2, U, TOLERANCE); mat::Vector2D V(U); VECTORS_EQUAL(1, 2, V, TOLERANCE); // Calls the mat::Vector(double, double) // constructor mat::Vector2D W = mat::Vector2D(4, 3); VECTORS_EQUAL(4, 3, W, TOLERANCE); // Calls the copy constructor mat::Vector2D Z = W; VECTORS_EQUAL(4, 3, Z, TOLERANCE); } TEST(VectorTestGroup, VectorAssignment) { mat::Vector2D U(1, 2); mat::Vector2D V(3, 4); U = V; VECTORS_EQUAL(3, 4, U, TOLERANCE); }
{ "domain": "codereview.stackexchange", "id": 43161, "lm_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++, unit-testing, mathematics", "url": null }
c++, unit-testing, mathematics TEST(VectorTestGroup, Vector_addition) { mat::Vector2D U(1, 2); mat::Vector2D V(3, 4); mat::Vector2D W = U + V; VECTORS_EQUAL(4, 6, W, TOLERANCE); } TEST(VectorTestGroup, Vector_addition_self_assignment) { mat::Vector2D A; const mat::Vector2D B( 1, 2); const mat::Vector2D C(-3, 4); const mat::Vector2D D(-5, -6); const mat::Vector2D E( 7, -8); A += B; VECTORS_EQUAL(1, 2, A, TOLERANCE); A += C; VECTORS_EQUAL(-2, 6, A, TOLERANCE); A += D; VECTORS_EQUAL(-7, 0, A, TOLERANCE); A += E; VECTORS_EQUAL(0, -8, A, TOLERANCE); mat::Vector2D F; mat::Vector2D G(1, 1); F = G += A; VECTORS_EQUAL(1, -7, F, TOLERANCE); } TEST(VectorTestGroup, Vector_subtraction) { mat::Vector2D U(1, 2); mat::Vector2D V(3, 4); mat::Vector2D W = U - V; VECTORS_EQUAL(-2, -2, W, TOLERANCE); } TEST(VectorTestGroup, Vector_subtraction_self_assignment) { mat::Vector2D A; const mat::Vector2D B( 1, 2); const mat::Vector2D C(-3, 4); const mat::Vector2D D(-5, -6); const mat::Vector2D E( 7, -8); A -= B; VECTORS_EQUAL(-1, -2, A, TOLERANCE); A -= C; VECTORS_EQUAL(2, -6, A, TOLERANCE); A -= D; VECTORS_EQUAL(7, 0, A, TOLERANCE); A -= E; VECTORS_EQUAL(0, 8, A, TOLERANCE); mat::Vector2D F; mat::Vector2D G(1, 1); F = G -= A; VECTORS_EQUAL(1, -7, F, TOLERANCE); } TEST(VectorTestGroup, Scalar_multiplication) { mat::Vector2D U(1, 2); mat::Vector2D V = 10 * U; // Number comes first VECTORS_EQUAL(10, 20, V, TOLERANCE); V = V * 3; // Vector comes first VECTORS_EQUAL(30, 60, V, TOLERANCE); } TEST(VectorTestGroup, Scalar_multiplication_self_assignment) { mat::Vector2D A(1, 2); A *= 2; VECTORS_EQUAL(2, 4, A, TOLERANCE); A *= -4.5; VECTORS_EQUAL(-9, -18, A, TOLERANCE); mat::Vector2D B = A *= 0.25; VECTORS_EQUAL(-2.25, -4.5, B, TOLERANCE); }
{ "domain": "codereview.stackexchange", "id": 43161, "lm_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++, unit-testing, mathematics", "url": null }
c++, unit-testing, mathematics mat::Vector2D B = A *= 0.25; VECTORS_EQUAL(-2.25, -4.5, B, TOLERANCE); } TEST(VectorTestGroup, Scalar_division) { mat::Vector2D U(1, 2); mat::Vector2D V = U / 4; VECTORS_EQUAL(0.25, 0.50, V, TOLERANCE); } TEST(VectorTestGroup, Scalar_division_self_assignment) { mat::Vector2D A(1, 2); A /= 2; VECTORS_EQUAL(0.5, 1, A, TOLERANCE); A /= -4; VECTORS_EQUAL(-0.125, -0.25, A, TOLERANCE); mat::Vector2D B = A /= 0.1; VECTORS_EQUAL(-1.25, -2.5, B, TOLERANCE); } void printVectorTest(const mat::Vector2D& expected, const mat::Vector2D& actual) { // Print vector as minimum one digit with 24 digits // trailing after the decimal point. printf("\n"); printf("Expected: <%1.24f, %1.24f>\n", expected.x, expected.y); printf(" Got: <%1.24f, %1.24f>\n", actual.x, actual.y); } TEST(VectorTestGroup, Vector_equality) { mat::Vector2D const A(1, 2); mat::Vector2D const B(3, 4); mat::Vector2D const C(1, 2); CHECK(A == A); CHECK(A == C); CHECK_FALSE(A == B); } TEST(VectorTestGroup, Vectors_that_are_about_the_same_are_equal) { // This is not exactly 0.3 mat::Vector2D const x(0.3); // Floating-point rounding errors will build up here mat::Vector2D const myPointNine = x + x + x; mat::Vector2D const expectedPointNine(0.9); printVectorTest(expectedPointNine, myPointNine); // Even though the result is not exactly 0.9, it's close // enough to be considered equal to 0.9 CHECK(myPointNine == expectedPointNine); } TEST(VectorTestGroup, Subtracting_two_equal_vectors_gives_the_zero_vector) { mat::Vector2D const b(3 * mat::Vector2D(0.3) - mat::Vector2D(0.9)); mat::Vector2D const ZERO_VECTOR; printVectorTest(ZERO_VECTOR, b); CHECK(b == ZERO_VECTOR); }
{ "domain": "codereview.stackexchange", "id": 43161, "lm_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++, unit-testing, mathematics", "url": null }
c++, unit-testing, mathematics printVectorTest(ZERO_VECTOR, b); CHECK(b == ZERO_VECTOR); } TEST(VectorTestGroup, Very_small_vectors_are_not_equal_to_the_zero_vector) { CHECK_FALSE(mat::Vector2D(0.000001) == mat::Vector2D(0)); CHECK_FALSE(mat::Vector2D(0.000000001) == mat::Vector2D(0)); CHECK_FALSE(mat::Vector2D(0.000000000001) == mat::Vector2D(0)); } TEST(VectorTestGroup, Vector_inequality) { mat::Vector2D const A(1, 2); mat::Vector2D const B(3, 4); mat::Vector2D const C(1, 2); CHECK_FALSE(A != A); CHECK_FALSE(A != C); CHECK(A != B); } TEST_GROUP(VectorOperationsGroup) { void setup() { mat::Vector2D U; } void teardown() { } }; IGNORE_TEST(VectorOperationsGroup, LENGTH) { // DOUBLES_EQUAL(5.000000, mat::length( mat::Vector2D( 4, 3) ), TOLERANCE); // DOUBLES_EQUAL(9.055385, mat::length( mat::Vector2D(-1, 9) ), TOLERANCE); // DOUBLES_EQUAL(8.246211, mat::length( mat::Vector2D(-8, -2) ), TOLERANCE); // DOUBLES_EQUAL(7.810250, mat::length( mat::Vector2D( 6, -5) ), TOLERANCE); CHECK(true); } IGNORE_TEST(VectorOperationsGroup, UNIT) { // mat::Vector2D const A( 4, 3); // mat::Vector2D const B(-1, 9); // mat::Vector2D const C(-8, -2); // mat::Vector2D const D( 6, -5); // mat::Vector2D a( mat::unit( A ) ); // mat::Vector2D b( mat::unit( B ) ); // mat::Vector2D c( mat::unit( C ) ); // mat::Vector2D d( mat::unit( D ) ); // DOUBLES_EQUAL(1.000000, mat::length(a), TOLERANCE); // DOUBLES_EQUAL(1.000000, mat::length(b), TOLERANCE); // DOUBLES_EQUAL(1.000000, mat::length(c), TOLERANCE); // DOUBLES_EQUAL(1.000000, mat::length(d), TOLERANCE); // VECTORS_EQUAL(A, a * mat::length(A), TOLERANCE); // VECTORS_EQUAL(B, b * mat::length(B), TOLERANCE); // VECTORS_EQUAL(C, c * mat::length(C), TOLERANCE); // VECTORS_EQUAL(D, d * mat::length(D), TOLERANCE); CHECK(true); }
{ "domain": "codereview.stackexchange", "id": 43161, "lm_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++, unit-testing, mathematics", "url": null }
c++, unit-testing, mathematics CHECK(true); } IGNORE_TEST(VectorOperationsGroup, DOT) { // mat::Vector2D const A( 4, 3); // mat::Vector2D const B(-1, 9); // mat::Vector2D const C(-8, -2); // mat::Vector2D const D( 6, -5); // DOUBLES_EQUAL( 23.00000, mat::dot(A, B), TOLERANCE); // DOUBLES_EQUAL(-38.00000, mat::dot(A, C), TOLERANCE); // DOUBLES_EQUAL( 9.000000, mat::dot(A, D), TOLERANCE); CHECK(true); } Vector2D.hpp #ifndef VECTOR_2D_HPP #define VECTOR_2D_HPP #include <ostream> namespace mat { class Vector2D { public: double x, y; Vector2D(); Vector2D(double x, double y = 0); Vector2D(const Vector2D& A); const Vector2D& operator =(const Vector2D& rhs); Vector2D operator +(const Vector2D& rhs) const; Vector2D operator -(const Vector2D& rhs) const; Vector2D operator /(double k) const; const Vector2D& operator +=(const Vector2D& rhs); const Vector2D& operator -=(const Vector2D& rhs); const Vector2D& operator *=(double k); const Vector2D& operator /=(double k); bool operator ==(const Vector2D& rhs) const; bool operator !=(const Vector2D& rhs) const; }; Vector2D operator*(double k, const Vector2D& A); Vector2D operator*(const Vector2D& A, double k); std::ostream& operator<<(std::ostream& os, const Vector2D& A); double length(Vector2D const &U); Vector2D unit(Vector2D const &U); double dot(Vector2D const &U, Vector2D const &V); } #endif Answer: Small things first:
{ "domain": "codereview.stackexchange", "id": 43161, "lm_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++, unit-testing, mathematics", "url": null }
c++, unit-testing, mathematics } #endif Answer: Small things first: Prefer to include the implementation file first, before the unit-test framework files (just in case we accidentally rely on its transitive includes). Include <osfwd> rather than <ostream> where we don't need full definitions. I don't like (non-member) * operator being separated from / so much - either make both functions non-member, or move the vector-first version of * within the class. The IGNORE_TEST functions at the end suggest that the code is still unfinished - code should be finished to be ready for review. We're missing tests of <<, length(), unit() and dot(). Main review: Please don't use all-caps names for things that are not preprocessor macros. That draws reader attention to all the wrong places. The whole "tolerance" complication seems unnecessary here. We're working with exact binary numbers here (apart from a division by 0.1 - that can be changed), so we should be able to use ordinary equality (even when we come to test length(), we can choose a Pythagorean pair to ensure exact results). Testing the vector's size is an over-test. The size shouldn't matter to user programs, and there's no good reason for it to be a fixed size (after all, it depends directly on the the platform's choice of double and char types). It's not clear why the arithmetic tests include more than one invocation of the method under test (particularly the assignment versions). A test normally has three phases - initialise, execute, verify - but these ones break that expectation. Prefer more, smaller tests: TEST(VectorTestGroup, Scalar_multiply_NxV) { VECTORS_EQUAL(mat::Vector2D{10, 20}, 10 * mat::Vector2D{1, 2}); } TEST(VectorTestGroup, Scalar_multiply_VxN) { VECTORS_EQUAL(mat::Vector2D{10, 20}, mat::Vector2D{1, 2} * 10); }
{ "domain": "codereview.stackexchange", "id": 43161, "lm_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++, unit-testing, mathematics", "url": null }
c++, unit-testing, mathematics The tests of == and != imply that those functions have a built-in fuzziness. I would recommend against that, and write a specific "approximately-equals" function instead when fuzzy comparison is required (allowing the user to pass in the relative and/or absolute tolerance to use - a baked-in choice is unlikely to suit all users). One significant aspect of such an unexpected overload is that it violates the contract of ==: users expect that if a == b and b == c, then a == c.
{ "domain": "codereview.stackexchange", "id": 43161, "lm_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++, unit-testing, mathematics", "url": null }
c++, constant-expression Title: Check array contains element at compile time Question: We have a modifyCoefficient(const char* name, int value) function that updates the value of a coefficient in a container. The names are known at compile time, they are read from an XML file in a pre-build step and stored in an array. Usage: data.modifyCoefficient("ADAPTIVE", 1); Compiler: MSVC 2017 v15.8 I would like to get a compile time error when the coefficient name does not exist. With the following code that happens, but is there a way to do it without a macro? #include <array> #define COEFF(name) returnName<coefficientExists(name)>(name) constexpr std::array<const char*, 3> COEFFICIENTS = { "VERSION", "CHANNELS", "ADAPTIVE" }; constexpr bool coefficientExists(const char* name) { for (auto coefficientIndex = 0U; coefficientIndex < COEFFICIENTS.size(); ++coefficientIndex) { if (COEFFICIENTS[coefficientIndex] == name) return true; } return false; } template<bool CoefficientTest> constexpr const char* returnName(const char* name) { static_assert(CoefficientTest, "coefficient does not exist"); return name; } int main() { static_assert(coefficientExists("VERSION"), "should exist"); static_assert(coefficientExists("TEST") == false, "should not exist"); static_assert(COEFF("ADAPTIVE") == "ADAPTIVE", "should return name"); COEFF("CHANNELS"); // data.modifyCoefficient(COEFF("ADAPTIVE"), 1); return 0; } https://godbolt.org/z/kpGcMS Answer: With C++20's consteval this is now possible without static_assert or macro's. Solution based on C++20 to eliminate runtime bugs and Compile-time format string checks. #include <algorithm> #include <array> #include <string_view> using namespace std::string_view_literals; constexpr auto COEFFICIENTS = std::array{ "VERSION"sv, "CHANNELS"sv, "POWER"sv }; struct CoefficientName { std::string_view str;
{ "domain": "codereview.stackexchange", "id": 43162, "lm_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++, constant-expression", "url": null }
c++, constant-expression struct CoefficientName { std::string_view str; consteval CoefficientName(std::string_view name) :str(name) { if(std::ranges::find(COEFFICIENTS, name) == COEFFICIENTS.end()) throw; } }; void modifyCoefficient(CoefficientName name, int value) { } int main() { modifyCoefficient("CHANNELS"sv, 42); modifyCoefficient("CURRENT"sv, 99); // compilation error modifyCoefficient("POWER"sv, 1); return 0; } https://godbolt.org/z/M3oE4acxc
{ "domain": "codereview.stackexchange", "id": 43162, "lm_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++, constant-expression", "url": null }
algorithm, c, graph, pathfinding, dijkstra Title: Traditional vs. bidirectional Dijkstra's algorithm in C Question: I have this CLion project on GitHub. It constructs a directed, weighted graph consisting of 100 thousand nodes and 500 thousand directed arcs, picks two random nodes, and computes the shortest paths between the two using both versions of the Dijkstra's algorithm. Code algorithm.c: #include "algorithm.h" #include "dary_heap.h" #include "distance_map.h" #include "graph.h" #include "parent_map.h" #include "util.h" #include "vertex_list.h" #include "vertex_set.h" #include <float.h> #include <stdlib.h> #define TRY_REPORT_RETURN_STATUS(RETURN_STATUS) \ if (p_return_status) { \ *p_return_status = RETURN_STATUS; \ } #define CLEAN_SEARCH_STATE search_state_free(&search_state_) #define CLEAN_SEARCH_STATE_2 search_state_2_free(&search_state_2_) static const size_t INITIAL_MAP_CAPACITY = 1024; static const float LOAD_FACTOR = 1.3f; static const size_t DARY_HEAP_DEGREE = 4; typedef struct search_state { dary_heap* p_open_forward; dary_heap* p_open_backward; vertex_set* p_closed_forward; vertex_set* p_closed_backward; distance_map* p_distance_forward; distance_map* p_distance_backward; parent_map* p_parent_forward; parent_map* p_parent_backward; } search_state; static void search_state_init(search_state* p_state) { p_state->p_open_forward = dary_heap_alloc( DARY_HEAP_DEGREE, INITIAL_MAP_CAPACITY, LOAD_FACTOR); p_state->p_open_backward = dary_heap_alloc( DARY_HEAP_DEGREE, INITIAL_MAP_CAPACITY, LOAD_FACTOR); p_state->p_closed_forward = vertex_set_alloc( INITIAL_MAP_CAPACITY, LOAD_FACTOR);
{ "domain": "codereview.stackexchange", "id": 43163, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, graph, pathfinding, dijkstra", "url": null }
algorithm, c, graph, pathfinding, dijkstra p_state->p_closed_backward = vertex_set_alloc( INITIAL_MAP_CAPACITY, LOAD_FACTOR); p_state->p_distance_forward = distance_map_alloc( INITIAL_MAP_CAPACITY, LOAD_FACTOR); p_state->p_distance_backward = distance_map_alloc( INITIAL_MAP_CAPACITY, LOAD_FACTOR); p_state->p_parent_forward = parent_map_alloc( INITIAL_MAP_CAPACITY, LOAD_FACTOR); p_state->p_parent_backward = parent_map_alloc( INITIAL_MAP_CAPACITY, LOAD_FACTOR); } static int search_state_ok(search_state* p_search_state) { return p_search_state->p_open_forward && p_search_state->p_open_backward && p_search_state->p_closed_forward && p_search_state->p_closed_backward && p_search_state->p_distance_forward && p_search_state->p_distance_backward && p_search_state->p_parent_forward && p_search_state->p_parent_backward; } static void search_state_free(search_state* p_search_state) { if (p_search_state->p_open_forward) { dary_heap_free(p_search_state->p_open_forward); } if (p_search_state->p_open_backward) { dary_heap_free(p_search_state->p_open_backward); } if (p_search_state->p_closed_forward) { vertex_set_free(p_search_state->p_closed_forward); } if (p_search_state->p_closed_backward) { vertex_set_free(p_search_state->p_closed_backward); } if (p_search_state->p_distance_forward) { distance_map_free(p_search_state->p_distance_forward); } if (p_search_state->p_distance_backward) { distance_map_free(p_search_state->p_distance_backward); } if (p_search_state->p_parent_forward) { parent_map_free(p_search_state->p_parent_forward); }
{ "domain": "codereview.stackexchange", "id": 43163, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, graph, pathfinding, dijkstra", "url": null }
algorithm, c, graph, pathfinding, dijkstra if (p_search_state->p_parent_backward) { parent_map_free(p_search_state->p_parent_backward); } } typedef struct search_state_2 { dary_heap* p_open; vertex_set* p_closed; distance_map* p_distance; parent_map* p_parent; } search_state_2; static void search_state_2_init(search_state_2* p_state) { p_state->p_open = dary_heap_alloc( DARY_HEAP_DEGREE, INITIAL_MAP_CAPACITY, LOAD_FACTOR); p_state->p_closed = vertex_set_alloc( INITIAL_MAP_CAPACITY, LOAD_FACTOR); p_state->p_distance = distance_map_alloc( INITIAL_MAP_CAPACITY, LOAD_FACTOR); p_state->p_parent = parent_map_alloc( INITIAL_MAP_CAPACITY, LOAD_FACTOR); } static int search_state_2_ok(search_state_2* p_search_state) { return p_search_state->p_open && p_search_state->p_closed && p_search_state->p_distance && p_search_state->p_parent; } void search_state_2_free(search_state_2* p_search_state) { if (p_search_state->p_open) { dary_heap_free(p_search_state->p_open); } if (p_search_state->p_closed) { vertex_set_free(p_search_state->p_closed); } if (p_search_state->p_distance) { distance_map_free(p_search_state->p_distance); } if (p_search_state->p_parent) { parent_map_free(p_search_state->p_parent); } } /* Constructs a shortest path after bidirectional search: */ static vertex_list* traceback_path(size_t touch_vertex_id, parent_map * parent_forward, parent_map * parent_backward) {
{ "domain": "codereview.stackexchange", "id": 43163, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, graph, pathfinding, dijkstra", "url": null }
algorithm, c, graph, pathfinding, dijkstra vertex_list* path = vertex_list_alloc(100); int rs; /* result status */ size_t vertex_id = touch_vertex_id; size_t previous_vertex_id = parent_map_get(parent_forward, touch_vertex_id); do { rs = vertex_list_push_front(path, vertex_id); if (rs != RETURN_STATUS_OK) { vertex_list_free(path); return NULL; } previous_vertex_id = vertex_id; vertex_id = parent_map_get(parent_forward, vertex_id); } while (vertex_id != previous_vertex_id); vertex_id = parent_map_get(parent_backward, touch_vertex_id); previous_vertex_id = touch_vertex_id; while (vertex_id != previous_vertex_id) { rs = vertex_list_push_back(path, vertex_id); if (rs != RETURN_STATUS_OK) { vertex_list_free(path); return NULL; } previous_vertex_id = vertex_id; vertex_id = parent_map_get(parent_backward, vertex_id); } return path; } /* Runs the bidirectional Dijkstra's algorithm: */ vertex_list* find_shortest_path(Graph * p_graph, size_t source_vertex_id, size_t target_vertex_id, int* p_return_status) { search_state search_state_; double best_path_length = DBL_MAX; double temporary_path_length; double tentative_length; double weight; size_t* p_touch_vertex_id = NULL; int rs; /* return status */ int updated; size_t current_vertex_id; size_t child_vertex_id; size_t parent_vertex_id; GraphVertex* p_graph_vertex; vertex_list* p_path; dary_heap* p_open_forward; dary_heap* p_open_backward; vertex_set* p_closed_forward; vertex_set* p_closed_backward; distance_map* p_distance_forward; distance_map* p_distance_backward; parent_map* p_parent_forward; parent_map* p_parent_backward;
{ "domain": "codereview.stackexchange", "id": 43163, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, graph, pathfinding, dijkstra", "url": null }
algorithm, c, graph, pathfinding, dijkstra weight_map_iterator* p_weight_map_children_iterator; weight_map_iterator* p_weight_map_parents_iterator; /* Begin: routine checks. */ if (!p_graph) { TRY_REPORT_RETURN_STATUS(RETURN_STATUS_NO_GRAPH); return NULL; } rs = 0; if (!hasVertex(p_graph, source_vertex_id)) { rs |= RETURN_STATUS_NO_SOURCE_VERTEX; } if (!hasVertex(p_graph, target_vertex_id)) { rs |= RETURN_STATUS_NO_TARGET_VERTEX; } if (rs) { CLEAN_SEARCH_STATE; TRY_REPORT_RETURN_STATUS(rs); return NULL; } /* End: routine checks. */ /* Handle a case where the source and target vertices are the same. Otherwise, the algorithm may return a cycle containing the source/target vertex. */ if (source_vertex_id == target_vertex_id) { p_path = vertex_list_alloc(1); if (p_path) { TRY_REPORT_RETURN_STATUS(RETURN_STATUS_OK); } else { TRY_REPORT_RETURN_STATUS(RETURN_STATUS_NO_MEMORY); return NULL; } if ((rs = vertex_list_push_back(p_path, source_vertex_id)) != RETURN_STATUS_OK) { vertex_list_free(p_path); TRY_REPORT_RETURN_STATUS(rs); return NULL; } TRY_REPORT_RETURN_STATUS(RETURN_STATUS_OK); return p_path; } /* Begin: create data structures. */ search_state_init(&search_state_); if (!search_state_ok(&search_state_)) { CLEAN_SEARCH_STATE; TRY_REPORT_RETURN_STATUS(RETURN_STATUS_NO_MEMORY); return NULL; }
{ "domain": "codereview.stackexchange", "id": 43163, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, graph, pathfinding, dijkstra", "url": null }
algorithm, c, graph, pathfinding, dijkstra p_open_forward = search_state_.p_open_forward; p_open_backward = search_state_.p_open_backward; p_closed_forward = search_state_.p_closed_forward; p_closed_backward = search_state_.p_closed_backward; p_distance_forward = search_state_.p_distance_forward; p_distance_backward = search_state_.p_distance_backward; p_parent_forward = search_state_.p_parent_forward; p_parent_backward = search_state_.p_parent_backward; /* Begin: initialize the state: */ if (dary_heap_add(p_open_forward, source_vertex_id, 0.0) != RETURN_STATUS_OK) { CLEAN_SEARCH_STATE; TRY_REPORT_RETURN_STATUS(RETURN_STATUS_NO_MEMORY); return NULL; } if (dary_heap_add(p_open_backward, target_vertex_id, 0.0) != RETURN_STATUS_OK) { CLEAN_SEARCH_STATE; TRY_REPORT_RETURN_STATUS(RETURN_STATUS_NO_MEMORY); return NULL; } if (distance_map_put(p_distance_forward, source_vertex_id, 0.0) != RETURN_STATUS_OK) { CLEAN_SEARCH_STATE; TRY_REPORT_RETURN_STATUS(RETURN_STATUS_NO_MEMORY); return NULL; } if (distance_map_put(p_distance_backward, target_vertex_id, 0.0) != RETURN_STATUS_OK) { CLEAN_SEARCH_STATE; TRY_REPORT_RETURN_STATUS(RETURN_STATUS_NO_MEMORY); return NULL; } if (parent_map_put(p_parent_forward, source_vertex_id, source_vertex_id) != RETURN_STATUS_OK) { CLEAN_SEARCH_STATE; TRY_REPORT_RETURN_STATUS(RETURN_STATUS_NO_MEMORY); return NULL; } if (parent_map_put(p_parent_backward, target_vertex_id, target_vertex_id) != RETURN_STATUS_OK) {
{ "domain": "codereview.stackexchange", "id": 43163, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, graph, pathfinding, dijkstra", "url": null }
algorithm, c, graph, pathfinding, dijkstra CLEAN_SEARCH_STATE; TRY_REPORT_RETURN_STATUS(RETURN_STATUS_NO_MEMORY); return NULL; } /* End: initialize the state. */ /* Main loop: */ while (dary_heap_size(p_open_forward) > 0 && dary_heap_size(p_open_backward) > 0) { if (p_touch_vertex_id) { /* There is somewhere a vertex at which both the search frontiers are meeting: */ temporary_path_length = distance_map_get( p_distance_forward, dary_heap_min(p_open_forward)) + distance_map_get( p_distance_backward, dary_heap_min(p_open_backward)); if (temporary_path_length > best_path_length) { /* Once here, we have a shortest path passing through '*p_touch_vertex_id'. '*/ p_path = traceback_path(*p_touch_vertex_id, p_parent_forward, p_parent_backward); if (p_path) { TRY_REPORT_RETURN_STATUS(RETURN_STATUS_OK); } else { TRY_REPORT_RETURN_STATUS(RETURN_STATUS_NO_MEMORY); } /* Clean up and return the path. The path may be NULL, which implies that there were no sufficient memory available for the path. */ CLEAN_SEARCH_STATE; free(p_touch_vertex_id); return p_path; } }
{ "domain": "codereview.stackexchange", "id": 43163, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, graph, pathfinding, dijkstra", "url": null }
algorithm, c, graph, pathfinding, dijkstra /* Choose the expansion direction. The smaller of the two search frontiers will be selected: */ if (dary_heap_size(p_open_forward) + vertex_set_size(p_closed_forward) <= dary_heap_size(p_open_backward) + vertex_set_size(p_closed_backward)) { /* Once here, we expanding the forward search frontier generating the child vertices of the selected vertex: */ current_vertex_id = dary_heap_extract_min(p_open_forward); /* Mark that we know the shortest path to 'current_vertex_id': */ if ((rs = vertex_set_add(p_closed_forward, current_vertex_id)) != RETURN_STATUS_OK) { CLEAN_SEARCH_STATE; TRY_REPORT_RETURN_STATUS(rs); return NULL; } p_graph_vertex = graph_vertex_map_get(p_graph->p_nodes, current_vertex_id); p_weight_map_children_iterator = weight_map_iterator_alloc( p_graph_vertex->p_children); if (!p_weight_map_children_iterator) { CLEAN_SEARCH_STATE; TRY_REPORT_RETURN_STATUS(RETURN_STATUS_NO_MEMORY); if (p_touch_vertex_id) { free(p_touch_vertex_id); } return NULL; } /* Expand the 'current_vertex_id'. In other words, iterate over all child nodes of 'current_vertex_id': */ while (weight_map_iterator_has_next( p_weight_map_children_iterator)) { updated = 0; weight_map_iterator_visit(p_weight_map_children_iterator, &child_vertex_id, &weight); weight_map_iterator_next(p_weight_map_children_iterator);
{ "domain": "codereview.stackexchange", "id": 43163, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, graph, pathfinding, dijkstra", "url": null }
algorithm, c, graph, pathfinding, dijkstra weight_map_iterator_next(p_weight_map_children_iterator); if (vertex_set_contains(p_closed_forward, child_vertex_id)) { /* Once here, the shortest path to 'child_vertex_id' is already known. Omit it: */ continue; } tentative_length = distance_map_get(p_distance_forward, current_vertex_id) + weight; if (!distance_map_contains_vertex_id(p_distance_forward, child_vertex_id)) { /* Once here, we reached 'child_vertex_id' for the first time! */ /* Add to the forward priority queue: */ if ((rs = dary_heap_add( p_open_forward, child_vertex_id, tentative_length)) != RETURN_STATUS_OK) { CLEAN_SEARCH_STATE; TRY_REPORT_RETURN_STATUS(rs); if (p_touch_vertex_id) { free(p_touch_vertex_id); } return NULL; } /* Mark that the distance and the parent maps should be updated: */ updated = 1; } else if (distance_map_get(p_distance_forward, child_vertex_id) > tentative_length) { /* Once here, we are reaching the 'child_vertex_id' for not the first time, byt we can lower its shortest path estimate. For that reason, we lower that estimate: */ dary_heap_decrease_key( p_open_forward, child_vertex_id, tentative_length);
{ "domain": "codereview.stackexchange", "id": 43163, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, graph, pathfinding, dijkstra", "url": null }
algorithm, c, graph, pathfinding, dijkstra /* Mark that the distance and the parent maps should be updated: */ updated = 1; } if (updated) { /* Once here, we need to update the shortest path estimate and the parent of the 'child_vertex_id': */ if ((rs = distance_map_put( p_distance_forward, child_vertex_id, tentative_length)) != RETURN_STATUS_OK) { CLEAN_SEARCH_STATE; TRY_REPORT_RETURN_STATUS(rs); free(NULL); free(p_touch_vertex_id); return NULL; } if ((rs = parent_map_put( p_parent_forward, child_vertex_id, current_vertex_id)) != RETURN_STATUS_OK) { CLEAN_SEARCH_STATE; TRY_REPORT_RETURN_STATUS(rs); free(p_touch_vertex_id); return NULL; } /* Checks whether we can find the meeting vertex: */ if (vertex_set_contains(p_closed_backward, child_vertex_id)) { temporary_path_length = tentative_length + distance_map_get(p_distance_backward, child_vertex_id); /* Can we improve the cost of a shortest path via the meeting point? */ if (best_path_length > temporary_path_length) { best_path_length = temporary_path_length;
{ "domain": "codereview.stackexchange", "id": 43163, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, graph, pathfinding, dijkstra", "url": null }
algorithm, c, graph, pathfinding, dijkstra if (!p_touch_vertex_id) { p_touch_vertex_id = malloc(sizeof(size_t)); } *p_touch_vertex_id = child_vertex_id; } } } } } else { /* Once here, we expand the backward search frontier generating all the parents of the selected of the selected vertex: */ current_vertex_id = dary_heap_extract_min(p_open_backward); vertex_set_add(p_closed_backward, current_vertex_id); p_graph_vertex = graph_vertex_map_get(p_graph->p_nodes, current_vertex_id); p_weight_map_parents_iterator = weight_map_iterator_alloc( p_graph_vertex->p_parents); /* Expand the 'current_vertex_id' in backward direction generating its parents: */ while (weight_map_iterator_has_next( p_weight_map_parents_iterator)) { updated = 0; weight_map_iterator_visit( p_weight_map_parents_iterator, &parent_vertex_id, &weight); weight_map_iterator_next(p_weight_map_parents_iterator); if (vertex_set_contains(p_closed_backward, parent_vertex_id)) { /* Once here, the shortest distance to 'parent_vertex_id' is already known. Omit it!*/ continue; } tentative_length = distance_map_get(p_distance_backward, current_vertex_id) + weight;
{ "domain": "codereview.stackexchange", "id": 43163, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, graph, pathfinding, dijkstra", "url": null }
algorithm, c, graph, pathfinding, dijkstra if (!distance_map_contains_vertex_id(p_distance_backward, parent_vertex_id)) { /* Once here, 'parent_vertex_id' is reached for the first time. Add it to the backward search frontier: */ if ((rs = dary_heap_add( p_open_backward, parent_vertex_id, tentative_length)) != RETURN_STATUS_OK) { CLEAN_SEARCH_STATE; TRY_REPORT_RETURN_STATUS(rs); free(p_touch_vertex_id); return NULL; } updated = 1; } else if (distance_map_get(p_distance_backward, parent_vertex_id) > tentative_length) { /* Once here, we can improve the distance to 'parent_vertex_id: */ dary_heap_decrease_key( p_open_backward, parent_vertex_id, tentative_length); updated = 1; } if (updated) { /* Once here, we need to update the auxiliary info: */ if ((rs = distance_map_put( p_distance_backward, parent_vertex_id, tentative_length)) != RETURN_STATUS_OK) { CLEAN_SEARCH_STATE; TRY_REPORT_RETURN_STATUS(rs); free(p_touch_vertex_id); return NULL; }
{ "domain": "codereview.stackexchange", "id": 43163, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, graph, pathfinding, dijkstra", "url": null }
algorithm, c, graph, pathfinding, dijkstra if ((rs = parent_map_put( p_parent_backward, parent_vertex_id, current_vertex_id)) != RETURN_STATUS_OK) { CLEAN_SEARCH_STATE; TRY_REPORT_RETURN_STATUS(rs); free(p_touch_vertex_id); return NULL; } if (vertex_set_contains(p_closed_forward, parent_vertex_id)) { /* Once here, there is a meeting vertex: */ temporary_path_length = tentative_length + distance_map_get(p_distance_forward, parent_vertex_id); /* Possibly update the meeting vertex and the cost of the path passing through it: */ if (best_path_length > temporary_path_length) { best_path_length = temporary_path_length; if (!p_touch_vertex_id) { p_touch_vertex_id = malloc(sizeof(size_t)); } *p_touch_vertex_id = parent_vertex_id; } } } } } } if (p_touch_vertex_id) { free(p_touch_vertex_id); } /* Once here, there is no path from the source vertex to the target vertex: */ CLEAN_SEARCH_STATE; TRY_REPORT_RETURN_STATUS(RETURN_STATUS_NO_PATH); return NULL; } /* Constructs the shortest path after unidirectional search: */ static vertex_list* traceback_path_2(size_t target_vertex_id, parent_map* parent) {
{ "domain": "codereview.stackexchange", "id": 43163, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, graph, pathfinding, dijkstra", "url": null }
algorithm, c, graph, pathfinding, dijkstra vertex_list* path = vertex_list_alloc(100); int rs; /* result status */ size_t vertex_id = target_vertex_id; size_t previous_vertex_id = parent_map_get(parent, target_vertex_id); do { rs = vertex_list_push_front(path, vertex_id); if (rs != RETURN_STATUS_OK) { vertex_list_free(path); return NULL; } previous_vertex_id = vertex_id; vertex_id = parent_map_get(parent, vertex_id); } while (vertex_id != previous_vertex_id); return path; } /* Runs the traditional (unidirectional) Dijkstra's algorithm: */ vertex_list* find_shortest_path_2(Graph* p_graph, size_t source_vertex_id, size_t target_vertex_id, int* p_return_status) { search_state_2 search_state_2_; size_t current_vertex_id; size_t child_vertex_id; double weight; double tentative_length; GraphVertex* p_graph_vertex; int rs; /* return status */ int updated; vertex_list* p_path; dary_heap* p_open; vertex_set* p_closed; distance_map* p_distance; parent_map* p_parent; weight_map_iterator* p_weight_map_children_iterator; /* Begin: routing checks. */ if (!p_graph) { TRY_REPORT_RETURN_STATUS(RETURN_STATUS_NO_GRAPH); return NULL; } rs = 0; if (!hasVertex(p_graph, source_vertex_id)) { rs |= RETURN_STATUS_NO_SOURCE_VERTEX; } if (!hasVertex(p_graph, target_vertex_id)) { rs |= RETURN_STATUS_NO_TARGET_VERTEX; } if (rs) { CLEAN_SEARCH_STATE_2; TRY_REPORT_RETURN_STATUS(rs); return NULL; } /* End: routine checks. */ search_state_2_init(&search_state_2_); if (!search_state_2_ok(&search_state_2_)) { CLEAN_SEARCH_STATE_2; TRY_REPORT_RETURN_STATUS(RETURN_STATUS_NO_MEMORY); return NULL; }
{ "domain": "codereview.stackexchange", "id": 43163, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, graph, pathfinding, dijkstra", "url": null }
algorithm, c, graph, pathfinding, dijkstra p_open = search_state_2_.p_open; p_closed = search_state_2_.p_closed; p_distance = search_state_2_.p_distance; p_parent = search_state_2_.p_parent; /* Begin: initialize the state: */ if ((rs = dary_heap_add(p_open, source_vertex_id, 0.0)) != RETURN_STATUS_OK) { CLEAN_SEARCH_STATE_2; TRY_REPORT_RETURN_STATUS(rs); return NULL; } if ((rs = distance_map_put(p_distance, source_vertex_id, 0.0)) != RETURN_STATUS_OK) { CLEAN_SEARCH_STATE_2; TRY_REPORT_RETURN_STATUS(rs); return NULL; } if ((rs = parent_map_put(p_parent, source_vertex_id, source_vertex_id)) != RETURN_STATUS_OK) { CLEAN_SEARCH_STATE_2; TRY_REPORT_RETURN_STATUS(rs); return NULL; } /* End: intitialize the state. */ /* Main loop: */ while (dary_heap_size(p_open) > 0) { current_vertex_id = dary_heap_extract_min(p_open); if (current_vertex_id == target_vertex_id) { /* Once here, the search has reached the target vertex. */ p_path = traceback_path_2(target_vertex_id, p_parent); CLEAN_SEARCH_STATE_2; if (p_path) { TRY_REPORT_RETURN_STATUS(RETURN_STATUS_OK); } else { TRY_REPORT_RETURN_STATUS(RETURN_STATUS_NO_MEMORY); } return p_path; } if (vertex_set_contains(p_closed, current_vertex_id)) { /* Once here, the shortest path distance to 'current_vertex_id' is already known. Omit it.*/ continue; }
{ "domain": "codereview.stackexchange", "id": 43163, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, graph, pathfinding, dijkstra", "url": null }
algorithm, c, graph, pathfinding, dijkstra if ((rs = vertex_set_add(p_closed, current_vertex_id)) != RETURN_STATUS_OK) { /* Mark 'current_vertex_id' as settled. */ CLEAN_SEARCH_STATE_2; TRY_REPORT_RETURN_STATUS(rs); return NULL; } p_graph_vertex = graph_vertex_map_get(p_graph->p_nodes, current_vertex_id); p_weight_map_children_iterator = weight_map_iterator_alloc( p_graph_vertex->p_children); if (!p_weight_map_children_iterator) { CLEAN_SEARCH_STATE_2; TRY_REPORT_RETURN_STATUS(RETURN_STATUS_NO_MEMORY); return NULL; } /* Iterate over all child vertices of the 'current_vertex_id': */ while (weight_map_iterator_has_next( p_weight_map_children_iterator)) { updated = FALSE; weight_map_iterator_visit(p_weight_map_children_iterator, &child_vertex_id, &weight); weight_map_iterator_next(p_weight_map_children_iterator); if (vertex_set_contains(p_closed, child_vertex_id)) { /* The shortest path distance to 'child_vertex_id' is already known. Omit it. */ continue; } tentative_length = distance_map_get(p_distance, current_vertex_id) + weight; if (!distance_map_contains_vertex_id(p_distance, child_vertex_id)) { /* Once here, 'child_vertex_id' is reached for the first time. Add it to the search frontier: */ updated = TRUE;
{ "domain": "codereview.stackexchange", "id": 43163, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, graph, pathfinding, dijkstra", "url": null }
algorithm, c, graph, pathfinding, dijkstra if ((rs = dary_heap_add( p_open, child_vertex_id, tentative_length)) != RETURN_STATUS_OK) { CLEAN_SEARCH_STATE_2; TRY_REPORT_RETURN_STATUS(rs); return NULL; } } else if (distance_map_get(p_distance, child_vertex_id) > tentative_length) { /* Once here, we can improve the shortest path estimate to 'child_vertex_id': */ updated = TRUE; dary_heap_decrease_key( p_open, child_vertex_id, tentative_length); } if (updated) { /* Once here, we need to update the state for the 'child_vertex_id': */ if ((rs = distance_map_put( p_distance, child_vertex_id, tentative_length)) != RETURN_STATUS_OK) { CLEAN_SEARCH_STATE_2; TRY_REPORT_RETURN_STATUS(rs); return NULL; } if ((rs = parent_map_put( p_parent, child_vertex_id, current_vertex_id)) != RETURN_STATUS_OK) { CLEAN_SEARCH_STATE_2; TRY_REPORT_RETURN_STATUS(rs); return NULL; } } } } /* Once here, there is no path from the source vertex to the target vertex: */ CLEAN_SEARCH_STATE_2; TRY_REPORT_RETURN_STATUS(RETURN_STATUS_NO_PATH); return NULL; }
{ "domain": "codereview.stackexchange", "id": 43163, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, graph, pathfinding, dijkstra", "url": null }
algorithm, c, graph, pathfinding, dijkstra Critique request Please, tell me anything that comes to mind. Also, I ran my program against valgrind: no memory leaks detected, so I suggest you don't waste your time searching for any. Outro If you run the entire demo program, you will likely observe that the bidirectional algorithms is faster than the traditional one by two orders of magnitude. Typical output follows: Seed = 1648197281 Built the graph in 1768 milliseconds. Source node: 16222 Target node: 79241 --- Bidirectional Dijkstra: 16222 57355 99046 17632 57708 23745 62656 12104 15177 432 72091 67852 42272 67600 91412 43363 43827 56094 90931 79241 Path length: 28.349254 Duration: 4 milliseconds. Result status: 0 --- Original Dijkstra: 16222 57355 99046 17632 57708 23745 62656 12104 15177 432 72091 67852 42272 67600 91412 43363 43827 56094 90931 79241 Path length: 28.349254 Duration: 210 milliseconds. Result status: 0 Algorithms agree: 1 Exiting...
{ "domain": "codereview.stackexchange", "id": 43163, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, graph, pathfinding, dijkstra", "url": null }
algorithm, c, graph, pathfinding, dijkstra Answer: My main issue with this C89 rendition is readability. I revisited your 2016 Python rendition which reads inconspicuous. I think the problem here is the bulk, the verbosity. (The code layout being lavish with vertical space compounds to the issue.) Your library style ADT implementations have names that make collisions unlikely. I suggest to provide short names that allow for fluent reading - either optional generic ones in the ADT's header, or names tailored to the context (maybe both?) There is a striking amount of repetitive handling of cleanup and error returns. The bulk could be reduced by just "jamming" same statements controlled by successive conditions: if ((rs = dary_heap_add(p_open, source_vertex_id, 0.0)) != RETURN_STATUS_OK ||(rs = distance_map_put(p_distance, source_vertex_id, 0.0)) != RETURN_STATUS_OK ||(rs = parent_map_put(p_parent, source_vertex_id, source_vertex_id)) != RETURN_STATUS_OK) { CLEAN_SEARCH_STATE_2; TRY_REPORT_RETURN_STATUS(rs); return NULL; }
{ "domain": "codereview.stackexchange", "id": 43163, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, graph, pathfinding, dijkstra", "url": null }
algorithm, c, graph, pathfinding, dijkstra - I'd introduce a macro return_ERROR(status)   (Similar to search_state_ok() handling? Naa…) Rather than cleaning up at every error return (and conditionally exporting a status), you could create a wrapper run_shortest_path(graph, source, target, pstatus, find_path, state_size, init, cleanup): vertex_list * run_shortest_path(Graph const * const p_graph, vertex_id source, vertex_id target,  int* pstatus, vertex_list *(*find_path)(), size_t state_size, int (*init)(), /* boolean: successful - state, rather? */ void (*cleanup)()) /** Run find_path: allocate&initialise state, call find_path, clean up */ { vertex_list *path = NULL; int return_status = RETURN_STATUS_NO_MEMORY; /* ? allows just "return NULL" */ void *state = NULL; /* variable length arrays non-standard before C99 */ if (0 == state_size || NULL != (state = calloc(1, state_size))) { if (0 == state_size || NULL == init || init(state)) path = find_path(p_graph, source, target,  &return_status, &state); if (NULL != cleanup) cleanup(state); } if (NULL != pstatus) *pstatus = return_status; return path; }
{ "domain": "codereview.stackexchange", "id": 43163, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, graph, pathfinding, dijkstra", "url": null }
algorithm, c, graph, pathfinding, dijkstra (needs amends in find_path() (search_state_.…→state->…).) There is a troubling amount of duplication "between directions". Thinking of search_state as a search_state_2[2]: static void init(void* outer) { search_state_2 *state = (search_state_2 *)outer; return search_state_2_init(state) && search_state_2_init(state + 1); } /* Possible, but not advisable in find_shortest_path(): search_state_2 *state = (search_state_2 *)outer; p_open_forward = search_state->p_open; p_closed_forward = search_state->p_closed; p_distance_forward = search_state->p_distance; p_parent_forward = search_state->p_parent; state += 1; p_open_backward = search_state->p_open; p_closed_backward = search_state->p_closed; … */ The naming makes me wonder about the Java rendition I assume original - is that well-known/readily accessible? I might prefer waiting over open, finished over closed, (out/in)neighbours over parents/children. While I see one merit to it, I didn't expect choice of vertex to handle "by shorter frontier". I guess you can construct a graph to make any scheme look bad - How about, one from source, one from target, k from shorter? I don't buy the choice of data structures to map from ID to vertex and from vertex to neighbours: I'd expect the ID space to be densely populated from 0, and the number of neighbours to be smallish: arrays for both! (Rather than, seeing id in vertex, replacing ID with pointers on construction) I would have considered C89 an odd choice in 2016: What's the story behind Dijkstra for Perl 4?
{ "domain": "codereview.stackexchange", "id": 43163, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, graph, pathfinding, dijkstra", "url": null }
performance, c, parsing, io, integer Title: Quickly read numeric input Question: Do you have any criticisms or corrections or improvements? I need to read only numbers(and this numbers could be from 0 to 1000000) void fast_input(int* int_input) { *int_input=0; char next_char=0; while( next_char < '0' || next_char > '9' ){ // Skip non-digits next_char = getchar(); } while( next_char >= '0' && next_char <= '9' ) { (*int_input) = ((*int_input)<<1) + ((*int_input)<<3) + next_char - '0'; next_char = getchar(); } } Answer: Do you have any criticisms or corrections or improvements? Infinite loop On end-of-file, first while loops loops forever. Better code would prevent looping forever and return not void, but an indication of success. int vs. char getchar() returns an int and typically 257 different values. Saving in a char will lose information. Save in an int to properly distinguish EOF from other characters. Avoid trying to out-think the compiler A good compiler will emit optimal code. // (*int_input) = ((*int_input)<<1) + ((*int_input)<<3) + next_char - '0'; *int_input = *int_input * 10 + + next_char - '0';
{ "domain": "codereview.stackexchange", "id": 43164, "lm_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, parsing, io, integer", "url": null }
performance, c, parsing, io, integer Fast vs. I/O Input/Output is a sink-hole of time. Significant time improvement are made there, not in trying to using < instead of *. On return, restore last character read To better work with other routines, it is more common to ungetc() the last non-digit read. No overflow protection Signed int overflow is undefined behavior (UB). Yes, OP has "need to read only numbers(and this numbers could be from 0 to 1000000)", but that limitation is not commented in the code. So the next person lifts this code and runs into UB. Comment important restrictions in code. Even better, detect potential overflow int ch = getchar(); if (*int_input >= INT_MAX/10 && (*int_input > INT_MAX/10 || ch - '0' > INT_MAX%10)) { // Overflow! *int_input = INT_MAX; } else { *int_input = *int_input * 10 + + next_char - '0'; } Consider a local variable int sum = 0; ... most of code *int_input = sum; Minor: 2 compares vs. isdigit() Consider isdigit() rather than 2 compares. Poor formatting Alternative Untested - but at least gives OP an idea of the above feedback. #include <ctype.h> #include <limits.h> // Return EOF on end-of-file or input error without reading an int. // Return 0 on overflow. Value is capped. // Return 1 on success. // Save value read if int_input is not NULL int fast_input_alt(int *int_input) { int sum = 0; int ch; // Skip non-digits while ((ch = getchar()) != EOF && !isdigit(ch)) { ; } if (ch == EOF) { return EOF; } int retval = 1; do { ch -= '0'; if (sum >= INT_MAX / 10 && (sum > INT_MAX / 10 || ch > INT_MAX % 10)) { sum = INT_MAX; retval = 0; // Overflow } else { sum = sum * 10 + ch; } ch = getchar(); } while (isdigit(ch)); ungetc(ch, stdin); if (int_input) { *int_input = sum; } return retval; }
{ "domain": "codereview.stackexchange", "id": 43164, "lm_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, parsing, io, integer", "url": null }
vba, benchmarking Title: VBA Code Profiling Question: I have wanted a way to do code profiling in VBA for quite some time. It becomes very complicated to figure out what methods are actually being executed for how long and how often in complex Access applications. A key reason this is complicated is that many form events or function calculations happen very often and not only as the result of code. Form events fire based on other form events or user input, etc. This is a basic class I am calling Profiler: Option Compare Database Option Explicit Private initTime As Double Private mProfiledMethod As String Public Property Let ProfiledMethod(pValue As String) mProfiledMethod = pValue End Property Private Sub Class_Initialize() initTime = GetTickCount End Sub Private Sub Class_Terminate() GetProfileManager.addMethodCall mProfiledMethod, GetTickCount() - initTime End Sub Here is what I am calling a ProfileManager class: Option Compare Database Option Explicit Private m_MethodTotalTimes As Scripting.Dictionary Private m_MethodTotalCalls As Scripting.Dictionary Public Sub addMethodCall(p_method As String, p_time As Double) If m_MethodTotalTimes.exists(p_method) Then m_MethodTotalTimes(p_method) = m_MethodTotalTimes(p_method) + p_time m_MethodTotalCalls(p_method) = m_MethodTotalCalls(p_method) + 1 Else m_MethodTotalTimes.Add p_method, p_time m_MethodTotalCalls.Add p_method, 1 End If End Sub Public Sub PrintTimes() Dim mKey For Each mKey In m_MethodTotalTimes.Keys Debug.Print mKey & " was called " & m_MethodTotalCalls(mKey) & " times for a total time of " & m_MethodTotalTimes(mKey) Next mKey End Sub Private Sub Class_Initialize() Set m_MethodTotalTimes = New Scripting.Dictionary Set m_MethodTotalCalls = New Scripting.Dictionary End Sub
{ "domain": "codereview.stackexchange", "id": 43165, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "vba, benchmarking", "url": null }
vba, benchmarking Here is my main module example. I have several nested methods. Public Declare Function GetTickCount Lib "kernel32.dll" () As Long Private mProfileManager As profileManager Public Function GetProfileManager() As profileManager If mProfileManager Is Nothing Then Set mProfileManager = New profileManager End If Set GetProfileManager = mProfileManager End Function Public Sub resetProfileManager() Set mProfileManager = Nothing End Sub Sub mainProfilerTest() 'reinit profile manager resetProfileManager 'run some time/tests test1 'print results GetProfileManager.PrintTimes End Sub Sub test1() Dim mProfiler As New Profiler mProfiler.ProfiledMethod = "test1" Dim i As Long For i = 0 To 100 test2 Next i End Sub Sub test2() Dim mProfiler As New Profiler mProfiler.ProfiledMethod = "test2" test3 test4 End Sub Sub test3() Dim mProfiler As New Profiler mProfiler.ProfiledMethod = "test3" Dim i As Long, j As Long For i = 0 To 1000000 j = 1 + 5 Next i End Sub Sub test4() Dim mProfiler As New Profiler mProfiler.ProfiledMethod = "test4" Dim i As Long, j As Long For i = 0 To 500000 j = 1 + 5 Next i End Sub This works alright. I will have to add the two lines of code to create/init each Profiler at the beginning of any method I want to profile, which is not ideal but not terribly awful. On my machine the raw output is: test3 was called 101 times for a total time of 640 test4 was called 101 times for a total time of 390 test2 was called 101 times for a total time of 1030 test1 was called 1 times for a total time of 1030 For actual runtime, I am intending on wrapping a ProfileManager over a simple sub which triggers form events. For example I might make a simple sub to Open a form, but do something like: resetProfileManager DoCmd.OpenForm "Form Name" GetProfileManager.PrintTimes
{ "domain": "codereview.stackexchange", "id": 43165, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "vba, benchmarking", "url": null }
vba, benchmarking DoCmd.OpenForm "Form Name" GetProfileManager.PrintTimes Which will print out all the profiled methods for all the tracked methods. Alternatively, I can reset the profile manager in the background and mimic user behavior and retrieve the profile at any time in the intermediate window with: ?GetProfileManager.PrintTimes I am basically looking for feedback on how to make this better. It is pretty rough currently because I don't want to go through all the methods I'd want to profile and start adding this code without having more eyes on this.
{ "domain": "codereview.stackexchange", "id": 43165, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "vba, benchmarking", "url": null }
vba, benchmarking Answer: This is pretty good and optimal already. Just a few hints here and there I would take the Private Declare Function GetTickCount Lib "kernel32.dll" () As Long and throw that into the Profiler class due to the class being the only one needing it. Trust me it's easy to forget to declare that on a new project in standard module and annoy the sh** out of yourself. You seem inconsistent about naming your members. Some subs are camelCase, others are PascalCase. Decide which one you're going to use and apply throughout the code. Generally, your project encapsulation is very loose. I mean, everything depends on everything if that makes any sense; (see interesting post here) I would think that ProfileManager should include members like Reset and GetProfileManager. BUT since your Profiler needs to access the manager in its Class_Terminate() event and you can't pass parameters nor can you raise an event to notify the manager that the object is about to get destroyed there isn't any other way to achieve this as far as I know due to your current design... I played with the code for about 2 hours but my conclusion is based on an assumption that you want to minimize it down to just creating an instance of Profiler and calling one Let property without having to explicitly destroy the instance (2 lines of code currently) ie. relying on the Class_Terminate event - you've already got the best approach and there is not much room for further optimizations. I am still not quite sure what the purpose of your ResetProfileManager() sub is so currently I find it a bit redundant since you could just do this once: Private manager As ProfileManager Sub MainProfilerTest() Set manager = New ProfileManager ...
{ "domain": "codereview.stackexchange", "id": 43165, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "vba, benchmarking", "url": null }
vba, benchmarking Set manager = New ProfileManager ... Oh btw. I would have changed the mProfileManager to just manager.. makes things simpler. And further to the above if you explicitly assign a new ProfilerManager to your manager you could improve the performance a bit by modifying the GetProfileManager by removing unnecessary check: Public Function GetProfileManager() As ProfileManager Set GetProfileManager = manager End Function Also, in ProfileManager consider using simpler names like: Private times As Dictionary Private calls As Dictionary And in the Profiler: Private initTime As Double Private method As String I would also add the Class_Terminate event to the ProfileManger and free refs to the Dictionaries Private Sub Class_Terminate() Set times = Nothing Set calls = Nothing End Sub I think it's matter of preference but generally I don't prefix Dictionary with Scripting. Any decent person who's even a bit familiar with VBA will know that Dictionary is Scripting.Dictionary. I also considered shortening the declaration to one line using imitation of a static class in combination with parametarised constructors but I've seen your chat message from last night saying that you wouldn't want to do that. I guess that's about all I can say about your code. Like I said if you didn't mind to explicitly destroy your Profile instances that would completely change the story :)
{ "domain": "codereview.stackexchange", "id": 43165, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "vba, benchmarking", "url": null }
vba, excel, benchmarking Title: VBA code for testing efficency Question: I am currently trying out code for timing efficiency (how fast it runs, basically). The general consensus is that code with ActiveCell,.Select,Selection and so forth are basicly rejected for being slow and buggy, whereas code that uses variables and not ActiveCell,.Select,Selection are considered quicker and less buggy The two codes I have made do the same thing, which is to enter a number 40000+1 every consecutive cell (so Cell A1 is 40000 then A2 is 40001 and so forth) and then converts those numbers into dates. One does this with ActiveCell, Selection and Select, while the other does it with varibles,Long and Range. I also did both with and then without Application.ScreenUpdating = False to see how that worked as well. The code ActiveCell etc. ran at 13494,26567,26489,14040,26598(without Application.ScreenUpdating = False) and 1154,1123,1123,1107,1170 (with Application.ScreenUpdating = False) "Milliseconds" The code without ActiveCell ran at 905,905,905,671,687 (without Application.ScreenUpdating = False) and ran at 577,609,577,577,562 (with Application.ScreenUpdating = False) "Milliseconds" The milliseconds is in "Milliseconds" as the Private Declare Function GetTickCount Lib "kernel32.dll" () As Long I have been lead to believe isnt very accurate, I use it because the accurate ones are addins for excel and I unable to download or install anything on this PC, but gvies a decent idea of the speed the code runs at The code that the efficency tests is the For i = 1 To 1000 loop Code with ActiveCells: Private Declare Function GetTickCount Lib "kernel32.dll" () As Long Sub UsingVaribles() Dim NumberToday As Long Dim StartTimer As Long Dim rngCells As Range Dim rng As Range Application.ScreenUpdating = False [A1].Select NumberToday = 40000 StartTimer = GetTickCount k = 1 For q = 1 To 26
{ "domain": "codereview.stackexchange", "id": 43166, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "vba, excel, benchmarking", "url": null }
vba, excel, benchmarking [A1].Select NumberToday = 40000 StartTimer = GetTickCount k = 1 For q = 1 To 26 For i = 1 To 1000 NumberToday = NumberToday + 1 Set rngCells = Cells(i, k) rngCells.Value = NumberToday Next i Range(rngCells, Cells(1, k)).NumberFormat = "m/d/yyyy" ' 1 bug out k = k + 1 Next q MsgBox (GetTickCount - StartTimer & " Milliseconds") End Sub Code without ActiveCells: Sub UsingActivecell() Application.ScreenUpdating = False [A1].Select NumberToday = 40000 Dim StartTimer As Long StartTimer = GetTickCount For q = 1 To 26 For i = 1 To 1000 NumberToday = NumberToday + 1 ActiveCell.Value = NumberToday ActiveCell.Offset(1, 0).Select Next i ActiveCell.Offset(-1, 0).Select Range(Selection, Selection.End(xlUp)).Select ' 3 issues with bug out, due to my incompitence Selection.NumberFormat = "m/d/yyyy" ActiveCell.Offset(0, 1).Select ActiveCell.End(xlUp).Select Next q MsgBox (GetTickCount - StartTimer & " Milliseconds") End Sub Answer: I know this isn't what you're asking, but what's up with your variables? You should always turn on Option Explicit which will catch things like k, q and i not being dimensioned. When you don't define your variable, VBA defines it as a variant. I'm pretty sure variants are objects: Performance. A variable you declare with the Object type is flexible enough to contain a reference to any object. However, when you invoke a method or property on such a variable, you always incur late binding (at run time). To force early binding (at compile time) and better performance, declare the variable with a specific class name, or cast it to the specific data type. So you pay a penalty when you don't dimension your variables. I imagine defining your variables might shave some milliseconds off over the long run. For variables I'm getting 570ish For selection I'm getting 950ish For i=1 to 10000
{ "domain": "codereview.stackexchange", "id": 43166, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "vba, excel, benchmarking", "url": null }
vba, excel, benchmarking For variables I'm getting 570ish For selection I'm getting 950ish For i=1 to 10000 using your variables is giving me about 5200 while using option explicit I'm getting around 5100. For i=1 to 50000 option explicit is 24165 your variables is 24476 Option Explicit has the gainz. And now, my version (why are you [A1].Selecting?) for i=1 to 50000 comes in at 23182. That right there should show you the .select statement was slowing it down. Option Explicit Private Declare Function GetTickCount Lib "kernel32.dll" () As Long Sub UsingVaribles() Application.ScreenUpdating = False Dim NumberToday As Long NumberToday = 40000 Dim StartTimer As Long StartTimer = GetTickCount Dim rngCells As Range Dim rng As Range Dim k As Long k = 1 Dim i As Long Dim q As Long For q = 1 To 26 For i = 1 To 50000 NumberToday = NumberToday + 1 Set rngCells = Cells(i, k) rngCells = NumberToday Next i Range(rngCells, Cells(1, k)).NumberFormat = "m/d/yyyy" ' 1 bug out k = k + 1 Next q MsgBox (GetTickCount - StartTimer & " Milliseconds") Application.ScreenUpdating = True End Sub
{ "domain": "codereview.stackexchange", "id": 43166, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "vba, excel, benchmarking", "url": null }
javascript, performance, tic-tac-toe Title: Avoiding nested loops in a TicTacToe algorithm JavaScript Question: I wrote a quick algorithm that detects a win in a TicTacToe Game. fn game() loops through a simulated ticTacToe board, finds all the index's of a given value, then loops through all the possible winning combos, finds any index's where the actual value is equal to the index's from the first loop, (I know :/) then replaces the value with the value passed into the function (either x or o). Then, a subsequent function is run that checks if every value inside any of the nested arrays inside the possibleWinCombos are all equal to each other. If true, a winner is found. const possibleWinCombos = [ [0, 1, 2], //================ // [3, 4, 5], //== Horizontal == // [6, 7, 8], //=================// [0, 3, 6], //================ // [1, 4, 7], //== Vertical == // [2, 5, 8], //=================// [0, 4, 8], //=================// [2, 4, 6], //== Diagonal == // ] const ticTacToe = [ 'x', 'o', null, null, 'x', null, 'o', null, 'x', ] const game = (value) => { ticTacToe.forEach((cell, idxOfCell) => { if(cell === value){ for (winCombo of possibleWinCombos){ let idxToReplace = winCombo.indexOf(idxOfCell) winCombo.splice(idxToReplace, 1, value) } } }) checkForWinner(value) ? console.log(`${value}'s win`) : console.log('game still going') } const checkForWinner = (value) => { return possibleWinCombos.some((winCombo) => { return winCombo.every((winComboValue) => winComboValue === value); }) } game('x') // x's win game('o') // game still going It's only two functions so it's not very code heavy but I feel like game() wouldn't score very high on the performance rankings due to the nested looping. Any recommendations on some improvements would be great. https://replit.com/@uwitdat/DrabNoteworthyLogin#script.js
{ "domain": "codereview.stackexchange", "id": 43167, "lm_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, performance, tic-tac-toe", "url": null }
javascript, performance, tic-tac-toe Answer: You should either end your statements with semicolons consistently, or not at all. I recommend using semicolons consistently. When writing for (winCombo of possibleWinCombos), you didn't declare winCombo, so it's a global variable. The biggest problem with your code is that it trashes the contents of possibleWinCombos, such that after execution, it has this value: possibleWinCombos = [ ["x", "o", "o"], [ 3, "x", "o"], ["o", 7, "o"], ["x", 3, "o"], ["o", "x", "o"], [ 2, 5, "o"], ["x", "x", "o"], [ 2, "x", "o"] ] … even though it was ostensibly const. That means that if you ever run a rematch, your code won't work correctly unless you reinitialize possibleWinCombos. If you're writing code in a functional style, you should aim for your functions to have no side-effects. You don't really have to worry about performance or scalability, since the board will always be no bigger than 3×3. That said, you should be aware that your algorithm calls .indexOf(), which involves a hidden loop to scan its array. I recommend writing an isWinner(board, player) function. The two parameters make it clear what the inputs are. The name of the function makes it clear that it returns a boolean. By defining it using an IIFE, we can make it so that possibleWinCombos is available only to the code within isWinner(), which avoids polluting the global namespace. const isWinner = (() => { const possibleWinCombos = [ [0, 1, 2], //================// [3, 4, 5], //== Horizontal ==// [6, 7, 8], //================// [0, 3, 6], //================// [1, 4, 7], //=== Vertical ===// [2, 5, 8], //================// [0, 4, 8], //================// [2, 4, 6], //=== Diagonal ===// ]; return (board, player) => { return possibleWinCombos.some((winCombo) => { return winCombo.every((i) => board[i] === player); }); }; })(); const ticTacToe = [ 'x', 'o', null, null, 'x', null, 'o', null, 'x', ];
{ "domain": "codereview.stackexchange", "id": 43167, "lm_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, performance, tic-tac-toe", "url": null }
javascript, performance, tic-tac-toe const ticTacToe = [ 'x', 'o', null, null, 'x', null, 'o', null, 'x', ]; if (isWinner(ticTacToe, 'x')) console.log('x won'); if (isWinner(ticTacToe, 'o')) console.log('o won');
{ "domain": "codereview.stackexchange", "id": 43167, "lm_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, performance, tic-tac-toe", "url": null }
java Title: Bi directional full relation between classes + small working tasks Question: I did this the way I could (I mean this way I find it okay for my knowledge and of course the most important output is the correct one , but as I know it is also important that the code looks clean and minimal). I have to figure out some tasks that you will see in the output, apart one where I have to implement bi directional full relation between these two objects. (Mother may have many children; a child has exactly one mother). (Apparently the one thing that give me headache since I took 2 days to figure out how to implement the relation between). I want to see if I can improve the code Can it be minimized? Is the approach correct? Is it the fastest way? I will appreciate any of your suggestions. Class Person: package victor; public abstract class Person { private String name; private int id; public Person(String name, int id) { this.name = name; this.id = id; } public int getId() { return id; } public String getName() { return name; } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } } Class Mother: package victor; import java.util.ArrayList; import java.util.List; public class Mother extends Person { private int age; private final List<Newborn> list; public Mother(String name, int id, int age) { super(name, id); this.age = age; this.list = new ArrayList<>(); } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public List<Newborn> getList() { return list; } @Override public String toString() { return getId() + " " + getName() + " " + age; } } Class Newborn: package victor; import java.time.LocalDate; import java.time.format.DateTimeFormatter;
{ "domain": "codereview.stackexchange", "id": 43168, "lm_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", "url": null }
java import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class Newborn extends Person { private boolean gender; private LocalDate birthday; private int weight; private int height; private int motherID; private Mother mother; public Newborn(String name, int id, boolean gender , String birthday, int weight, int height , int motherID) { super(name, id); this.gender = gender; parseBirthday(birthday); this.weight = weight; this.height = height; this.motherID = motherID; } public boolean getGender() { return this.gender; } public void setGender(boolean gender) { this.gender = gender; } public LocalDate getBirthday() { return birthday; } public int getHeight() { return height; } public Mother getMother() { return mother; } public int getMotherID() { return motherID; } public int getWeight() { return weight; } public void setBirthday(LocalDate birthday) { this.birthday = birthday; } public void setMother(Mother mother) { this.mother = mother; } public void setHeight(int height) { this.height = height; } public void setMotherID(int motherID) { this.motherID = motherID; } public void setWeight(int weight) { this.weight = weight; } public void parseBirthday(String format) { DateTimeFormatter sdf = DateTimeFormatter.ISO_DATE; this.birthday = LocalDate.parse(format, sdf); } @Override public String toString() { return getId() + " " + (gender ? "s " : "c ") + getName() + " " + birthday.format(DateTimeFormatter.ISO_DATE) + " " + weight + " " + height + " " + motherID; } } Class App + Main(code): package victor;
{ "domain": "codereview.stackexchange", "id": 43168, "lm_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", "url": null }
java Class App + Main(code): package victor; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.time.LocalDate; import java.util.*; import java.util.Map.Entry; public class App { private List<Mother> mothers = new ArrayList<>(); private List<Newborn> newborns = new ArrayList<>(); public void importMothers(String filename) { File file = new File(filename); try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { String[] arr = line.split("\\s+"); mothers.add(new Mother(arr[1], Integer.parseInt(arr[0]) , Integer.parseInt(arr[2]))); } } catch (IOException e) { System.err.println(e.getMessage()); System.exit(1); } } public void importNewborns(String filename) { File file = new File(filename); try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { String[] arr = line.split("\\s+"); newborns.add(new Newborn(arr[2], Integer.parseInt(arr[0]) , arr[1].equals("c") ? false : true , arr[3], Integer.parseInt(arr[4]) , Integer.parseInt(arr[5]) , Integer.parseInt(arr[6]))); } } catch (IOException e) { System.err.println(e.getMessage()); System.exit(1); } } public void buildRelation(String momsFilename, String newbornsFilename) { importMothers(momsFilename); importNewborns(newbornsFilename); for (Newborn newborn : newborns) { findMother(newborn); } }
{ "domain": "codereview.stackexchange", "id": 43168, "lm_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", "url": null }
java public void findMother(Newborn newborn) { for (Mother mother : mothers) { if (newborn.getMotherID() == mother.getId()) { mother.getList() .add(newborn); newborn.setMother(mother); break; } } } public Newborn getTallestNewborn(boolean son) { Newborn tallest = null; int height = 0; for (Newborn newborn : newborns) { if (newborn.getHeight() > height && newborn.getGender() == son) { tallest = newborn; height = newborn.getHeight(); } } return tallest; } public LocalDate mostCommonDate() { Map<LocalDate, Integer> map = new HashMap<>(); for (Newborn newborn : newborns) { Integer value = map.get(newborn.getBirthday()); map.put(newborn.getBirthday(), (value == null) ? 1 : value + 1); } Entry<LocalDate, Integer> max = null; for (Entry<LocalDate, Integer> entry : map.entrySet()) { if (max == null || max.getValue() > entry.getValue()) { max = entry; } } assert max != null; return max.getKey(); } public List<Mother> motherMoreThan() { List<Mother> list = new ArrayList<>(); for (Mother mother : mothers) { if (mother.getAge() > 25 && isChildOver4000(mother)) { list.add(mother); } } return list; } public boolean isChildOver4000(Mother mother) { for (Newborn newborn : mother.getList()) { if (newborn.getWeight() > 4000) { return true; } } return false; } public List<Newborn> newbornWithMotherName() { List<Newborn> list = new ArrayList<>();
{ "domain": "codereview.stackexchange", "id": 43168, "lm_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", "url": null }
java public List<Newborn> newbornWithMotherName() { List<Newborn> list = new ArrayList<>(); for (Newborn newborn : newborns) { if (!newborn.getGender()) if (newborn.getMother() .getName() .equals(newborn.getName())) list.add(newborn); } return list; } public List<Mother> mothersWithTwins() { List<Mother> list = new ArrayList<>(); for (Mother mother : mothers) { if (motherHasTwins(mother)) { list.add(mother); } } return list; } public boolean motherHasTwins(Mother mother) { Set<LocalDate> set = new TreeSet<>(); for (Newborn newborn : mother.getList()) { set.add(newborn.getBirthday()); } return set.size() < mother.getList() .size(); } public static void main(String[] args) { App app = new App(); app.buildRelation("src\\motherFile.txt", "src\\\\NewbornFile.txt"); System.out.println("Tallest daughter:"); System.out.println(app.getTallestNewborn(false)); System.out.println("\nTallest son:"); System.out.println(app.getTallestNewborn(true)); System.out.println("\nMost common date:"); System.out.println(app.mostCommonDate()); System.out.println("\nMothers over 25 Years old with childer heavier than 4000g;"); app.motherMoreThan() .forEach(System.out::println); System.out.println("\nDaughters that inherits their mother's name: "); app.newbornWithMotherName() .forEach(System.out::println); System.out.println("\nMother that has twins:"); app.mothersWithTwins() .forEach(System.out::println); } } Answer: Is it the fastest way?
{ "domain": "codereview.stackexchange", "id": 43168, "lm_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", "url": null }
java } } Answer: Is it the fastest way? Probably not, though there's a lot to work on before performance considerations necessarily factor in. Can it be minimized? Yes! Is the approach correct?
{ "domain": "codereview.stackexchange", "id": 43168, "lm_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", "url": null }
java Effectively impossible to say unless you give more information as to why you're doing the things you're doing. If this is for a real-life, production database of hospital patients, a flat text file is not a good idea (for instance). Many more of your fields should be final than you currently have; immutability bestows a number of benefits. As other reviewers have mentioned, circular dependencies complicate this, and if they're avoided then your classes can be made fully immutable. Don't blindly add getters and setters for their own sake. Consider using a String.format call in your toString implementations. gender being a boolean is effectively wrong. First of all, you've given it a name that leaves the programmer guessing as to which boolean value evaluates to which gender (seems like male is true based on inference); so a better variable name would be male or isMale. Just as important, though: intersex babies are real and any effort to cast them to a boolean doesn't at all fit reality. Depending on how medically detailed you need your database to be, either an enum or a simple string value will fit better. Adding to this: what on earth are "c" and "s"? parseBirthday should be made a static returning a LocalDate, and should not set the birthday member. Your import functions should either be static pseudoconstructor methods on their respective models, or perhaps dedicated parser classes; but should not exist in App. buildRelation prevents the App instance from being immutable, so move its contents to a constructor. findMother is inefficient. Rather than looping, you should use a hash map lookup. Basically all of your analysis methods could be improved by use of streams. motherHasTwins is inefficient since it unconditionally iterates the entire collection of newborns. Instead, as soon as you find a duplicate you should break the loop. Including the word "file" in your filename is redundant.
{ "domain": "codereview.stackexchange", "id": 43168, "lm_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", "url": null }
java Including the word "file" in your filename is redundant. Don't hard-code \n as that's a system-specific newline; prefer %n in printf-like calls or use println. Some of your fields - height, weight and age - are mysteries. Weight appears to be in grams and age in years, but you don't mention this anywhere. One way to have the code self-document this is to bake the unit into the variable name, as in weightGrams. Also, all three of these quantities are continuous in real life, so should be represented as floats and not ints. Consider using a streamed implementation for producing parsed records from your files. Suggested Covering some of the above: App.java package victor;
{ "domain": "codereview.stackexchange", "id": 43168, "lm_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", "url": null }
java import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Path; import java.time.LocalDate; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; public class App { private final Map<Integer, Mother> mothers; private final List<Newborn> newborns; public App(Path momsPath, Path newbornsPath) throws IOException { newborns = Newborn.importFromFile(newbornsPath) .collect(Collectors.toList()); Map<Integer, List<Newborn>> newbornsByMother = Newborn.newbornsByMother(newborns); mothers = Mother.importFromFile(momsPath, newbornsByMother) .collect(Collectors.toMap( m -> m.id, Function.identity() )); } public Newborn getTallestNewborn(boolean male) { return newborns.stream() .filter(n -> n.male == male) .max(Comparator.comparing(n -> n.height)) .get(); } public LocalDate mostCommonBirthday() { return newborns.stream() .map(n -> n.birthday) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet() .stream() .max(Map.Entry.comparingByValue()) .get() .getKey(); } public Stream<Mother> motherMoreThan() { return mothers.values().stream() .filter( m -> m.age > 25 && m.anyChildHeavierThan(4000) ); } public Stream<Newborn> daughtersWithMothersName() { return newborns.stream() .filter( n -> !n.male && n.name.equals(mothers.get(n.motherID).name) ); } public Stream<Mother> mothersWithTwins() { return mothers.values().stream() .filter(Mother::hasTwins); }
{ "domain": "codereview.stackexchange", "id": 43168, "lm_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", "url": null }
java public void describe(PrintWriter out) { out.printf( "Tallest daughter:" + "%n%s" + "%n" + "%nTallest son:" + "%n%s" + "%n" + "%nMost common birthday:" + "%n%s" + "%n" + "%n", getTallestNewborn(false), getTallestNewborn(true), mostCommonBirthday() ); out.println("Mothers over 25 Years old with children heavier than 4 kg:"); motherMoreThan() .forEach(out::println); out.printf("%nDaughters that inherits their mother's name:%n"); daughtersWithMothersName() .forEach(out::println); out.printf("%nMother that has twins:%n"); mothersWithTwins() .forEach(out::println); } public static void main(String[] args) throws IOException { App app = new App(Path.of("mothers.txt"), Path.of("newborns.txt")); try (PrintWriter out = new PrintWriter(System.out)) { app.describe(out); } } } Mother.java package victor; import org.jetbrains.annotations.NotNull; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDate; import java.util.*; import java.util.stream.Stream; public class Mother extends Person { public final float age; private final List<Newborn> children; public Mother(String name, int id, float age, List<Newborn> children) { super(name, id); this.age = age; this.children = children; } public List<Newborn> getChildren() { return Collections.unmodifiableList(children); } @Override public String toString() { return String.format("%d %s %.1f", id, name, age); }
{ "domain": "codereview.stackexchange", "id": 43168, "lm_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", "url": null }
java public static Mother fromString(String line, Map<Integer, List<Newborn>> newbornsByMother) { String[] arr = line.split("\\s+"); int id = Integer.parseInt(arr[0]); String name = arr[1]; float age = Float.parseFloat(arr[2]); return new Mother(name, id, age, newbornsByMother.get(id)); } public static Stream<Mother> importFromFile( @NotNull Path path, Map<Integer, List<Newborn>> newbornsByMother ) throws IOException { return Files.lines(path) .map(line -> fromString(line, newbornsByMother)); } public boolean anyChildHeavierThan(float weight) { return children.stream() .anyMatch(n -> n.weight > weight); } public boolean hasTwins() { Set<LocalDate> birthdays = new HashSet<>(); return !children.stream() .map(n -> n.birthday) .allMatch(birthdays::add); } } Newborn.java package victor; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class Newborn extends Person { private static final DateTimeFormatter birthdayFormat = DateTimeFormatter.ISO_DATE; public final boolean male; public final LocalDate birthday; public final float weight; public final float height; public final int motherID; public Newborn( String name, int id, boolean male, LocalDate birthday, float weight, float height, int motherID ) { super(name, id); this.male = male; this.birthday = birthday; this.weight = weight; this.height = height; this.motherID = motherID; } private static LocalDate parseBirthday(String date) { return LocalDate.parse(date, birthdayFormat); }
{ "domain": "codereview.stackexchange", "id": 43168, "lm_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", "url": null }
java @Override public String toString() { return String.format( "%d %c %s %s %.1f %.1f %d", id, male ? 's' : 'c', name, birthday.format(birthdayFormat), weight, height, motherID ); } public static Newborn fromString(String line) { String[] arr = line.split("\\s+"); int id = Integer.parseInt(arr[0]); boolean male = !"c".equals(arr[1]); String name = arr[2]; LocalDate birthday = parseBirthday(arr[3]); float weight = Float.parseFloat(arr[4]); float height = Float.parseFloat(arr[5]); int motherID = Integer.parseInt(arr[6]); return new Newborn(name, id, male, birthday, weight, height, motherID); } public static Stream<Newborn> importFromFile(@NotNull Path path) throws IOException { return Files.lines(path) .map(Newborn::fromString); } public static Map<Integer, List<Newborn>> newbornsByMother(Collection<Newborn> newborns) { return newborns.stream() .collect(Collectors.groupingBy(n -> n.motherID)); } } Person.java package victor; public abstract class Person { public final String name; public final int id; public Person(String name, int id) { this.name = name; this.id = id; } }
{ "domain": "codereview.stackexchange", "id": 43168, "lm_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", "url": null }
python, performance, python-3.x, programming-challenge Title: Drug Analyzer challenge Question: What do I need help with? I'm doing the challenge below, in which I need to increase code performance. It's currently at 63% and I need to increase it to at least 71% however I can't optimize more than the current one. How can it be optimized? Introduction You are a member of a biotechnology programming team that is responsible for creating a system for lab technicians, which will assist them with drug analysis. Your goal is to create the application that will let them input their findings into the system, provide a meaningful analysis and verify the correctness of the data that they have sent. Prerequisites To complete this task, use Python 3. Task Details Note: Please do NOT modify any tests unless specifically told to do so. Part 1 Your goal in this part is to implement the app.drug_analyzer.DrugAnalyzer class. It will be responsible for analyzing data like the data presented below: pill_id pill_weight active_substance impurities L01-10 1007.67 102.88 1.00100 L01-06 996.42 99.68 2.00087 G02-03 1111.95 125.04 3.00004 G03-06 989.01 119.00 4.00062 The initialization of the class can be done from Python's list of lists (or nothing) and stored in the instance variable called data as per example below: >> my_drug_data = [ ... ['L01-10', 1007.67, 102.88, 1.00100], ... ['L01-06', 996.42, 99.68, 2.00087], ... ['G02-03', 1111.95, 125.04, 3.00100], ... ['G03-06', 989.01, 119.00, 4.00004] ... ] >>> my_analyzer = DrugAnalyzer(my_drug_data) >>> my_analyzer.data [['L01-10', 1007.67, 102.88, 0.001], ... ['L01-06', 996.42, 99.68, 0.00087], ... ['G02-03', 1111.95, 125.04, 0.00100], ... ['G03-06', 989.01, 119.00, 0.00004]] >>> DrugAnalyzer().data []
{ "domain": "codereview.stackexchange", "id": 43169, "lm_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", "url": null }
python, performance, python-3.x, programming-challenge The class should also have an option to add single lists into the object. Adding a list to the DrugAnalyzer object should return a new instance of this object with an additional element. Adding improper type or a list with improper length should raise a ValueError. An example of a correct and wrong addition output is shown below: >>> my_new_analyzer = my_analyzer + ['G03-01', 789.01, 129.00, 0.00008] >>> my_new_analyzer.data [['L01-10', 1007.67, 102.88, 0.001], ... ['L01-06', 996.42, 99.68, 0.00087], ... ['G02-03', 1111.95, 125.04, 0.00100], ... ['G03-06', 989.01, 119.00, 0.00004], ... ['G03-01', 789.01, 129.00, 0.00008]] >>> my_new_analyzer = my_analyzer + ['G03-01', 129.00, 0.00008] Traceback (the most recent call is displayed as the last one):   File "<stdin>", line 1, in <module> ValueError: Improper length of the added list. Part 2 Implement the verify_series method inside the app.drug_analyzer.DrugAnalyzer class. The goal of this method is to receive a list of parameters and use them to verify if the pills described inside the instance variable data matches the given criteria. It should return a Boolean value as a result. The function would be called as follows: verify_series(series_id = 'L01', act_subst_wgt = 100, act_subst_rate = 0.05, allowed_imp = 0.001) Where: the series_id is a 3 characters long string that is present at the beginning of every pill_id, before the - sign, for example, L01 is the series_id in pill_id = L01-12. the act_subst_wgt is the expected weight (mg) of the active substance content in the given series in one pill. the act_subst_rate is the allowed rate of difference in the active substance weight from the expected one. For example, for 100 mg, the accepted values would be between 95 and 105. the allowed_imp is the allowed rate of impure substances in the pill_weight. For example, for 1000 mg pill_weight and 0.001 rate, the allowed amount of impurities is 1 mg.
{ "domain": "codereview.stackexchange", "id": 43169, "lm_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", "url": null }
python, performance, python-3.x, programming-challenge The function should take all pills that are part of the L01 series, sum their weight and calculate if the amount of active_substance, as well as impurities, match the given rates. It should return True if both conditions are met and False if any of them is not met. The False result should mean that all the passed parameters are proper, but either the active_substance amount or the impurities amount is improper. In case of a series_id that is not present in the data at all or in case of any improper parameter, the function should throw a ValueError. Please think what could be the possible edge case in such a scenario. Example: >>> my_drug_data = [ ... ['L01-10', 1000.02, 102.88, 1.00100], ... ['L01-06', 999.90, 96.00, 2.00087], ... ['G02-03', 1000, 96.50, 3.00100], ... ['G03-06', 989.01, 119.00, 4.00004] ... ] >>> my_analyzer = DrugAnalyzer(my_drug_data) >>> my_analyzer.verify_series(series_id = 'L01', act_subst_wgt = 100, act_subst_rate = 0.05, allowed_imp = 0.001) False >>> // The overall active_substances weight would be 198.88, which is within the given rate of 0.05 for 200 mg (2 * act_subst_wgt). >>> // However, the sum of impurities would be 3.00187, which is more than 0.001*1999.92 (allowed_imp_rate * (1000.02 + 999.90). >>> my_analyzer.verify_series(series_id = 'L01', act_subst_wgt = 100, act_subst_rate = 0.05, allowed_imp = 0.0001) True >>> my_analyzer.verify_series(series_id = 'B03', act_subst_wgt = 100, act_subst_rate = 0.05, allowed_imp = 0.001) Traceback (the most recent call is displayed as the last one):   File "<stdin>", line 1, in <module> ValueError: B03 series is not present within the dataset. My Code: class DrugAnalyzer: def __init__(self, data=[]): self.data = data def __add__(self, other): if len(self.data[0]) != len(other): raise ValueError('Improper length of the added list.')
{ "domain": "codereview.stackexchange", "id": 43169, "lm_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", "url": null }
python, performance, python-3.x, programming-challenge if type(other[0]) is not str or type(other[1]) is not float or type(other[2]) is not float or type(other[3]) is not float: raise ValueError('Wrong type.') total_data = self.data total_data.append(other) return DrugAnalyzer(total_data) def verify_series( self, series_id: str, act_subst_wgt: float, act_subst_rate: float, allowed_imp: float, ) -> bool: lists = list(filter(lambda k: series_id in k[0], self.data)) pills_weight = sum([liste[1] for liste in lists]) actives_substances = sum([liste[2] for liste in lists]) impurities = sum([liste[3] for liste in lists]) if (len(lists) * act_subst_wgt * (1 + act_subst_rate)) > actives_substances > (len(lists) * act_subst_wgt * (1 - act_subst_rate)): if impurities < (allowed_imp * pills_weight): return True return False Answer: __init__ has a mutable default argument. The default argument is not reset between calls to a function, so multiple analyzers that start out empty will have the same list, which could be a problem if one of them changes: >>> a1 = DrugAnalyzer() >>> a1.data.append(['G03-01', 789.01, 129.00, 0.00008]) >>> a2 = DrugAnalyzer() >>> a2.data [['G03-01', 789.01, 129.0, 8e-05]] One option to avoid that could be explicitly copying the argument's content to a new list, perhaps like def __init__(self, drug_data=None): self.data = [] if drug_data: self.data[:] = drug_data It feels weird that __add__ verifies the shape of its input, but __init__ doesn't. Especially since the pre-existing data is used to decide whether a list is valid to add with __add__ - what if someone did DrugAnalyzer([[]])? Then you could only add 0-length lists to that analyzer, and a 0-length list will never pass the type check!
{ "domain": "codereview.stackexchange", "id": 43169, "lm_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", "url": null }
python, performance, python-3.x, programming-challenge By the way, the reason I used a1.data.append instead of += earlier? __add__ does not work on empty DrugAnalyzers - it tries to get self.data[0], which won't work if self.data is empty __add__ modifies self.data. Try: >>> a1 = DrugAnalyzer([['G03-01', 789.01, 129.00, 0.00008]]) >>> a2 = a1 + ['G02-03', 1111.95, 125.04, 3.00100] >>> a1.data [['G03-01', 789.01, 129.0, 8e-05], ['G02-03', 1111.95, 125.04, 3.001]] This is because both the old and new analyzer share the same list. You probably want to explicitly create a new list instead - total_data = self.data + [other] could be one way to do that The if in verify_series is annoyingly long. I would consider at least calculating len(lists) * act_subst_weight) in advance and going if target_weight * (1 + act_subst_rate) > active_substances > (1 - act_subst_rate). Or perhaps something like actual_rate = actives_substances / act_subst_weight followed by if (1 + act_subst_rate) > actual_rate > (1 - act_subst_rate) verify_series does not throw a ValueError for non-existing pill series' as the requirements demand, but instead returns False verify_series may mis-identify pills as belonging to the wrong pill series - if I understand the requirements correctly, G03-06 should only belong to the G03 series, not G0, 06 or 3-0, but this implementation will count it as being part of all those. Something like series_id == k[0].split('-')[0] or k[0].startswith(series_id + "-") might be more robust
{ "domain": "codereview.stackexchange", "id": 43169, "lm_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", "url": null }
sql, postgresql Title: PostgreSQL query which return metrics joining different tables
{ "domain": "codereview.stackexchange", "id": 43170, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "sql, postgresql", "url": null }
sql, postgresql Question: I have a query that can be seen on this fiddle and I'm relatively new to PSQL, having a few months of experience. DB Fiddle As mentioned in the comment I should put the query here and the code is perfectly working. The reason for this question is to find an improvement on it. The link to the third party is to show the result of it otherwise would be difficult to visualize it here. WITH statuses_flow AS ( SELECT c.id, c.study_id, c.site_id, s.type AS status_type, s.timestamp AS status_from, sa.type, row_number() OVER (ORDER BY s.candidate_id, s.timestamp) AS row_no FROM public.candidates c JOIN public.statuses s ON s.candidate_id = c.id JOIN public.statuses sa ON sa.candidate_id = c.id AND sa.id in( SELECT max(id) FROM public.statuses GROUP BY candidate_id) WHERE c.study_id in('INIT1') AND c.site_id in('Test1') AND sa.type != 'ANONYMISED' ORDER BY row_no ASC ) SELECT statuses_flow.id, statuses_flow.study_id AS "studyId", statuses_flow.site_id AS "siteId", statuses_flow.status_type AS "statusType", statuses_flow.status_from AS "statusFrom", next_status.status_from AS "statusTo", CASE WHEN next_status.status_from IS NULL THEN NULL ELSE ( SELECT created_at AS first_contact FROM public.activities WHERE candidate_id = statuses_flow.id AND TYPE in('PHONE', 'SMS', 'EMAIL') AND created_at BETWEEN statuses_flow.status_from AND next_status.status_from ORDER BY created_at FETCH FIRST 1 ROWS ONLY) END AS "first_contact" FROM statuses_flow LEFT JOIN statuses_flow next_status ON statuses_flow.id = next_status.id AND statuses_flow.row_no + 1 = next_status.row_no WHERE
{ "domain": "codereview.stackexchange", "id": 43170, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "sql, postgresql", "url": null }
sql, postgresql AND statuses_flow.row_no + 1 = next_status.row_no WHERE statuses_flow.status_type in('PENDING_SITE', 'PENDING_CALLCENTER', 'INCOMPLETE', 'REJECTED_CALLCENTER', 'REJECTED_SITE', 'CONSENTED') ORDER BY statuses_flow.id, statuses_flow.status_from
{ "domain": "codereview.stackexchange", "id": 43170, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "sql, postgresql", "url": null }
sql, postgresql This query collects and returns some metrics joining 3 tables about candidates being in a specific status during a medical study process. The query in the real life is very slow and needs some adjustments to be written better. The indexes are already applied on the original DB but still would be useful to find a better way. The section of the query which I'm not convinced at this point is lines 29 to 42 from the DB fiddle link above. I was wondering if by any chance could be changed to use a left join or another method to make a better performance. It is returning per every candidate something as for example for one candidate the table below id studyId siteId statusType statusFrom statusTo first_contact 1 Study1 Site1 INCOMPLETE 2021-07-20 09:30:52.101055+00 2021-07-20 09:31:53.568346+00 NULL 1 Study1 Site1 PENDING_CALLCENTER 2021-07-20 09:31:53.568346+00 2021-07-20 09:35:34.171876+00 2021-07-20 09:31:55.849+00 1 Study1 Site1 PENDING_SITE 2021-07-20 09:35:34.171876+00 2021-07-20 09:52:42.185163+00 2021-07-20 09:35:56.642+00 1 Study1 Site1 REJECTED_SITE 2021-07-20 09:53:08.874271+00 NULL NULL To explain, the same candidate, in a range of time can be in different statuses and for example, Candidate 1 (for simplicity C1) in the table above, was in 4 statuses. C1 stayed in incomplete status from/to and on this status period was not contacted so that why we have null on last column first_contact. C1 was contacted in the next 2 statuses and we determine the first_contact checking from the activities table the minimum activity timestamps of the types PHONE, EMAIL, and SMS in the range of time C1 was in that specific status from/to. The first_contact is the first time a candidate was contacted by EMAIL PHONE or SMS. On the last status, we have statusTo = null so also firstContact is null. The result I'm getting now is correct but seems not efficient to me and probably can get better but have no confidence in the way to manage the change in this situation.
{ "domain": "codereview.stackexchange", "id": 43170, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "sql, postgresql", "url": null }
sql, postgresql Answer: Thing number 1 is to convert your CTE to a subquery, since until recently, CTEs impose an optimisation fence. I'm unclear on whether this will affect the version of PostgreSQL that you use. Converting to a subquery will require that you repeat it, which has advantages and disadvantages: obviously the code will be longer, but you can tailor each of the copies so that it only selects columns that you care about. In the case of next_status this will only be these: c.id, s.type AS status_type, s.timestamp AS status_from, row_number() OVER (ORDER BY s.candidate_id, s.timestamp) AS row_no Don't in against a tuple of one item, as here: c.study_id in('INIT1') AND c.site_id in('Test1') Instead just =. Your dual row_number() with join is likely to be a source of slowness. Instead consider using the PostgreSQL lead/lag support in windowing functions. You would set up a window grouping values of candidates.id; within each group next_status is the row lead()ing the current row.
{ "domain": "codereview.stackexchange", "id": 43170, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "sql, postgresql", "url": null }
java, beginner, random Title: Truth or dare program in java Question: I wrote this code in Java as a "Truth or Dare" game where if you type "truth" or "dare", it will pick a random number from the switch and then output the truth question or dare. The code works great but what I am looking for is critique. I'm self taught and pretty new at coding so do you have any suggestions on cleaning up the code or how to layout the structure of the code? Was there anything that I did that could have been done in a much simpler way? And overall, how does it look for a newbie? Anything helps and will be much appreciated! Thank you! Hopefully I put the code below correctly. import java.util.*;
{ "domain": "codereview.stackexchange", "id": 43171, "lm_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, random", "url": null }
java, beginner, random public class Main { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); System.out.println("TRUTH OR DARE?"); System.out.println(); System.out.println("Type type truth or dare!"); System.out.println(); int truth = 1 + (int)(Math.random() * ((18 - 1) + 1)); // Random number from 1-18 int dare = 18 + (int)(Math.random() * ((36 - 18) + 1)); // Random number from 19-36 String truthOrDare = myObj.nextLine(); System.out.println(); if (truthOrDare.equals("truth") || truthOrDare.equals("Truth") || truthOrDare.equals("T") || truthOrDare.equals("true") || truthOrDare.equals("t")) { System.out.println(truth); } else { System.out.println(dare); } System.out.println(); // TRUTH Cases ****************************************************************** switch (truth) { case 1: System.out.println("When was the last time that you lied?"); break; case 2: System.out.println("Have you ever pooped yourself?"); break; case 3: System.out.println("What's your biggest fantasy?"); break; case 4: System.out.println("What is a secret your parents don't know?"); break; case 5: System.out.println("Who is your celebrity crush?"); break; case 6: System.out.println("What is the most trouble you have been in?"); break; case 7: System.out.println("Do you have a hidden talent?"); break; case 8: System.out.println("What is the last lie that you told?"); break; case 9: System.out.println("What was your most physically painful experience?"); break; case 10: System.out.println("If you met a genie, what would your three wishes be?"); break; case 11: System.out.println("Who was your worst kiss ever?"); break; case 12:
{ "domain": "codereview.stackexchange", "id": 43171, "lm_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, random", "url": null }
java, beginner, random break; case 11: System.out.println("Who was your worst kiss ever?"); break; case 12: System.out.println("Who are you most jealous of?"); break; case 13: System.out.println("Boxers or Briefs?"); break; case 14: System.out.println("How do you really feel about the Twilight Saga?"); break; case 15: System.out.println("Have you ever peed in a pool?"); break; case 16: System.out.println("If you were guaranteed to never get caught, who would you murder?"); break; case 17: System.out.println("Who is your hallpass?"); break; case 18: System.out.println("Who would you hate to see naked?"); break; // DARE Cases ******************************************************************** case 19: System.out.println("Show the most embarrassing photo on your phone!"); break; case 20: System.out.println("Eat a raw piece of garlic!"); break; case 21: System.out.println("Put 10 different available liquids into a cup and drink it!"); break; case 22: System.out.println("Eat a Spoonful of mustard!"); break; case 23: System.out.println("Show off your orgasm face!"); break; case 24: System.out.println("Do your best sexy crawl!"); break; case 25: System.out.println("Pole dance on an imaginary or real pole (if present)!"); break; case 26: System.out.println("Drink Lemon juice!"); break; case 27: System.out.println("Eat a packet of hot sauce or ketchup!"); break; case 28: System.out.println("Lick a bar of soap!"); break; case 29: System.out.println("Crack an egg on your head!"); break; case 30: System.out.println("Poor ice down your pants!"); break; case 31: System.out.println("Spin around 12 times and try to walk straight!"); break; case 32: System.out.println("Eat a raw egg!"); break; case 33:
{ "domain": "codereview.stackexchange", "id": 43171, "lm_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, random", "url": null }