text
stringlengths
1
2.12k
source
dict
python, programming-challenge, string-processing for idx, value in enumerate(input_values): # A more Pythonic range check: if source_range_start <= value <= source_range_end: new_values[idx] += adjustment return new_values def parse_maps(seeds: list[int], lines: Iterable[str]) -> list[int]: input_values = seeds for line in lines: if any( line.startswith(x) for x in [ "seed", "soil", "fertilizer", "water", "light", "temperature", "humidity", ] ): input_values = map_values(input_values, lines) return input_values ... Further Simplification If we assume that the input is correct, then we know we have a seeds specification followed by one or more maps separated by an empty line. We don't really care what the names of these maps are. Therefore functions parse_maps and map_values can be combined into a single function, map_seeds, which is appropriately named now because it is only invoked once with a list of seeds to be mapped to locations. Note that I have rewritten parse_seeds and lowest_location to now consistently use the expression next(lines) to fetch the next line. Note that in your code you have specified lines to be of type Iterable[str] but you then proceed to call method lines.readline() but readline is not a method of an iterable type (by using next(lines) instead, we can have lines be, for example, a list of strings). ...
{ "domain": "codereview.stackexchange", "id": 45328, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing def map_seeds(seeds: list[int], lines: Iterable[str]) -> list[int]: input_values = seeds try: while True: next(lines) # Get next map if any # Any more lines in the current map? new_values = input_values.copy() while (line := next(lines).strip()): # Empty line? # Modified variable names to match problem description names: destination_range_start, source_range_start, range_length = map(int, line.split()) # Calculate these values once: source_range_end = source_range_start + range_length - 1 adjustment = destination_range_start - source_range_start for idx, value in enumerate(input_values): # A more Pythonic range check: if source_range_start <= value <= source_range_end: new_values[idx] += adjustment input_values = new_values except StopIteration: # No more lines in the input return new_values def parse_seeds(lines: Iterable[str]) -> list[int]: line = next(lines) next(lines) # Read in following blank line return list(map(int, line.split(': ')[1].split())) def lowest_location(lines: Iterable[str]) -> int: return min(map_seeds(parse_seeds(lines), lines)) ...
{ "domain": "codereview.stackexchange", "id": 45328, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
typescript Title: Parsing fetched data in TypeScript Question: I use this code to populate a DB with a batch of pokemon entries from the POKEAPI. Since I'm using TypeScript, I added some custom parsing to use the data's type in the code. I've used a mix of A instanceof Object and 'field' in A, but what would be a better way? On top of this, I'm converting data to the Result<T> type. This is just to avoid using null or undefined for data that couldn't be parsed. Other question: at the bottom I put await prisma.pokemon.createMany({ data: allPokemon }) (with await) because the createMany didn't go through without await. Did this happen because the DB would disconnect too early or something? // =================== // RESULT // =================== type Result<T> = Ok<T> | Error type Ok<T> = { type: 'ok', data: T } type Error = { type: 'error', error: string } const ok = <T>(data: T): Ok<T> => ({ type: 'ok', data }) const error = (error: string): Error => ({ type: 'error', error }) const isOk = <T>(res: Result<T>): res is Ok<T> => res.type === 'ok' /** * Returns data if `res` is Ok, or `def` otherwise * * @returns T */ const orDefault = <T>(res: Result<T>, def: T) => res.type === 'ok' ? res.data : def /** * Collects data from any Ok value in an array of Results. * Also acts as a filter for Error values. * * @returns {T[]} */ const collectData = <T>(resAr: Result<T>[]) => resAr.filter(isOk).map(cur => cur.data) // =================== // POKEMON PARSING // =================== type Pokemon = { id: number, name: string } type PokemonBatch = { count: number results: { name: string }[] } const isPokemonName = (input: unknown): input is Pokemon => input instanceof Object && 'name' in input && typeof input.name === 'string' const parsePokemonName = (input: unknown): Result<{ name: string }> => isPokemonName(input) ? ok(input) : error('Failed to parse pokemon name')
{ "domain": "codereview.stackexchange", "id": 45329, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "typescript", "url": null }
typescript const isPokemonBatchLike = (input: unknown): input is PokemonBatch => input instanceof Object && 'count' in input && typeof input.count === 'number' && 'results' in input && Array.isArray(input.results) const parsePokemonBatch = (input: unknown): Result<PokemonBatch> => { if (isPokemonBatchLike(input)) { // filter out fields we couldn't parse const results = collectData(input.results.map(parsePokemonName)) return ok({ count: input.count, results: results }) } return error('Failed to parse pokemon batch.') } const getPokemonCount = () => fetch(`https://pokeapi.co/api/v2/pokemon`) .then(res => res.json()) .then(data => orDefault(parsePokemonBatch(data), { count: 0, results: [] }).count) const getAllPokemon = async (): Promise<Pokemon[]> => { const count = await getPokemonCount() const pokemon = await fetch(`https://pokeapi.co/api/v2/pokemon?limit=${count}`) .then(res => res.json()) .then(data => parsePokemonBatch(data)) if (pokemon.type === 'ok') // using index for id field, for now doesn't matter if the order is correct return pokemon.data.results.map(({ name }, i) => ({ id: i, name })) else return [] } // =================== // PRISMA // =================== const prisma = new PrismaClient() async function main() { const count = await prisma.pokemon.count() // populate DB if first time / empty if (count === 0) { const allPokemon = await getAllPokemon() await prisma.pokemon.createMany({ data: allPokemon }) } } main() .then(async () => { await prisma.$disconnect() }) .catch(async (e) => { console.error(e) await prisma.$disconnect() process.exit(1) }) ```
{ "domain": "codereview.stackexchange", "id": 45329, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "typescript", "url": null }
typescript Answer: All in all, it was fairly easy to read and understand the code. Some minor improvements suggested below Can't speak to the prisma usage, as I'm not familiar with it. However, it looks like you are correct that the function without await would immediately return and run the disconnect code. I'm a bit surprised this didn't cause an error though The same endpoint is called twice, first to get the count, then to use that count as limit. Since you intend to get everything in one go anyway, you can just use a really high value for limit instead. If the API has a max value for the limit, you could use the "next" token returned in the response to iterate over the results The code abstracts over the API with names like 'getPokemonCount' and 'getAllPokemon', and it does some specific processing for the application. This path leads you to repeat the code for each endpoint for any concern you have in your application. Already you are parsing the same type of response in two places in your code. I suggest creating a really thin layer over the API instead. E.g. just 'getPokemons' (or whatever the API endpoint is called), and add support for passing the various query parameters and whatnot supported in that function. This way you make the API client a single concern in your code. Using the name 'Error' as a type is a bit annoying since it clashes with the global Error object. Maybe use 'Failure' instead? 'isPokemonName' is not the best name. The input is not a pokemon name, it's an object that contains a pokemon name. In addition, the guard clause sets the type to "Pokemon". A better name would be 'isPokemon', or 'isPokemonLike' to adhere to the standard set by 'isPokemonBatchLike'
{ "domain": "codereview.stackexchange", "id": 45329, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "typescript", "url": null }
typescript I think you can reduce the amount of code by a lot if you use nulls instead of ok/error. 'orDefault' would be replaced by ??. collectData would be replaced by a simple filter. The reason why I think this is that you don't handle the errors anyway other than defaulting to empty values, so there's nothing to gain. About parsing json into types: If you want to do this the safest possible way, I recommend looking into something like typebox + ajv, where you can define your json schema and types in one go, and parse them with proper error messages and the whole shebang. If you trust the API, this may be a bit overkill, and you could just cast the response type instead. If it's important to always clean something up after a promise is done (like disconnecting in both the then and catch block), you can use 'finally'. Probably not a big deal here though.
{ "domain": "codereview.stackexchange", "id": 45329, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "typescript", "url": null }
object-oriented, design-patterns, typescript, classes Title: Random generation of points for the graphs of 3 stock share parameters Question: I currently studying OOP and related design patterns, and tried to implement random data generation for some stock charts using OOP as an exercise. This code randomly generates data points for 3 parameters (share price, spread and yield), so it later can be used as an input for the graphs. I want to receive some feedback on how to make this code more SOLID and in accordance with OOP best practices in general. Have I used the proper design patterns? import { faker } from "@faker-js/faker"; import { addDays, eachDayOfInterval, subMonths, isAfter, subWeeks, subYears, startOfWeek, startOfMonth, startOfQuarter, startOfYear, } from "date-fns"; const MIN_YEARS = 1.5; const MAX_YEARS = 6; // Oriented on SP500 shares to get the hardcoded numbers in USD const MIN_SHARE_PRICE = 300; const MAX_SHARE_PRICE = 5000; // Googled that 4 is maximum number of decimal places for share prices const SHARE_PRICE_FIXED_PRECISION = 6; // Yield and spread are in percents const MIN_YIELD = 0.1; const MAX_YIELD = 0.5; const YIELD_PRECISION = 0.0001; const MIN_SPREAD = 0.12; const MAX_SPREAD = 0.2; const SPREAD_PRECISION = 0.0001; const CHANGE_FACTOR = 0.03; type TimeIntervaleOption = "week" | "month" | "quarter" | "year" | "max"; type ShareParameter = { yield: number; spread: number; price: number; }; class DataPoint { id: string; date: Date; parameters: ShareParameter; constructor(id: string, date: Date, parameters: ShareParameter) { this.id = id; this.date = date; this.parameters = parameters; } } class Share { public readonly name: string; public readonly ISIN: string; private _dataPoints: DataPoint[]; get dataPoints() { return this._dataPoints; }
{ "domain": "codereview.stackexchange", "id": 45330, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, design-patterns, typescript, classes", "url": null }
object-oriented, design-patterns, typescript, classes get dataPoints() { return this._dataPoints; } constructor(name: string, ISIN: string, dataPoints: DataPoint[]) { this.name = name; this.ISIN = ISIN; this._dataPoints = dataPoints; } } class ShareFactory { private static _nextIdNumber = 0; private static get nextIdNumber() { return ShareFactory._nextIdNumber++; } static createShare(name: string, ISIN: string): Share { const dataPoints = ShareFactory.generateDataPoints(ISIN); return new Share(name, ISIN, dataPoints); } static generateDataPoints(ISIN: string): DataPoint[] { // how many years the stock exists const years = faker.number.float({ min: MIN_YEARS, max: MAX_YEARS }); // let's niglect leap years difference for simplicity const startDate = addDays(new Date(), -years * 365); const endDate = new Date(); let previousDataPointPrice = parseFloat( faker.finance.amount(MIN_SHARE_PRICE, MAX_SHARE_PRICE, SHARE_PRICE_FIXED_PRECISION) ); let previousDataPointYield = faker.number.float({ min: MIN_YIELD, max: MAX_YIELD, precision: YIELD_PRECISION, }); let previousDataPointSpread = faker.number.float({ min: MIN_SPREAD, max: MAX_SPREAD, precision: SPREAD_PRECISION, }); const days = eachDayOfInterval({ start: startDate, end: endDate }); const dataPoints = days.map((date: Date) => { const changeFactor = faker.number.float({ min: 1 - CHANGE_FACTOR, max: 1 + CHANGE_FACTOR, }); const newPrice = parseFloat( (previousDataPointPrice * changeFactor).toFixed(SHARE_PRICE_FIXED_PRECISION) ); const newYield = previousDataPointYield * changeFactor; const newSpread = previousDataPointSpread * changeFactor;
{ "domain": "codereview.stackexchange", "id": 45330, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, design-patterns, typescript, classes", "url": null }
object-oriented, design-patterns, typescript, classes previousDataPointPrice = newPrice; previousDataPointYield = newYield; previousDataPointSpread = newSpread; return new DataPoint(ISIN + ShareFactory.nextIdNumber, date, { yield: newYield, spread: newSpread, price: newPrice, }); }); return dataPoints; } } class ShareFilterService { static filterDataPointsByTime(share: Share, timeInterval?: TimeIntervaleOption): DataPoint[] { const now = new Date(); let startDate: Date; switch (timeInterval) { case "week": startDate = startOfWeek(subWeeks(now, 1)); break; case "month": startDate = startOfMonth(subMonths(now, 1)); break; case "quarter": startDate = startOfQuarter(subMonths(now, 3)); break; case "year": startDate = startOfYear(subYears(now, 1)); break; default: // corresponds to 'max' startDate = new Date( Math.min(...share.dataPoints.map((dataPoint) => dataPoint.date.getTime())) ); } return share.dataPoints.filter((dataPoint) => isAfter(dataPoint.date, startDate)); } } class ShareRepository { private readonly _sharePool: Map<string, Share> = new Map(); constructor(private shareFactory: typeof ShareFactory) {} getShareByISIN(ISIN: string): Share | null { return this._sharePool.get(ISIN) || null; }
{ "domain": "codereview.stackexchange", "id": 45330, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, design-patterns, typescript, classes", "url": null }
object-oriented, design-patterns, typescript, classes createShare(name?: string, ISIN?: string): void { if (ISIN && !this._sharePool.has(ISIN)) { const actualName = name || faker.company.name(); const actualISIN = ISIN || faker.string.alpha({ length: 2 }).toUpperCase() + faker.string.alphanumeric(10).toUpperCase() + faker.number.int(1); const share = this.shareFactory.createShare(actualName, actualISIN); this._sharePool.set(share.ISIN, share); } else { throw new Error("Share with this ISIN already exists"); } } } const repo = new ShareRepository(ShareFactory); repo.createShare("US1234567890"); const share = repo.getShareByISIN("US1234567890"); if (share) { const filteredDataPoints = ShareFilterService.filterDataPointsByTime(share, "week"); console.log(filteredDataPoints && filteredDataPoints[0]); } Answer: nextIdNumber The method returns the current _nextIdNumber, not the next. ++ suffix uses the variable's value then increments. private static get nextIdNumber() { return ShareFactory._nextIdNumber++; } For next value use: ++_nextIdNumber Defining constants is excellent. Looks like these are used only by shareFactory so put them there. It makes a more coherent class and reduces coupling; also it gets them out of global scope OOP is not necessary here
{ "domain": "codereview.stackexchange", "id": 45330, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, design-patterns, typescript, classes", "url": null }
object-oriented, design-patterns, typescript, classes OOP is not necessary here OOP's goals and purposes certainly are. And SOLID, as a nemonic, certainly does not encapsulate near the entirety of OOP principles and practice. It is hard to fully appreciate the revolution that is OOP without having experienced a complex application written in something pre-OOP (like COBOL). Indeed when a Norwegian team found it impossible to model the complexity of cargo shipping, they stopped the project and invented Simula then continued on the project using Simula. And I must say that OOP is not mutually exclusive to nor incompatible with functional programming as current debates imply. Factory Pattern Design patterns are as much about intent as their particular designs. Some patterns have virtually identical design but with slight differences motivated by their differing intent. The Factory is about creating differently typed objects with the specific type deferred to the factory. Typically we mean subclasses implementing an API. Instantiating objects of only one type would be done in a constructor. In this case we might encapsulate complex construction via methods or even use a separate class - this is good OOP but is not The Factory Pattern. Study the "construction" design patterns for their differing purposes and design.
{ "domain": "codereview.stackexchange", "id": 45330, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, design-patterns, typescript, classes", "url": null }
python Title: String and bytes range generators Question: character_range aims to be an equivalent of the native range for str and bytes (currently there's no support for step and decreasing range however): lazy and intuitive. The code are fully type hinted with mypy as the primary type checker. There are about 750 LOC. Please ignore the code style. Algorithm suggestions, optimization techniques, naming, bug hunting, general code improvements, etc. are welcome. Other files can be found at the GitHub repository. Project structure: . ├── CHANGELOG ├── LICENSE ├── README.md ├── docs │ ├── Makefile │ ├── make.bat │ └── source │ ├── conf.py │ ├── index.rst │ ├── map.rst │ └── range.rst ├── pyproject.toml ├── src │ └── character_range │ ├── __init__.py │ ├── character_and_byte_map.py │ └── string_and_bytes_range.py ├── tests │ ├── __init__.py │ ├── test_character_and_byte_map.py │ └── test_string_and_bytes_range.py └── tox.ini __init__.py: ''' Does exactly what it says on the tin: >>> list(character_range('aaa', 'aba', CharacterMap.ASCII_LOWERCASE)) ['aaa', 'aab', ..., 'aay', 'aaz', 'aba'] >>> character_range(b'0', b'10', ByteMap.ASCII_LOWERCASE) [b'0', b'1', ..., b'9', b'00', b'01', ..., b'09', b'10'] ''' from .character_and_byte_map import ( ByteInterval, ByteMap, CharacterInterval, CharacterMap ) from .string_and_bytes_range import ( BytesRange, character_range, StringRange ) __all__ = [ 'ByteInterval', 'ByteMap', 'BytesRange', 'CharacterInterval', 'CharacterMap', 'StringRange', 'character_range' ] character_and_byte_map.py: ''' Implementation of: * :class:`Interval`: :class:`CharacterInterval`, :class:`ByteInterval` * :class:`IndexMap`: :class:`CharacterMap`, :class:`ByteMap` ''' from __future__ import annotations
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python from __future__ import annotations from abc import ABC, ABCMeta, abstractmethod from collections.abc import Callable, Iterable, Iterator from dataclasses import astuple, dataclass from functools import cache, partial from itertools import chain from typing import ( Any, cast, ClassVar, Generic, overload, TYPE_CHECKING, TypeGuard, TypeVar ) from typing_extensions import Self _T = TypeVar('_T') _Char = TypeVar('_Char', str, bytes) _Index = int _LookupChar = Callable[[_Char], _Index] _LookupIndex = Callable[[_Index], _Char] def _ascii_repr(char: str | bytes) -> str: if isinstance(char, str): char_is_ascii_printable = ' ' <= char <= '~' elif isinstance(char, bytes): char_is_ascii_printable = b' ' <= char <= b'~' else: raise RuntimeError if char in ('\\', b'\\'): return r'\\' if char_is_ascii_printable: return char.decode() if isinstance(char, bytes) else char codepoint = ord(char) if codepoint <= 0xFF: return fr'\x{codepoint:02X}' if codepoint <= 0xFFFF: return fr'\u{codepoint:04X}' return fr'\U{codepoint:08X}' def _is_char_of_type( value: str | bytes, expected_type: type[_Char], / ) -> TypeGuard[_Char]: return isinstance(value, expected_type) and len(value) == 1 class NoIntervals(ValueError): ''' Raised when no intervals are passed to the map constructor. ''' pass class OverlappingIntervals(ValueError): ''' Raised when there are at least two overlapping intervals in the list of intervals passed to the map constructor. ''' def __init__(self) -> None: super().__init__('Intervals must not overlap') class ConfigurationConflict(ValueError): ''' Raised when the map constructor is passed: * A list of intervals whose elements don't have the same type. * Only one lookup function but not the other. ''' pass
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python class NotACharacter(ValueError): ''' Raised when an object is expected to be a character (a :class:`str` of length 1) but it is not one. ''' def __init__(self, actual: object) -> None: if isinstance(actual, str): value_repr = f'string of length {len(actual)}' else: value_repr = repr(actual) super().__init__(f'Expected a character, got {value_repr}') class NotAByte(ValueError): ''' Raised when an object is expected to be a byte (a :class:`bytes` object of length 1) but it is not one. ''' def __init__(self, actual: object) -> None: if isinstance(actual, bytes): value_repr = f'a bytes object of length {len(actual)}' else: value_repr = repr(actual) super().__init__(f'Expected a single byte, got {value_repr!r}') class InvalidIntervalDirection(ValueError): ''' Raised when an interval constructor is passed a ``start`` whose value is greater than that of ``end``. ''' def __init__(self, start: _Char, stop: _Char) -> None: super().__init__( f'Expected stop to be greater than or equals to start, ' f'got {start!r} > {stop!r}' ) class InvalidIndex(LookupError): ''' Raised when the index returned by a ``lookup_char`` function is not a valid index. ''' def __init__(self, length: int, actual_index: object) -> None: super().__init__( f'Expected lookup_char to return an integer ' f'in the interval [0, {length}], got {actual_index!r}' )
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python class InvalidChar(LookupError): ''' Raised when the character returned by a ``lookup_index`` function is not of the type expected by the map. ''' def __init__( self, actual_char: object, expected_type: type[str] | type[bytes] ) -> None: if issubclass(expected_type, str): expected_type_name = 'string' else: expected_type_name = 'bytes object' super().__init__( f'Expected lookup_index to return ' f'a {expected_type_name}, got {actual_char!r}' )
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python class Interval(Generic[_Char], ABC): ''' An interval (both ends inclusive) of characters, represented using either :class:`str` or :class:`bytes`. For a :class:`CharacterInterval`, the codepoint of an endpoint must not be negative or greater than ``0x10FFFF``. Similarly, for a :class:`ByteInterval`, the integral value of an endpoint must be in the interval ``[0, 255]``. ''' start: _Char end: _Char # PyCharm can't infer that an immutable dataclass # already has __hash__ defined and will therefore # raise a warning if this is an @abstractmethod. # However, it outright rejects unsafe_hash = True # if __hash__ is also defined, regardless of the # TYPE_CHECKING guard. def __hash__(self) -> int: raise RuntimeError('Subclasses must implement __hash__') @abstractmethod def __iter__(self) -> Iterator[_Char]: ''' Lazily yield each character or byte. ''' raise NotImplementedError @abstractmethod def __getitem__(self, item: int) -> _Char: ''' ``O(1)`` indexing of character or byte. ''' raise NotImplementedError @abstractmethod def __add__(self, other: Self) -> IndexMap[_Char]: ''' Create a new :class:`IndexMap` with both ``self`` and ``other`` as ``intervals``. ''' raise NotImplementedError def __len__(self) -> int: ''' The length of the interval, equivalent to ``codepoint(start) - codepoint(end) + 1``. ''' return len(self.to_codepoint_range()) def __contains__(self, item: Any) -> bool: ''' Assert that ``item``'s codepoint is greater than or equals to that of ``start`` and less than or equals to that of ``end``. ''' if not isinstance(item, self.start.__class__) or len(item) != 1:
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python ''' if not isinstance(item, self.start.__class__) or len(item) != 1: return False return self.start <= item <= self.end def __repr__(self) -> str: return f'{self.__class__.__name__}({self})' def __str__(self) -> str: if len(self) == 1: return _ascii_repr(self.start) return f'{_ascii_repr(self.start)}-{_ascii_repr(self.end)}' def __eq__(self, other: object) -> bool: ''' Two intervals are equal if one is an instance of the other's class and their endpoints have the same integral values. ''' if not isinstance(other, self.__class__): return NotImplemented return self.to_codepoint_range() == other.to_codepoint_range() def __and__(self, other: Self) -> bool: ''' See :meth:`Interval.intersects`. ''' if not isinstance(other, self.__class__): return NotImplemented earlier_end = min(self.end, other.end) later_start = max(self.start, other.start) return later_start <= earlier_end @property @abstractmethod def element_type(self) -> type[_Char]: ''' A class-based property that returns the type of the interval's elements. ''' raise NotImplementedError def _validate(self, *, exception_type: type[ValueError]) -> None: if not _is_char_of_type(self.start, self.element_type): raise exception_type(self.start) if not _is_char_of_type(self.end, self.element_type): raise exception_type(self.end) if self.start > self.end: raise InvalidIntervalDirection(self.start, self.end) def to_codepoint_range(self) -> range: ''' Convert the interval to a native :class:`range` that
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python ''' Convert the interval to a native :class:`range` that would yield the codepoints of the elements of the interval. ''' return range(ord(self.start), ord(self.end) + 1) def intersects(self, other: Self) -> bool: ''' Whether two intervals intersect each other. ''' return self & other
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python @dataclass( eq = False, frozen = True, repr = False, slots = True, unsafe_hash = True ) class CharacterInterval(Interval[str]): start: str end: str def __post_init__(self) -> None: self._validate(exception_type = NotACharacter) def __iter__(self) -> Iterator[str]: for codepoint in self.to_codepoint_range(): yield chr(codepoint) def __getitem__(self, item: int) -> str: if not 0 <= item < len(self): raise IndexError('Index out of range') return chr(ord(self.start) + item) def __add__(self, other: Self) -> CharacterMap: if not isinstance(other, self.__class__): return NotImplemented return CharacterMap([self, other]) @property def element_type(self) -> type[str]: return str @dataclass( eq = False, frozen = True, repr = False, slots = True, unsafe_hash = True ) class ByteInterval(Interval[bytes]): start: bytes end: bytes def __post_init__(self) -> None: self._validate(exception_type = NotAByte) def __iter__(self) -> Iterator[bytes]: for bytes_value in self.to_codepoint_range(): yield bytes_value.to_bytes(1, 'big') def __getitem__(self, item: int) -> bytes: if not isinstance(item, int): raise TypeError(f'Expected a non-negative integer, got {item}') if not 0 <= item < len(self): raise IndexError('Index out of range') return (ord(self.start) + item).to_bytes(1, 'big') def __add__(self, other: Self) -> ByteMap: if not isinstance(other, self.__class__): return NotImplemented return ByteMap([self, other]) @property def element_type(self) -> type[bytes]: return bytes
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python @dataclass(frozen = True, slots = True) class _Searchers(Generic[_Char]): lookup_char: _LookupChar[_Char] | None lookup_index: _LookupIndex[_Char] | None @property def both_given(self) -> bool: ''' Whether both functions are not ``None``. ''' return self.lookup_char is not None and self.lookup_index is not None @property def both_omitted(self) -> bool: ''' Whether both functions are ``None``. ''' return self.lookup_char is None and self.lookup_index is None @property def only_one_given(self) -> bool: ''' Whether only one of the functions is ``None``. ''' return not self.both_given and not self.both_omitted class _RunCallbackAfterInitialization(type): ''' :class:`_HasPrebuiltMembers`'s metaclass (a.k.a. metametaclass). Runs a callback defined at the instance's level. ''' _callback_method_name: str def __call__(cls, *args: object, **kwargs: object) -> Any: class_with_prebuilt_members = super().__call__(*args, **kwargs) callback = getattr(cls, cls._callback_method_name) callback(class_with_prebuilt_members) return class_with_prebuilt_members
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python # This cannot be generic due to # https://github.com/python/mypy/issues/11672 class _HasPrebuiltMembers( ABCMeta, metaclass = _RunCallbackAfterInitialization ): ''' :class:`CharacterMap` and :class:`ByteMap`'s metaclass. ''' _callback_method_name: ClassVar[str] = '_instantiate_members' # When the `cls` (`self`) argument is typed as 'type[_T]', # mypy refuses to understand that it also has the '_member_names' # attribute, regardless of assertions and castings. # The way to circumvent this is to use 'getattr()', # as demonstrated below in '__getitem__' and 'members'. _member_names: list[str] def __new__( mcs, name: str, bases: tuple[type, ...], namespace: dict[str, Any], **kwargs: Any ) -> _HasPrebuiltMembers: new_class = super().__new__(mcs, name, bases, namespace, **kwargs) if ABC in bases: return new_class new_class._member_names = [ name for name, value in new_class.__dict__.items() if not name.startswith('_') and not callable(value) ] return new_class def __getitem__(cls: type[_T], item: str) -> _T: member_names: list[str] = getattr(cls, '_member_names') if item not in member_names: raise LookupError(f'No such member: {item!r}') return cast(_T, getattr(cls, item)) @property def members(cls: type[_T]) -> tuple[_T, ...]: ''' Returns a tuple of pre-built members of the class. ''' member_names: list[str] = getattr(cls, '_member_names') return tuple(getattr(cls, name) for name in member_names) def _instantiate_members(cls) -> None: for member_name in cls._member_names: value = getattr(cls, member_name) if isinstance(value, tuple):
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python value = getattr(cls, member_name) if isinstance(value, tuple): setattr(cls, member_name, cls(*value)) else: setattr(cls, member_name, cls(value))
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python class IndexMap(Generic[_Char], ABC): ''' A two-way mapping between character or byte to its corresponding index. ''' __slots__ = ( '_intervals', '_char_to_index', '_searchers', '_index_to_char', '_maps_populated', '_element_type', '_not_a_char_exception' ) _intervals: tuple[Interval[_Char], ...] _char_to_index: dict[_Char, _Index] _index_to_char: dict[_Index, _Char] _searchers: _Searchers[_Char] _element_type: type[_Char] _maps_populated: bool _not_a_char_exception: type[NotACharacter] | type[NotAByte] def __init__( self, intervals: Iterable[Interval[_Char]], lookup_char: _LookupChar[_Char] | None = None, lookup_index: _LookupIndex[_Char] | None = None ) -> None: r''' Construct a new map from a number of intervals. The underlying character-to-index and index-to-character maps will not be populated if lookup functions are given. Lookup functions are expected to be the optimized versions of the naive, brute-force lookup algorithm. This relationship is similar to that of ``__method__``\ s and built-ins; for example, while ``__contains__`` is automatically implemented when a class defines both ``__len__`` and ``__getitem__``, a ``__contains__`` may still be needed if manual iterations are too unperformant, unnecessary or unwanted. Lookup functions must raise either :class:`LookupError` or :class:`ValueError` if the index or character cannot be found. If the index returned by ``lookup_char`` is not in the interval ``[0, len(self) - 1]``, a :class:`ValueError` is raised. :raise ConfigurationConflict: \ If only one lookup function is given. :raise NoIntervals: \ If no intervals are given. '''
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python :raise NoIntervals: \ If no intervals are given. ''' self._intervals = tuple(intervals) self._searchers = _Searchers(lookup_char, lookup_index) self._char_to_index = {} self._index_to_char = {} if self._searchers.only_one_given: raise ConfigurationConflict( 'The two lookup functions must be either ' 'both given or both omitted' ) if not self._intervals: raise NoIntervals('At least one interval expected') self._intervals_must_have_same_type() self._element_type = self._intervals[0].element_type if issubclass(self._element_type, str): self._not_a_char_exception = NotACharacter elif issubclass(self._element_type, bytes): self._not_a_char_exception = NotAByte else: raise RuntimeError if self._searchers.both_given: self._intervals_must_not_overlap() self._maps_populated = False return self._populate_maps() self._maps_populated = True def __hash__(self) -> int: return hash(self._intervals) @cache def __len__(self) -> int: if self._maps_populated: return len(self._char_to_index) return sum(len(interval) for interval in self._intervals) @cache def __repr__(self) -> str: joined_ranges = ''.join(str(interval) for interval in self._intervals) return f'{self.__class__.__name__}({joined_ranges})' @overload def __getitem__(self, item: _Char) -> _Index: ... @overload def __getitem__(self, item: _Index) -> _Char: ... def __getitem__(self, item: _Char | _Index) -> _Index | _Char: ''' Either look for the character/index in the underlying maps,
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python ''' Either look for the character/index in the underlying maps, or delegate that task to the look-up functions given. Results are cached. :raise ValueError: \ If ``item`` is neither a character/byte nor an index. :raise IndexError: \ If ``lookup_char`` ''' if isinstance(item, int): return self._get_char_given_index(item) if isinstance(item, self._element_type): return self._get_index_given_char(item) raise TypeError(f'Expected a character or an index, got {item!r}') def __contains__(self, item: object) -> bool: if not isinstance(item, self._element_type | int): return False if isinstance(item, int): return 0 <= item < len(self) try: # This is necessary for PyCharm, # deemed redundant by mypy, # and makes pyright think that 'item' is of type 'object'. item = cast(_Char, item) # type: ignore _ = self._get_index_given_char(item) except (LookupError, ValueError): return False else: return True def __eq__(self, other: object) -> bool: if not isinstance(other, self.__class__): return NotImplemented return self._intervals == other._intervals # Needed for testing and type hint convenience def __add__(self, other: Self | IndexMap[_Char] | Interval[_Char]) -> Self: if not isinstance(other, IndexMap | Interval): return NotImplemented if other.element_type is not self.element_type: raise ConfigurationConflict('Different element types') lookup_char, lookup_index = astuple(self._searchers) if isinstance(other, Interval): return self.__class__(
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python if isinstance(other, Interval): return self.__class__( self._intervals + tuple([other]), lookup_char = lookup_char, lookup_index = lookup_index ) if self._searchers != other._searchers: raise ConfigurationConflict( 'Maps having different lookup functions ' 'cannot be combined' ) return self.__class__( self._intervals + other._intervals, lookup_char = lookup_char, lookup_index = lookup_index ) @property def intervals(self) -> tuple[Interval[_Char], ...]: ''' The intervals that make up the map. ''' return self._intervals @property def element_type(self) -> type[_Char]: ''' The type of the map's elements. ''' return self._element_type def _intervals_must_have_same_type(self) -> None: interval_types = {type(interval) for interval in self._intervals} if len(interval_types) > 1: raise ConfigurationConflict('Intervals must be of same types') def _intervals_must_not_overlap(self) -> None: seen: list[Interval[_Char]] = [] for current_interval in self._intervals: overlapped = any( current_interval.intersects(seen_interval) for seen_interval in seen ) if overlapped: raise OverlappingIntervals seen.append(current_interval) def _populate_maps(self) -> None: chained_intervals = chain.from_iterable(self._intervals) for index, char in enumerate(chained_intervals): if char in self._char_to_index: raise OverlappingIntervals self._char_to_index[char] = index
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python self._char_to_index[char] = index self._index_to_char[index] = char def _get_char_given_index(self, index: _Index, /) -> _Char: if index not in self: raise IndexError(f'Index {index} is out of range') if index in self._index_to_char: return self._index_to_char[index] lookup_index = self._searchers.lookup_index assert lookup_index is not None result = lookup_index(index) if not _is_char_of_type(result, self._element_type): raise InvalidChar(result, self._element_type) self._index_to_char[index] = result return self._index_to_char[index] def _get_index_given_char(self, char: _Char, /) -> _Index: if not _is_char_of_type(char, self._element_type): raise self._not_a_char_exception(char) if char in self._char_to_index: return self._char_to_index[char] lookup_char = self._searchers.lookup_char if lookup_char is None: raise LookupError(f'Char {char!r} is not in the map') result = lookup_char(char) if not isinstance(result, int) or result not in self: raise InvalidIndex(len(self), result) self._char_to_index[char] = result return self._char_to_index[char]
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python def _ascii_index_from_char_or_byte(char_or_byte: str | bytes) -> int: codepoint = ord(char_or_byte) if not 0 <= codepoint <= 0xFF: raise ValueError('Not an ASCII character or byte') return codepoint @overload def _ascii_char_or_byte_from_index(constructor: type[str], index: int) -> str: ... @overload def _ascii_char_or_byte_from_index( constructor: type[bytes], index: int ) -> bytes: ... def _ascii_char_or_byte_from_index( constructor: type[str] | type[bytes], index: int ) -> str | bytes: if issubclass(constructor, str): return constructor(chr(index)) if issubclass(constructor, bytes): # \x80 and higher would be converted # to two bytes with .encode() alone. return constructor(index.to_bytes(1, 'big')) raise RuntimeError _ascii_char_from_index = cast( Callable[[int], str], partial(_ascii_char_or_byte_from_index, str) ) _ascii_byte_from_index = cast( Callable[[int], bytes], partial(_ascii_char_or_byte_from_index, bytes) )
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python if TYPE_CHECKING: class CharacterMap(IndexMap[str], metaclass = _HasPrebuiltMembers): # At runtime, this is a read-only class-level property. members: ClassVar[tuple[CharacterMap, ...]] ASCII_LOWERCASE: ClassVar[CharacterMap] ASCII_UPPERCASE: ClassVar[CharacterMap] ASCII_LETTERS: ClassVar[CharacterMap] ASCII_DIGITS: ClassVar[CharacterMap] LOWERCASE_HEX_DIGITS: ClassVar[CharacterMap] UPPERCASE_HEX_DIGITS: ClassVar[CharacterMap] LOWERCASE_BASE_36: ClassVar[CharacterMap] UPPERCASE_BASE_36: ClassVar[CharacterMap] ASCII: ClassVar[CharacterMap] NON_ASCII: ClassVar[CharacterMap] UNICODE: ClassVar[CharacterMap] # At runtime, this functionality is provided # using the metaclass's __getitem__. def __class_getitem__(cls, item: str) -> CharacterMap: ... class ByteMap(IndexMap[bytes], metaclass = _HasPrebuiltMembers): # At runtime, this is a read-only class-level property. members: ClassVar[tuple[ByteMap, ...]] ASCII_LOWERCASE: ClassVar[ByteMap] ASCII_UPPERCASE: ClassVar[ByteMap] ASCII_LETTERS: ClassVar[ByteMap] ASCII_DIGITS: ClassVar[ByteMap] LOWERCASE_HEX_DIGITS: ClassVar[ByteMap] UPPERCASE_HEX_DIGITS: ClassVar[ByteMap] LOWERCASE_BASE_36: ClassVar[ByteMap] UPPERCASE_BASE_36: ClassVar[ByteMap] ASCII: ClassVar[ByteMap] # At runtime, this functionality is provided # using the metaclass's __getitem__. def __class_getitem__(cls, item: str) -> ByteMap: ...
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python else: class CharacterMap(IndexMap[str], metaclass = _HasPrebuiltMembers): ASCII_LOWERCASE = [CharacterInterval('a', 'z')] ASCII_UPPERCASE = [CharacterInterval('A', 'Z')] ASCII_LETTERS = ASCII_LOWERCASE + ASCII_UPPERCASE ASCII_DIGITS = [CharacterInterval('0', '9')] LOWERCASE_HEX_DIGITS = ASCII_DIGITS + [CharacterInterval('a', 'f')] UPPERCASE_HEX_DIGITS = ASCII_DIGITS + [CharacterInterval('A', 'F')] LOWERCASE_BASE_36 = ASCII_DIGITS + ASCII_LOWERCASE UPPERCASE_BASE_36 = ASCII_DIGITS + ASCII_UPPERCASE ASCII = ( [CharacterInterval('\x00', '\xFF')], _ascii_index_from_char_or_byte, _ascii_char_from_index ) NON_ASCII = ( [CharacterInterval('\u0100', '\U0010FFFF')], lambda char: ord(char) - 0x100, lambda index: chr(index + 0x100) ) UNICODE = ([CharacterInterval('\x00', '\U0010FFFF')], ord, chr) class ByteMap(IndexMap[bytes], metaclass = _HasPrebuiltMembers): ASCII_LOWERCASE = [ByteInterval(b'a', b'z')] ASCII_UPPERCASE = [ByteInterval(b'A', b'Z')] ASCII_LETTERS = ASCII_LOWERCASE + ASCII_UPPERCASE ASCII_DIGITS = [ByteInterval(b'0', b'9')] LOWERCASE_HEX_DIGITS = ASCII_DIGITS + [ByteInterval(b'a', b'f')] UPPERCASE_HEX_DIGITS = ASCII_DIGITS + [ByteInterval(b'A', b'F')] LOWERCASE_BASE_36 = ASCII_DIGITS + ASCII_LOWERCASE UPPERCASE_BASE_36 = ASCII_DIGITS + ASCII_UPPERCASE ASCII = ( [ByteInterval(b'\x00', b'\xFF')], _ascii_index_from_char_or_byte, _ascii_byte_from_index ) string_and_bytes_range.py: ''' The highest-level features of the package, implemented as :class:`_Range` and :func:`character_range`. ''' from __future__ import annotations
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python from __future__ import annotations from abc import ABC, abstractmethod from collections.abc import Iterable, Iterator from enum import Enum from functools import total_ordering from typing import cast, Generic, overload, TypeVar from typing_extensions import Literal, Self from .character_and_byte_map import ByteMap, CharacterMap, IndexMap _StrOrBytes = TypeVar('_StrOrBytes', str, bytes) # Keep these in sync with CharacterMap and ByteMap # TODO: Allow passing the name of a prebuilt map as an argument. _CharacterMapName = Literal[ 'ascii_lowercase', 'ascii_uppercase', 'ascii_letters', 'ascii_digits', 'lowercase_hex_digits', 'uppercase_hex_digits', 'lowercase_base_36', 'uppercase_base_36', 'ascii', 'non_ascii', 'unicode' ] _ByteMapName = Literal[ 'ascii_lowercase', 'ascii_uppercase', 'ascii_letters', 'ascii_digits', 'lowercase_hex_digits', 'uppercase_hex_digits', 'lowercase_base_36', 'uppercase_base_36', 'ascii' ] @overload def _get_prebuilt_map( map_class: type[CharacterMap], name: str ) -> CharacterMap: ... @overload def _get_prebuilt_map( map_class: type[ByteMap], name: str ) -> ByteMap: ... def _get_prebuilt_map( map_class: type[CharacterMap] | type[ByteMap], name: str ) -> CharacterMap | ByteMap: try: member = map_class[name.upper()] except KeyError: raise _NoSuchPrebuiltMap(name) return cast(CharacterMap | ByteMap, member) def _split(value: _StrOrBytes) -> list[_StrOrBytes]: if isinstance(value, str): return list(value) return [ byte_as_int.to_bytes(1, 'big') for byte_as_int in value ] # TODO: Support different types of ranges class _RangeType(str, Enum): ''' Given a range from ``aa`` to ``zz``:
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python +------------+----------+----------+ | Range type | Contains | Contains | | / Property | ``aa`` | ``zz`` | +============+==========+==========+ | Open | No | No | +------------+----------+----------+ | Closed | Yes | Yes | +------------+----------+----------+ | Left-open | No | Yes | +------------+----------+----------+ | Right-open | Yes | No | +------------+----------+----------+ These terms are taken from `the Wikipedia article about mathematical intervals \ <https://en.wikipedia.org/wiki/Interval_(mathematics)>`_. A :class:`_Range` always represent a closed interval. However, for convenience, :func:`character_range` accepts an optional ``range_type`` argument that deals with these. ''' OPEN = 'open' CLOSED = 'closed' LEFT_OPEN = 'left_open' RIGHT_OPEN = 'right_open' class InvalidEndpoints(ValueError): ''' Raised when the endpoints given to :class:`_Range` is either: * Empty, or * At least one character is not in the corresponding map. ''' def __init__(self, *endpoints: str | bytes): super().__init__(', '.join(repr(endpoint) for endpoint in endpoints)) class InvalidRangeDirection(ValueError): ''' Raised when ``start`` is longer than ``end`` or they have the same length but ``start`` is lexicographically "less than" end. ''' def __init__(self, start: object, end: object) -> None: super().__init__(f'Start is greater than end ({start!r} > {end!r})') class _NoSuchPrebuiltMap(ValueError): def __init__(self, name: str) -> None: super().__init__(f'No such prebuilt map with given name: {name!r}') class _EmptyListOfIndices(ValueError): def __init__(self) -> None: super().__init__('List of indices must not be empty')
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python class _InvalidBase(ValueError): def __init__(self, actual: object) -> None: super().__init__(f'Expected a positive integer, got {actual!r}')
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python @total_ordering class _IncrementableIndexCollection: ''' A collection of indices of a :class:`IndexMap` that can be incremented one by one. :meth:`_MonotonicIndexCollection.increment` works in an index-wise manner:: >>> c = _IncrementableIndexCollection([1], 2) >>> c.increment() _MonotonicIndexCollection([0, 0], base = 2) ''' __slots__ = ('_inverted_indices', '_base') _inverted_indices: list[int] _base: int def __init__(self, indices: Iterable[int], /, base: int) -> None: self._inverted_indices = list(indices)[::-1] self._base = base if not self._inverted_indices: raise _EmptyListOfIndices if not isinstance(base, int) or base < 1: raise _InvalidBase(base) def __repr__(self) -> str: indices, base = self._indices, self._base return f'{self.__class__.__name__}({indices!r}, {base = !r})' def __index__(self) -> int: ''' The integeral value computed by interpreting the indices as the digits of a base-*n* integer. ''' total = 0 for order_of_magnitude, index in enumerate(self._inverted_indices): total += index * self._base ** order_of_magnitude return total def __len__(self) -> int: ''' The number of indices the collection currently holds. ''' return len(self._inverted_indices) def __iter__(self) -> Iterator[int]: ''' Lazily yield the elements this collection currently holds. ''' yield from reversed(self._inverted_indices) def __lt__(self, other: Self) -> bool: ''' Whether ``other``'s length is greater than ``self``'s or the lengths are equals but the integral value of ``other`` is greater than that of ``self``. '''
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python ``other`` is greater than that of ``self``. ''' if not isinstance(other, self.__class__): return NotImplemented if len(self) < len(other): return True return len(self) == len(other) and self._indices < other._indices def __eq__(self, other: object) -> bool: ''' Whether two collections have the same base and elements. ''' if not isinstance(other, self.__class__): return NotImplemented return self._base == other._base and self._indices == other._indices @property def _indices(self) -> tuple[int, ...]: ''' The current indices of the collection. ''' return tuple(self) @property def base(self) -> int: ''' The maximum value of an index, plus 1. ''' return self._base def increment(self) -> Self: ''' Add 1 to the last index. If the new value is equals to ``base``, that index will become 0 and the process continues at the next index. If the last index is reached, a new index (0) is added to the list. This is equivalent to C/C++'s pre-increment operator, in that it returns the original value after modification. Examples:: [0, 0] -> [0, 1] [0, 1] -> [1, 0] [1, 1] -> [0, 0, 0] ''' for order_of_magnitude in range(len(self._inverted_indices)): self._inverted_indices[order_of_magnitude] += 1 if self._inverted_indices[order_of_magnitude] < self._base: return self self._inverted_indices[order_of_magnitude] = 0 self._inverted_indices.append(0) return self
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python class _Range(Generic[_StrOrBytes], ABC): ''' Represents a range between two string or bytes object endpoints. A range of this type is always a closed interval: both endpoints are inclusive. This goes in line with how regex character ranges work, even though those only ever support single characters:: >>> list(StringRange('a', 'c', CharacterMap.ASCII_LOWERCASE)) ['a', 'b', 'c'] >>> list(StringRange('aa', 'ac', CharacterMap.ASCII_LOWERCASE)) ['aa', 'ab', 'ac'] For :class:`BytesRange`, each byte of the yielded :class:`bytes` objects will have the corresponding integral values ranging from 0 through 0xFF:: >>> list(BytesRange(b'0xFE', b'0x81', ByteMap.ASCII)) [b'0xFE', b'0xFF', b'0x80', b'0x81'] Also note that the next value after ``[base - 1]`` is ``[0, 0]``, not ``[1, 0]``:: >>> list(StringRange('0', '19', CharacterMap.ASCII_DIGITS)) [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19' ] See also :class:`_IncrementableIndexCollection`. ''' __slots__ = ('_start', '_end', '_map') _start: _StrOrBytes _end: _StrOrBytes _map: IndexMap[_StrOrBytes] def __init__( self, start: _StrOrBytes, end: _StrOrBytes, /, index_map: IndexMap[_StrOrBytes] ) -> None: self._start = start self._end = end self._map = index_map start_is_valid = self._is_valid_endpoint(start) end_is_valid = self._is_valid_endpoint(end) if not start_is_valid or not end_is_valid: raise InvalidEndpoints(start, end) if len(start) > len(end) or len(start) == len(end) and start > end: raise InvalidRangeDirection(start, end)
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python raise InvalidRangeDirection(start, end) def __repr__(self) -> str: return f'{self.__class__.__name__}({self._start!r}, {self._end!r})' def __iter__(self) -> Iterator[_StrOrBytes]: ''' Lazily yield the elements. ''' current = self._make_collection(self._start) end = self._make_collection(self._end) # https://github.com/python/mypy/issues/16711 while current <= end: # type: ignore yield self._make_element(current) current.increment() def __len__(self) -> int: ''' The number of elements the range would yield, calculated mathematically. ''' # Realistic example: # start = 'y'; end = 'aaac' # base = len('a'-'z') = 26 # # len = ( # (len('a'-'z') + len('aa'-'zz') + len('aaa'-'zzz')) + # len('aaaa'-'aaac') - # (len('a'-'y') - len('y'-'y') # ) # len = (base ** 1 + base ** 2 + base ** 3) + 3 - (25 - 1) # len = (26 ** 1 + 26 ** 2 + 26 ** 3) + 3 - 24 start, end = self._start, self._end base = len(self._map) from_len_start_up_to_len_end: int = sum( base ** width for width in range(len(start), len(end)) ) from_len_start_through_start = int(self._make_collection(start)) from_len_end_through_end = int(self._make_collection(end)) result = from_len_start_up_to_len_end result += from_len_end_through_end result -= from_len_start_through_start result += 1 return result @property def _base(self) -> int: return len(self._map) @property def start(self) -> _StrOrBytes: ''' The starting endpoint of the range. ''' return self._start @property def end(self) -> _StrOrBytes:
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python ''' return self._start @property def end(self) -> _StrOrBytes: ''' The ending endpoint of the range. ''' return self._end @property def map(self) -> IndexMap[_StrOrBytes]: ''' The map to look up the available characters or bytes. ''' return self._map @property def element_type(self) -> type[_StrOrBytes]: ''' The element type of :meth:`map`. See :meth:`IndexMap.element_type`. ''' return self._map.element_type @abstractmethod def _make_element( self, indices: _IncrementableIndexCollection, / ) -> _StrOrBytes: raise NotImplementedError def _is_valid_endpoint(self, value: _StrOrBytes) -> bool: return ( len(value) > 0 and all(char in self._map for char in _split(value)) ) def _make_collection( self, value: _StrOrBytes, / ) -> _IncrementableIndexCollection: indices = (self._map[char] for char in _split(value)) return _IncrementableIndexCollection(indices, len(self._map))
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python class StringRange(_Range[str]): def _make_element(self, indices: _IncrementableIndexCollection, /) -> str: return ''.join(self._map[index] for index in indices) class BytesRange(_Range[bytes]): def _make_element(self, indices: _IncrementableIndexCollection, /) -> bytes: return b''.join(self._map[index] for index in indices) @overload def character_range( start: str, end: str, /, index_map: IndexMap[str] ) -> StringRange: ... @overload def character_range( start: bytes, end: bytes, /, index_map: IndexMap[bytes] ) -> BytesRange: ... # TODO: Design a more intuitive signature for this function # Example: A map parser than takes in a string of form r'a-zB-J&$\-\x00-\x12' def character_range( start: str | bytes, end: str | bytes, /, index_map: IndexMap[str] | IndexMap[bytes] ) -> StringRange | BytesRange: ''' ``range``-lookalike alias for :class:`StringRange` and :class:`BytesRange`. ``start`` and ``end`` must be of the same type, either :class:`str` or :class:`bytes`. ``index_map`` must contain all elements of both of them. ''' map_class: type[CharacterMap] | type[ByteMap] | None = None range_class: type[StringRange] | type[BytesRange] | None = None if isinstance(start, str) and isinstance(end, str): map_class = CharacterMap range_class = StringRange if isinstance(start, bytes) and isinstance(end, bytes): map_class = ByteMap range_class = BytesRange if map_class is not None and range_class is not None: # Either mypy isn't yet smart enough to figure out # that this will not cause errors, or I'm not smart # enough to figure out all cases. return range_class(start, end, index_map) # type: ignore raise TypeError( f'Expected two strings or two bytes objects, got ' f'{type(start).__name__} and {type(end).__name__}' )
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python Answer: There are many marks of a vaguely good library here - multiple modules, docs, tests, types, __all__, custom exceptions. Does exactly what it says on the tin is debatable. The moment a Python developer sees range, it carries implications: we expect a half-open interval. That applies to (for example) the built-in range, randrange, and Numpy's arange. Also note that all three have the parameters start, stop, step. Strongly consider following this signature and making the range half-open. Good job with the types. _Index = int is good, but could be strengthened with NewType. In _ascii_repr, raise RuntimeError is not appropriate and should be replaced with raise TypeError(). Don't triple-apostrophe docstrings; use triple quotes. You've said that you're using PyCharm, which means it will already have warned you about this, assuming that you have a sane configuration. Otherwise, it just... seems like a tonne of code for what is a very simple operation. At the very least, I'd drop support for bytes entirely, since it's trivial for the user to encode and decode themselves. About your tests: Most test cases are dynamically generated. (Perfect Heisenbug environment, I know.) So... you know the problem. Either do plain-old hard-coded tests, or use a testing library like hypothesis that takes stochastic testing seriously. Is >>> character_range(b'0', b'10', ByteMap.ASCII_LOWERCASE) [b'0', b'1', ..., b'9', b'00', b'01', ..., b'09', b'10'] accurate? Sure seems like it isn't, and should show ASCII_DIGITS instead.
{ "domain": "codereview.stackexchange", "id": 45331, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python, programming-challenge, string-processing Title: Advent of Code 2023 - Day 6: Wait For It Question: Part One: The task involves organizing multiple toy boat races, each assigned a specific race time and a recorded distance. To surpass the existing record, participants must optimize the duration of holding the button, as the toy boat's speed increases by one millimeter per millisecond for every whole millisecond the button is pressed at the beginning of the race. The objective is to determine the various possible ways to achieve a performance surpassing the established record. For example: Time: 7 15 30 Distance: 9 40 200 This document describes three races: The first race lasts 7 milliseconds. The record distance in this race is 9 millimeters. The second race lasts 15 milliseconds. The record distance in this race is 40 millimeters. The third race lasts 30 milliseconds. The record distance in this race is 200 millimeters. Your toy boat has a starting speed of zero millimeters per millisecond. For each whole millisecond you spend at the beginning of the race holding down the button, the boat's speed increases by one millimeter per millisecond. So, because the first race lasts 7 milliseconds, you only have a few options:
{ "domain": "codereview.stackexchange", "id": 45332, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing Don't hold the button at all (that is, hold it for 0 milliseconds) at the start of the race. The boat won't move; it will have traveled 0 millimeters by the end of the race. Hold the button for 1 millisecond at the start of the race. Then, the boat will travel at a speed of 1 millimeter per millisecond for 6 milliseconds, reaching a total distance traveled of 6 millimeters. Hold the button for 2 milliseconds, giving the boat a speed of 2 millimeters per millisecond. It will then get 5 milliseconds to move, reaching a total distance of 10 millimeters. Hold the button for 3 milliseconds. After its remaining 4 milliseconds of travel time, the boat will have gone 12 millimeters. Hold the button for 4 milliseconds. After its remaining 3 milliseconds of travel time, the boat will have gone 12 millimeters. Hold the button for 5 milliseconds, causing the boat to travel a total of 10 millimeters. Hold the button for 6 milliseconds, causing the boat to travel a total of 6 millimeters. Hold the button for 7 milliseconds. That's the entire duration of the race. You never let go of the button. The boat can't move until you let go of the button. Please make sure you let go of the button so the boat gets to move. 0 millimeters. In the example provided, with a current record of 9 millimeters: For the first race, holding the button for 2, 3, 4, or 5 milliseconds allows winning, totaling 4 different ways. In the second race, winning strategies involve holding the button for at least 4 milliseconds and at most 11 milliseconds, providing a total of 8 different ways to win. For the third race, winning requires holding the button for at least 11 milliseconds and no more than 19 milliseconds, offering a total of 9 ways to win. The answer is determined by multiplying the respective counts of winning strategies in each race. In this example, if you multiply all these values together, you get 288 (4 * 8 * 9). #!/usr/bin/env python3 from pathlib import Path from typing import Iterable
{ "domain": "codereview.stackexchange", "id": 45332, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing from pathlib import Path from typing import Iterable import typer def race(speed: int, time_left: int, record: int) -> bool: # Check if we can cover a distance greater than the specified record. return speed * time_left > record def parse_nums(line: str) -> list[int]: # Name: A B C ... nums = line.split(": ")[1] return list(map(int, nums.split())) def count_wins(time: int, distance: int) -> int: return sum( race(hold_time, time - hold_time, distance) for hold_time in range(1, time + 1) ) def total_possibilities(lines: Iterable[str]) -> int: times, distances = tuple(map(parse_nums, lines)) total_margin = 1 for idx, time in enumerate(times): count = count_wins(time, distances[idx]) if count: total_margin *= count return total_margin def main(race_document: Path) -> None: with open(race_document) as f: print(total_possibilities(f)) if __name__ == "__main__": typer.run(main) Part 2: This part involves a single, extended toy boat race with combined time and record distance. So, the example from before: Time: 7 15 30 Distance: 9 40 200 now instead means this: Time: 71530 Distance: 940200 This time, the answer is 71503. #!/usr/bin/env python3 import sys from pathlib import Path from typing import Iterable import typer def race(hold_time: int, time_left: int, record: int) -> bool: # Check if we can cover a distance greater than the specified record. return hold_time * time_left > record def parse_nums(line: str) -> list[int]: # Name: A B C ... nums = line.split(": ")[1].strip().split() return int("".join(nums)) def count_wins(time: int, distance: int) -> int: return sum( race(hold_time, time - hold_time, distance) for hold_time in range(1, time + 1) ) def total_possibilities(lines: Iterable[str]) -> int: return count_wins(*tuple(map(parse_nums, lines)))
{ "domain": "codereview.stackexchange", "id": 45332, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing def main(race_document: Path) -> None: sys.set_int_max_str_digits(0) with open(race_document) as f: print(total_possibilities(f)) if __name__ == "__main__": typer.run(main) Review Request: General coding comments, style, etc. What are some possible simplications? What would you do differently? Answer: Part 1 You ask what might be done differently. In function total_possibilities I would probably replace the use of the enumerate function used in your loop with the buit-in zip function: def total_possibilities(lines: Iterable[str]) -> int: # No need to use the tuple function: times, distances = map(parse_nums, lines) total_margin = 1 for time, distance in zip(times, distances): count = count_wins(time, distance) if count: total_margin *= count return total_margin We can now modify function parse_nums to return a map instead of a list since there is no longer any need to do any explicit indexing: def parse_nums(line: str) -> list[int]: # Name: A B C ... nums = line.split(": ")[1] return map(int, nums.split()) # No need to create a list If you wished you could also incorporate the functools.reduce function into function total_possibilities and use a comprehension: def total_possibilities(lines: Iterable[str]) -> int: times, distances = map(parse_nums, lines) return reduce( lambda x, y: x * y, (count_wins(time, distance) for time, distance in zip(times, distances)) ) Finally, in count_wins you are letting hold_range take on the values in the range [1, time]. But you should use instead the range [1, time-1] since if you hold the button for the maximum allowed time there is no time left for the boat to move: def count_wins(time: int, distance: int) -> int: return sum( race(hold_time, time - hold_time, distance) for hold_time in range(1, time) )
{ "domain": "codereview.stackexchange", "id": 45332, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing Part 2 In function parse_nums you are doing an extra split followed by a join. These two calls can be replaced with a call to replace: def parse_nums(line: str) -> list[int]: # Name: A B C ... return int(line.split(": ")[1].replace(' ', '')) Note that there is no need to perform a call to strip. But clearly, as indicated in the comment made by user vnp, the biggest improvement can be achieved with a change in algorithm. As I understand it you really want to solve the quadratic equation for distance + 1. This yields two roots and we wish to count all the integer values between these roots. So we have: ... from math import sqrt, ceil, floor def parse_nums(line: str) -> list[int]: # Name: A B C ... return int(line.split(": ")[1].replace(' ', '')) def count_wins(time: int, distance: int) -> int: distance += 1 discriminant = time ** 2 - 4 * distance sqrt_discriminant = sqrt(discriminant) upper_root = (time + sqrt_discriminant) / 2 lower_root = (time - sqrt_discriminant) / 2 # Get number of integers in the range [lower_root, upper_root]: return floor(upper_root) - ceil(lower_root) + 1 def total_possibilities(lines: Iterable[str]) -> int: # No need for the tuple function: return count_wins(*map(parse_nums, lines)) ... ```
{ "domain": "codereview.stackexchange", "id": 45332, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
rust, macros Title: Custom derive macro to create getters and setters Question: To learn how custom derive macros work in Rust, I decided to create a simple derive macro to provide getters and setters for a given struct. It would be used like this: #[derive(GetSet)] pub struct Example { #[get] #[set] field1: String, #[get] field2: i32, } However, there are some things that feel wrong to me about it: The code uses both proc_macro and proc_macro2, is this necessary? Currently, every getter / setter is in their own impl block. But the quote! macro requires code that is well-formed regarding braces, so I think I cannot create impl #name { first and fill in the methods afterwards. Is there a better way? The function identifiers are created with format!, is this okay? Would it be possible to adapt it so one could just write #[get, set] field: (), instead of #[get] #[set] field: (), Apart from that, what else would you improve or change? Here is the code: use proc_macro::TokenStream; use proc_macro2::{Ident, Span}; use quote::quote; use syn::{Data, DeriveInput}; #[proc_macro_derive(GetSet, attributes(get, set))] pub fn get_set_derive(input: TokenStream) -> TokenStream { let ast: DeriveInput = syn::parse(input).unwrap(); let mut gen = proc_macro2::TokenStream::new(); let name = &ast.ident; let data = &ast.data; if let Data::Struct(data_struct) = data { let fields = &data_struct.fields; for field in fields { let field_name = field .ident .as_ref() .expect("struct idents are required for this to work!"); let field_type = &field.ty; for attr in &field.attrs { let path = attr.path(); if path.is_ident("get") { let fn_ident = Ident::new(&format!("get_{field_name}"), Span::call_site());
{ "domain": "codereview.stackexchange", "id": 45333, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, macros", "url": null }
rust, macros let getter = quote! { impl #name { pub fn #fn_ident(&self) -> &#field_type { &self.#field_name } } }; gen.extend(getter); } if path.is_ident("set") { let fn_ident = Ident::new(&format!("set_{field_name}"), Span::call_site()); let setter = quote! { impl #name { pub fn #fn_ident(&mut self, new: #field_type) { self.#field_name = new; } } }; gen.extend(setter); } } } } else { panic!("no support for enums or unions!") } gen.into() } Answer: The code uses both proc_macro and proc_macro2, is this necessary? This is normal. proc_macro is the compiler API stub, only available to proc-macro crates, and proc_macro2 is a plain library that doesn't depend on the compiler proc macro API. It's possible to write a proc-macro crate that doesn't depend on proc_macro2 at all, but then you'd also need to avoid using syn and quote, or any other proc-macro utility libraries — they all depend on proc_macro2, precisely because without it there's no way to manipulate tokens in library code (as opposed to proc-macro crate code). Currently, every getter / setter is in their own impl block. But the quote! macro requires code that is well-formed regarding braces, so I think I cannot create impl #name { first and fill in the methods afterwards. You can use an iterator or collection in quote! to assemble the complete structure at once. let mut functions: Vec<proc_macro2::TokenStream> = Vec::new(); // ... gather functions into vector ...
{ "domain": "codereview.stackexchange", "id": 45333, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, macros", "url": null }
rust, macros // ... gather functions into vector ... // this is the entire output of the derive (no `gen` stream) quote! { impl #name { #( #functions )* } } The function identifiers are created with format!, is this okay? Yes. Would it be possible to adapt it … No, the syntax of attributes does not allow #[foo, bar]. You have to pick one name for the attribute, but it can have parameters: #[getset(get, set)]. Apart from that, what else would you improve or change? It looks pretty good. You asked the right questions and I can't think of more things to change.
{ "domain": "codereview.stackexchange", "id": 45333, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, macros", "url": null }
c++, beginner, number-guessing-game Title: Learn.cpp chapter 8 exercise add error handling to the high low game Question: I did the exercise of LearnCpp.com's Chapter 8 summary and quiz and I'm still learning… Question #3 Implement a game of hi-lo. First, your program should pick a random integer between 1 and 100. The user is given 7 tries to guess the number. If the user does not guess the correct number, the program should tell them whether they guessed too high or too low. If the user guesses the right number, the program should tell them they won. If they run out of guesses, the program should tell them they lost, and what the correct number is. At the end of the game, the user should be asked if they want to play again. If the user doesn’t enter ‘y’ or ‘n’, ask them again. For this quiz, assume the user enters a valid number. #include <iostream> #include "Random.h" void ignoreChar() { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } int randNum() { std::mt19937_64 rd{std::random_device{}()}; std::uniform_int_distribution num{1, 100}; return num(rd); } bool tryAgain(char guess) { switch (guess) { case 'y': return true; case 'n': return false; // Add a return statement for the "n" case default: return false; } } void guessNumber(int userGuess, int actualTarget) { if (userGuess > actualTarget) { std::cout << "Your guess is too high."; } else if (userGuess < actualTarget) { std::cout << "Your guess is too low."; } else if (userGuess == actualTarget) { std::cout << "Correct! You win!"; } } void loopFunction(int input, int target, int guess) { while (input <= 7) { std::cout << "\nGuess #" << input << ": "; std::cin >> guess; guessNumber(guess, target); ++input; if (guess == target) { break; } } }
{ "domain": "codereview.stackexchange", "id": 45334, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, number-guessing-game", "url": null }
c++, beginner, number-guessing-game int main() { int target = randNum(); char typeNow{}; int guess{}; int input{1}; std::cout << "Let's play a game. I'm thinking of a number between 1 and 100. You have 7 tries so guess what it is.\n"; loopFunction(input, target, guess); do { if (guess != target) { std::cout << "\nSorry, you lose. The correct number was " << target; } std::cout << "\nWould you like to play again (y/n)? "; std::cin >> typeNow; ignoreChar(); if (typeNow == 'y') { input = 1; target = randNum(); guess = 0; std::cout << "\nLet's play a game. I'm thinking of a number between 1 and 100. You have 7 tries so guess what it is.\n"; loopFunction(input, target, guess); } } while (typeNow == 'y'); std::cout << "\nThank you for playing."; return 0; } Is the code redundant? What are the changes I should make? Answer: Overview Very good. You can simplify your loops a bit in a couple of places. You have not really implemented error handling! What happens if I type "Bob" when the code is here: std::cin >> guess; That will set the std::cin into an error state and you will never exit. When you are epxecting things other than a string you should always check that the read worked. if (std::cin >> guess) { // User has input a valid number. // Add code to handle good user input guessNumber(guess, target); } else { // User has input bad input (not an integer) // The stream is in a bad state. Any subsequent // attempt to read will no fail until you reset // the stream std::cout << "Bad Input. Ignoring text to end of line\n"; ignoreChar(); } You don't implement this part of the code ocrrectly: At the end of the game, the user should be asked if they want to play again. If the user doesn’t enter ‘y’ or ‘n’, ask them again.
{ "domain": "codereview.stackexchange", "id": 45334, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, number-guessing-game", "url": null }
c++, beginner, number-guessing-game If they enter 'k' it behaves like you entered an 'n'. The definition says you should ask them again for the input. Codereview Assuming nothing important in here that needs reviewing? #include "Random.h" OK. void ignoreChar() { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } The object of type std::mt19937_64 is quite expensive to build. You don't need to re-build it every time you want a random number. int randNum() { std::mt19937_64 rd{std::random_device{}()}; std::uniform_int_distribution num{1, 100}; return num(rd); } Here I would make rd and num static members of the funciton. This means they will be created once and re-used every time the function is entered. int randNum() { static std::mt19937_64 rd{std::random_device{}()}; static std::uniform_int_distribution num{1, 100}; return num(rd); } A switch is good when you have lots of choices. Personally it seems overkill for two. bool tryAgain(char guess) { switch (guess) { case 'y': return true; case 'n': return false; // Add a return statement for the "n" case default: return false; } } Personally if I was using the switch. I would treat 'y' and 'Y' the same way. Also you can't tell the difference between an 'n' and an illegal value. I think that would be important especially in a situation where you are adding code to handle error situations. You print out you win. void guessNumber(int userGuess, int actualTarget) { if (userGuess > actualTarget) { std::cout << "Your guess is too high."; } else if (userGuess < actualTarget) { std::cout << "Your guess is too low."; } else if (userGuess == actualTarget) { std::cout << "Correct! You win!"; } }
{ "domain": "codereview.stackexchange", "id": 45334, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, number-guessing-game", "url": null }
c++, beginner, number-guessing-game But don't you want to keep track of the fact that you won or that you are continuing? Seems like a grat function to return true from when the player wins a game. Looking at the next function loopFunction() it seems like you are doing the same test all over again. You could simply use the result of this function to break out of the loop. Also I don't see a test for loosing. You only have 7 chances you should probably say you loose of you run out of chances. The while() loop here looks like it could be simplified into a for() loop. void loopFunction(int input, int target, int guess) { while (input <= 7) { std::cout << "\nGuess #" << input << ": "; std::cin >> guess; guessNumber(guess, target); ++input; if (guess == target) { break; } } } Looks. good. But one thing is that if you do things multiple times it can be make you life simpler if you put that in a function or variable. Here you print out the string "Let's play a game. I'm thinking of a number between 1 and 100. You have 7 tries so guess what it is." multiple times. Put that text into a variable so it can be re-used. That way if in the future you need to change the text you only need to change the text in one place. I also thing you can simplify the loop in main. you repeat the same code before the loop and inside the loop (when the user selects 'y'). Could you not simply do that at the beignning of the loop and break out if they enter 'n' at the end of the loop. int main() { int target = randNum(); char typeNow{}; int guess{}; int input{1}; std::cout << "Let's play a game. I'm thinking of a number between 1 and 100. You have 7 tries so guess what it is.\n"; loopFunction(input, target, guess);
{ "domain": "codereview.stackexchange", "id": 45334, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, number-guessing-game", "url": null }
c++, beginner, number-guessing-game loopFunction(input, target, guess); do { if (guess != target) { std::cout << "\nSorry, you lose. The correct number was " << target; } std::cout << "\nWould you like to play again (y/n)? "; std::cin >> typeNow; ignoreChar(); if (typeNow == 'y') { input = 1; target = randNum(); guess = 0; std::cout << "\nLet's play a game. I'm thinking of a number between 1 and 100. You have 7 tries so guess what it is.\n"; loopFunction(input, target, guess); } } while (typeNow == 'y'); std::cout << "\nThank you for playing."; return 0; }
{ "domain": "codereview.stackexchange", "id": 45334, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, beginner, number-guessing-game", "url": null }
object-oriented, game, c++17, cmake Title: Othello (Reversi) in C++17 and CMake Question: Othello is a two-player strategy game typically played over the board. I implemented Othello in C++17 with CMake as the build system. I'm looking for feedback on cleanness, readability, and extensibility, in addition to the quality of the C++ (are there certain features I could have taken advantage of / are there features that I used inappropriately?). Here is the project structure: Othello │ ├── cmake-build-debug │ ├── src │ ├── Controller │ │ ├── Controller.cpp │ │ └── Controller.h │ ├── Model │ │ ├── Model.cpp │ │ ├── Model.h │ │ ├── Player.cpp │ │ ├── Player.h │ │ └── Utility.h │ └── View │ ├── StandardView.cpp │ └── StandardView.h │ ├── main.cpp ├── CMakeLists.txt └── test Here are the source files: main.cpp #include <iostream> #include "Controller/Controller.h" int main() { Othello::Controller othello; othello.SetUpGame(); othello.PlayGame(); return 0; } Controller Controller.h #ifndef OTHELLO_CONTROLLER_H #define OTHELLO_CONTROLLER_H #include "../View/StandardView.h" #include "../Model/Model.h" namespace Othello { class Controller { public: Controller(); void SetUpGame(); void PlayGame(); private: Model* model_; StandardView* view_; void EnactMove(Move move); }; } #endif //OTHELLO_CONTROLLER_H Controller.cpp #include "Controller.h" void Othello::Controller::SetUpGame() { // Get size of the board and player names int board_size = Othello::StandardView::GetBoardSize(); auto [black_name, white_name] = Othello::StandardView::GetPlayerNames(); // Create the board and players model_->Init(board_size, black_name, white_name); // Set up the board with the usual configuration int center_row = board_size / 2 - 1; int center_col = center_row;
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake Coordinate top_left = {center_row, center_col}; Coordinate top_right = {center_row, center_col + 1}; Coordinate bottom_left = {center_row + 1, center_col}; Coordinate bottom_right = {center_row + 1, center_col + 1}; model_->AddPiece(top_left, WHITE); model_->AddPiece(top_right, BLACK); model_->AddPiece(bottom_left, BLACK); model_->AddPiece(bottom_right, WHITE); view_->PrintBoard(model_); } void Othello::Controller::PlayGame() { // Game ends when neither player can make a move while (!model_->IsGameOver()) { // Check if active player can make a move // If not, skip turn if (!model_->TurnValid()) { model_->ChangeTurn(); continue; } // If active player cannot move, turn is skipped auto move = view_->GetMove(model_); // We need to use the model to check if move is valid this->EnactMove(move); model_->ChangeTurn(); } // view_.DeclareWinner(model_.GetWinner()); } void Othello::Controller::EnactMove(Move move) { auto [coordinate, color] = move; model_->AddPiece(coordinate, color); auto tiles_flipped = model_->GetTilesFlipped(move); for (auto& tile : tiles_flipped) { model_->InvertCell(tile); } } Othello::Controller::Controller() { model_ = new Model(); view_ = new StandardView(); } Model Model.h #ifndef OTHELLO_MODEL_H #define OTHELLO_MODEL_H #include "Player.h" namespace Othello { class Model { public: Model(); void Init(int board_size, std::string black_name, std::string white_name); // Board editing utility void AddPiece(Coordinate coordinate, Color color); void InvertCell(Coordinate coordinate);
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake // Getters & commonly used board state Color GetCellColor(Coordinate coordinate) const; int GetBoardSize() const; bool IsGameOver() const; bool CanMove(Player* player) const; bool IsValidMove(Move move) const; bool TurnValid() const; std::vector<Coordinate> GetTilesFlipped(Move move) const; // Active Player Methods Color GetActiveColor() const; std::string GetActiveName() const; void ChangeTurn(); private: Player* black_; Player* white_; std::vector<std::vector<Cell>> board_; int board_size_; Player* active_player_; bool Inbounds(int coordinate) const; }; } #endif //OTHELLO_MODEL_H Model.cpp #include "Model.h" #include <utility> Othello::Model::Model() : board_(0) {} void Othello::Model::AddPiece(Coordinate coordinate, Color color) { auto [row, column] = coordinate; auto& cell = board_.at(row).at(column); if (cell.color != EMPTY) { throw std::logic_error("You are trying to add a piece to a square that already has one."); } cell.color = color; } void Othello::Model::InvertCell(Coordinate coordinate) { auto [row, column] = coordinate; auto& cell = board_.at(row).at(column); Color curr_color = cell.color; if (curr_color == EMPTY) { throw std::logic_error("You are trying to invert a cell that is empty."); } else { Color new_color = (curr_color == BLACK) ? WHITE : BLACK; cell.color = new_color; } } void Othello::Model::Init(int board_size, std::string black_name, std::string white_name) { black_ = new Player(std::move(black_name), BLACK); white_ = new Player(std::move(white_name), WHITE); board_ = std::vector<std::vector<Cell>>(board_size, std::vector<Cell>(board_size)); board_size_ = board_size; active_player_ = black_; // BLACK goes first by default }
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake Color Othello::Model::GetCellColor(Coordinate coordinate) const { auto [row, column] = coordinate; auto cell = board_.at(row).at(column); return cell.color; } int Othello::Model::GetBoardSize() const { return board_size_; } bool Othello::Model::IsGameOver() const { return !CanMove(black_) && !CanMove(white_); } bool Othello::Model::CanMove(Othello::Player *player) const { int size = (int)board_.size(); for (int row = 0; row < size; row++) { for (int column = 0; column < size; column++) { // If the cell is occupied, skip if (GetCellColor({row, column}) != EMPTY) continue; // From this cell, check in all directions Move move = {row, column, player->GetPlayerColor()}; if (!GetTilesFlipped(move).empty()) { return true; } } } return false; } bool Othello::Model::TurnValid() const{ return CanMove(active_player_); } bool Othello::Model::IsValidMove(Move move) const { return !GetTilesFlipped(move).empty(); } std::vector<Coordinate> Othello::Model::GetTilesFlipped(Move move) const { auto [coordinate, same_color] = move; auto [start_row, start_column] = coordinate; Color alt_color = (same_color == BLACK) ? WHITE : BLACK; std::vector<Coordinate> directions = { {0, 1}, // Horizontal {1, 0}, // Vertical {1, 1}, // Right Diagonal {1, -1} // Left Diagonal }; // offset for forward and backwards pass std::vector<int> offsets = { -1, // Backward Pass 1 // Forward Pass }; std::vector<Coordinate> tiles_flipped; for (auto& direction : directions) { // for each direction, we perform a forward and backward pass for (auto offset : offsets) { auto [row_activated, column_activated] = direction;
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake // We collect all alternate-color pieces std::vector<Coordinate> potential_tiles_flipped; // neat trick for combining forward and backward passes into one loop int row_offset = offset * row_activated; int column_offset = offset * column_activated; int row = start_row + row_offset; int column = start_column + column_offset; // we add the potential tiles flipped once we encounter a tile of the same color bool completed_flip = false; // flip check loop while (Inbounds(row) && Inbounds(column)) { auto cell_color = GetCellColor({row, column}); if (cell_color == alt_color) { potential_tiles_flipped.push_back({row, column}); } else if (cell_color == same_color) { completed_flip = true; break; } else { completed_flip = false; break; } // update offset += offset; row_offset = offset * row_activated; column_offset = offset * column_activated; row = start_row + row_offset; column = start_column + column_offset; } if (completed_flip) { // flip all intermediate tiles if flip is completed tiles_flipped.insert(tiles_flipped.end(), potential_tiles_flipped.begin(), potential_tiles_flipped.end()); } } } return tiles_flipped; } void Othello::Model::ChangeTurn() { bool is_black = (active_player_ == black_); active_player_ = (is_black) ? white_ : black_; } bool Othello::Model::Inbounds(int coordinate) const { return (coordinate >= 0) && (coordinate < board_size_); }
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake Color Othello::Model::GetActiveColor() const { return active_player_->GetPlayerColor(); } std::string Othello::Model::GetActiveName() const { return active_player_->GetName(); } Player.h #ifndef OTHELLO_PLAYER_H #define OTHELLO_PLAYER_H #include <string> #include "Utility.h" namespace Othello { class Player { public: Player(std::string name, Color color); std::string GetName(); Color GetPlayerColor(); private: std::string name_; Color color_; }; } #endif //OTHELLO_PLAYER_H Player.cpp #include "Player.h" #include <utility> using std::vector; Othello::Player::Player(std::string name, Color color) : name_(std::move(name)), color_(color) { } std::string Othello::Player::GetName() { return name_; } Color Othello::Player::GetPlayerColor() { return color_; } Utility.h #ifndef OTHELLO_UTILITY_H #define OTHELLO_UTILITY_H #include "Player.h" enum Color { EMPTY, BLACK, WHITE }; inline std::string ToString(Color color) { switch (color) { case EMPTY: return "empty"; case BLACK: return "black"; case WHITE: return "white"; } } struct Coordinate { int row; int column; }; struct Cell { Coordinate coordinate; Color color; }; struct Move { Coordinate coordinate; Color color; }; #endif //OTHELLO_UTILITY_H View StandardView.h #ifndef OTHELLO_STANDARDVIEW_H #define OTHELLO_STANDARDVIEW_H #include <utility> #include <string> #include "../Model/Model.h" namespace Othello { class StandardView { public: StandardView() = default; // Input methods static int GetBoardSize(); static std::pair<std::string, std::string> GetPlayerNames(); // Output methods void PrintBoard(Model *model) ; Move GetMove(Othello::Model *model); }; } #endif //OTHELLO_STANDARDVIEW_H StandardView.cpp #include "StandardView.h" #include <iostream>
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake #endif //OTHELLO_STANDARDVIEW_H StandardView.cpp #include "StandardView.h" #include <iostream> using std::cout, std::cin, std::string, std::pair; int Othello::StandardView::GetBoardSize() { // TODO: Add validation for an even board size int board_size; std::cout << "Enter an even board size: \n"; std::cin >> board_size; return board_size; } pair<std::string, std::string> Othello::StandardView::GetPlayerNames() { string black_name, white_name; cout << "Enter the name of player with the black pieces: \n"; cin >> black_name; cout << "Enter the name of player with the white pieces: \n"; cin >> white_name; return {black_name, white_name}; } // Design taken from Code Review Stack Exchange // https://codereview.stackexchange.com/questions/51716/shortest-possible-way-of-printing-a-specific-board void Othello::StandardView::PrintBoard(Model *model) { int size = model->GetBoardSize(); string letter_bar, decoration_bar; // We want to pad each line with a consistent amount of spaces int total_padding = (int)log10(size); // Construct letter bar for (int _ = 0; _ < total_padding; _++) { letter_bar += " "; } for (char letter = 'a'; (int)letter < 'a' + size; letter++) { letter_bar += letter; letter_bar += " "; } // Construct decoration bar for (int _ = 0; _ < total_padding; _++) { decoration_bar += " "; } decoration_bar += "+"; for (int _ = 0; _ < size; _++) { decoration_bar += "--"; } decoration_bar += "--+";
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake // Print board cout << " " << letter_bar << '\n'; cout << " " << decoration_bar << '\n'; for (int row = 0; row < size; row++) { int num_digits = (int)log10(row + 1); for (int _ = 0; _ < total_padding - num_digits; _++) { cout << " "; } cout << row + 1 << "| "; for (int column = 0; column < size; column++) { Color color = model->GetCellColor({row, column}); switch (color) { case BLACK: std::cout << 'B'; break; case WHITE: std::cout << 'W'; break; case EMPTY: std::cout << ' '; break; default: throw std::logic_error("Cell has not been initialized."); } cout << " "; } std::cout << " |\n"; } cout << " " << decoration_bar << '\n'; } Move Othello::StandardView::GetMove(Othello::Model *model) { Move move{0}; do { PrintBoard(model); auto color = model->GetActiveColor(); auto name = model->GetActiveName(); cout << "It's your move " << name << ".\n"; cout << "You have the " << ToString(color) << " pieces.\n"; cout << "Enter move as space separated row number and column character\n"; cout << "Ex. 1 a\n"; int raw_row; char raw_col; // add some validation here later cin >> raw_row >> raw_col; int row = raw_row - 1; int column = tolower(raw_col)-'a'; move = {row, column, color}; } while (!model->IsValidMove(move)); return move; } CMakeLists.txt cmake_minimum_required(VERSION 3.25) project(Othello) set(CMAKE_CXX_STANDARD 17)
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake CMakeLists.txt cmake_minimum_required(VERSION 3.25) project(Othello) set(CMAKE_CXX_STANDARD 17) add_executable(Othello src/main.cpp src/Controller/Controller.cpp src/Controller/Controller.h src/View/StandardView.cpp src/View/StandardView.h src/Model/Player.cpp src/Model/Player.h src/Model/Model.cpp src/Model/Model.h src/Model/Utility.h) Answer: Project layout I don’t do CMake if I can avoid it, so I won’t comment on that stuff. I’ll first suggest that your main.cpp should probably be in src… which is where it seems to be according to CMakeLists.txt, but not according to the illustration. So, maybe the illustration is wrong? Now, as for tests, you really should have them, and it looks like you’ve at least given that a thought, judging by the existence of the test directory. However: The directory is typically named tests (note the plural) for technical reasons (test is a standard POSIX utility). That directory is typically for functional testing, or maybe integration testing, not unit testing. For unit tests, the best recommendation I’ve seen—and the one I always use—is to include the unit tests alongside the units. So for a single logical module, you’d have Player.hpp (the interface), Player.cpp (the implementation), and Player.test.cpp (the unit tests), all together, side-by-side in the same directory. I don’t know how well this works with CMake.
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake High-level design Using a model-view-controller pattern is all fine and good but… you know, you don’t actually need to explicitly use the names of the design pattern elements. This is especially true when the pattern names don’t really make sense in the practical context. Put another way: You are not making an abstract software “thing”, you are making a game. And games have specific terminology and structure that all game developers understand. Even if a game’s renderer is technically the “view” in the MVC pattern, in the context of games we usually refer to it as the “renderer”. Design patterns are for understanding and communicating software structure; they are not meant to be explicitly implemented, so don’t be a slave to them. And to make that point even more emphatically: I don’t think you’ve implemented the model-view-controller pattern properly. In a game, the “controller” is not the game… it’s just the input to the game. And your view is actually acting partly as a view, and partly as a controller. It’s all muddled. In the MVC pattern, the model is the “thing” that holds all the data and business logic; the view is the way the model passes information to the user, and the controller is the way the user passes information to the model. The point of the MVC pattern is the view and controller abstract away that information exchange between the model and user, so you can change the way the user interacts with the model without changing the model.
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake If you imagine a physical console game system, the model is the game itself, the controller is the controller (the thing you hold and push buttons on to control the game), and the view is the screen. The idea of the MVC system is that you can swap out different controllers—you can change between game pad, keyboard-and-mouse, touchscreen, etc.—to change the way you control the game, but the game itself doesn’t change. Similarly, you can change the display—you can view it via a big-screen TV, a small tablet display, or a VR headset—to change the way you view the game, but again, the game remains unchanged. So it doesn’t really make sense for the controller to set up a game. And you don’t play a controller, you play a game. So the methods SetUpGame() and PlayGame() don’t really make sense for the controller. For a game like Othello, pretty much the only thing you need to do to control the game is “get move”, to get the \$x\$ and \$y\$ coordinates of the square to place a piece in. You do have this method… but it’s in the view component. For your specific implementation, you have a couple more things that you need from the controller. You need it to get the board size, and the player name… again, both of which are currently in the view. Basically, any input you need from the player to control the game should come from the controller… not the view, and not the model. But note: it should not be “get player nameS (plural)”, it should be “get player name (singular)”, because each player should have their own controller. Each player should also have their own view. The standard game loop is, very basically: while (not done) { input(); // Process the player(s) input(s) update(); // Update the game state render(); // Display the game state }
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake Using MVC terms: auto game = model{}; while (not game.done) { for (auto&& player : game.players) game.process_input(player.controller.get_input()); game.update(); for (auto&& player : game.players) player.view.render(game.state()); } That’s more for a real-time game where all players can act at any time. For a turn-based game like Othello, you might want something more like: // Probably makes more sense to call it "game" rather than "model": auto model::play() { while (not done) { // Probably makes more sense to just do stuff like: // current_player.get_move() // rather than: // current_player.controller.get_move() // but I'm illustrating the pattern. auto move = current_player.controller.get_move(); update(move); for (auto&& player : players) player.view.render(state); } }
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake for (auto&& player : players) player.view.render(state); } } All you need is a brief section before the loop to get the board size and player name(s), and that’s basically your game. Or, you could integrate the game setup into the game loop, by getting general “input” rather than specifically moves. So the model is the game; the model class should probably be called game or othello. Each player gets their own controller and view to interact with the model. For maximum flexibility, you probably want the player to be an abstract class. That way you can support local human players (using standard input and output), online human players (using a network connection to get the game state and submit moves), AI players, and maybe more. The controller and view should both be abstract base classes as well. That way, even if you only have a local human player, you can support console input and output (std::cin and std::cout), a graphical interface (using a mouse or touch to get moves), etc.. Code review Generally, the code is nice and well-structured. (Though, I’m not a fan of indenting code at namespace scope. EVERYTHING is (or should be) in a namespace, so if you indent at namespace scope, you just waste 4+ columns of horizontal space for no good reason.) I’m not going to do an ordered, line-by-line review because there is so much code, and I’ll be mixing design suggestions along with actual code structure suggestions. So, let’s dive in. Let’s start at the highest level: the main function: int main() { Othello::Controller othello; othello.SetUpGame(); othello.PlayGame(); return 0; }
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake So, first, Othello::Controller isn’t really a great name for what you’re making (setting aside the fact that it’s also logically incorrect). You’re supposed to be constructing a game, right? Not a controller (or model). I would think that, in practice, anyone constructing an instance is not interested in the design pattern being used; they just want to make a game. So it would make more sense for the type to be named game or othello or othello::game or something like that. Now, I have to ask: will there ever be a situation where someone would want to set up a game, and not play it? Or, more interestingly, will there ever be a situation where someone would want to play a game without first setting it up? No? Then why not just have a single function that does all the set up and plays the game? Types should be easy to use, and hard—if not impossible—to misuse. Any time your interface has a set of functions that must all be called in a certain sequence… why put that responsibility on the user? Why not just do all the work internally, and only a expose a single function that does the whole sequence? Consider std::string. When you assign an array of characters to a std::string, it has to free its current data, allocate new memory for the new data, then copy the data into that memory. So basically, this: auto str = std::string{}; str.free_current_memory(); str.allocate_new_memory(std::strlen("hello")); str.copy_characters_into_memory("hello"); Now, imagine what a nightmare it would be to have to write the above code every time you want to assign new data to a std::string, instead of just: auto str = std::string{}; str.assign("hello"); or: auto str = std::string{}; str = "hello"; or even just: auto str = std::string{"hello"}; Looking at the code for your class, I see: Othello::Controller othello; othello.SetUpGame(); othello.PlayGame();
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake and I ask, why not: // Set up is either done in the constructor, or at the start of PlayGame() Othello::Controller othello; othello.PlayGame(); Now, regarding std::string you can do: auto str = std::string{}; str.clear(); str.reserve(std::strlen("hello")); str.assign("hello");
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake Which is basically the same as the nightmare code above. std::string does give you that level of control, and you may make the case that you want that level of control for your game class: there may be cases where you want to set up the game separately from playing it, maybe to do something else in between. But here is the really, really important point about that: std::string does gives you that level of control… if you want to use it. And here’s the second really, really important point about that: no matter what you do, no matter what order you call those functions in, no matter if you forget one or two… everything always still works. What I’m saying is: If your class requires calling certain functions and/or requires calling functions in a certain order… then your class is broken. So rather than requiring the user to call “setup” then “play”… it should just work with “play”, doing the setup implicitly and automatically. And if you want to have separation between “setup” and “play” (and you shouldn’t; more on that in a moment), then everything should still work if the user forgets to call “setup”, or calls it multiple times, or whatever. So you just need a “play” function for the game class. You could make a separate “setup” function… but I would suggest not. Because the more crap you add to an interface, the more you have to test. And you should test your code. If you just a “play” function, you just have one function to test. But the moment you add a separate “setup” function… now you have two functions to test… and you need to test the interaction between those two functions (“What happens if you forget to call ‘setup’ before ‘play’?” “What happens if you call ‘setup’ multiple times before ‘play’?” “What happens if you call ‘setup’ but don’t call ‘play’?”). So don’t complicate the interface without a damn good reason. All you need is “play”.
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake So this is what I’d suggest your main function should look like (roughly; never mind the style choices like trailing return and AAA): auto main() -> int { auto game = othello::game{}; game.play(); }
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake I’m going to skip to the model class… which should be the game class (not controller). Let’s start by looking at the data members: Player* black_; Player* white_; std::vector<std::vector<Cell>> board_; int board_size_; Player* active_player_;
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake You have 3 naked pointers there. 2 of them are owning, 1 is not. All of this is very bad. Let’s start with the owning pointers. Using naked pointers for ownership is completely unacceptable in modern C++. There is just no excuse for it anymore. You should be using smart pointers. And, if you had used smart pointers—and particularly if you used the correct smart pointer std::unique_ptr—then you would have avoided several rather massive bugs that exist in your code. Bug #1: Your code leaks. You use new, but there is not a single delete anywhere in your code. At the very least, Model should have a destructor to free the memory you allocated with the new calls. But even a destructor would not be enough because: Bug #2: Your Model class automatically gets copy operations, which will just copy those raw pointers. Which means if you just naïvely delete them, you’ll probably end up with a double delete, and a crash. So Model should also have a copy constructor and copy assignment operator… and probably move constructor and move assignment as well. All of those bugs and all of that extra work magically goes away if you just replace those naked pointers with std::unique_ptr<Player>. This is why smart pointers are not optional in modern C++. If you are not using smart pointers, your code is not acceptable in any modern C++ project. Now, what about that third pointer, the non-owning one.
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake Now, what about that third pointer, the non-owning one. This isn’t technically a problem, in that it isn’t actively creating bugs. But it’s still not great. The problem is that you’ve coupled two (or three) data members together. If ever you change the player (either one!), then you must remember to change the active player pointer, too. Right now, you change them all together, which is good. But this is brittle. If your game gets more complex… like, say, maybe you make it possible to change players mid-game (if a player disconnects and reconnects, or maybe they have to quit but what to hand the game over to someone who will finish it for them, or whatever)… then you have to be very careful to remember to keep all the pointers in sync. Let offer an alternative design. Right now you are hard-coding two players, and hard-coding them as separate data members. What if, instead, you coded the players like this: class Model { // ... [snip] ...
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake std::array<std::unique_ptr<Player>, 2> players_ = {}; std::size_t active_player_index_ = {} // ... [snip] ... }; Couple things to note: It is now trivially possible to add more players. Just change the size of the array, or replace it with a vector to have a dynamically-adjustable number of players. Even if you say you will never, ever have more than two players, coding them like this makes other places in the code simpler. For example, look at your ChangeTurn() function. With the structure above, that becomes a one-liner: active_player_index_ = (++active_player_index_) % players_.size();. By using an index to keep track of the active player, you are now free from worry about pointers going stale. Last thing to note about those pointers… do they need to be pointers? I mean, yes, if you were using polymorphism with an abstract player base class, then sure, pointers would make sense. But… you’re not. There is no reason to hold pointers to players when you could just as well hold the players directly. In other words: class Model { // ... [snip] ... std::array<Player, 2> players_ = {}; std::size_t active_player_index_ = {} // ... [snip] ... }; Now let’s look at the board itself: std::vector<std::vector<Cell>> board_; This is a bad pattern; you (almost) never want vectors of vectors. What you want is a 2D array, right? The way to do that is to use a flat array, and calculate the indices. In other words, to get a 8×10 array, you would do: auto board = std::vector<Cell>(8 * 10); // I want to access cell (3, 5): board[(3 * 8) + 5].color = black; In C++23, we get std::mdspan to make this easier: auto board = std::vector<Cell>(8 * 10); auto board_view = std::mdspan{board.data(), 8, 10}; // I want to access cell (3, 5): board_view[3, 5].color = black; Because your board is always square, you can just store a single extent, like you’re doing now: class Model { // ... [snip] ...
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake std::vector<Cell> board_ = {}; int board_size_ = {}; // ... [snip] ... }; auto Model::AddPiece(Coordinate coordinate, Color color) { auto const board_view = std::mdspan{board_.data(), board_size_, board_size_}; auto const [row, column] = coordinate; if (board_view[row, column].color != EMPTY) throw std::logic_error{"You are trying to add a piece to a square that already has one."}; board_view[row, column].color = color; } And you can always assert that board_.size() == std::pow(board_size, 2);. (Or you can allow for non-square boards by including an extents object directly. In fact, you could even theoretically allow for 3D or higher dimensional boards. Once you avoid hard-coding assumptions into the code, a lot of amazing things become possible, even if you never take advantage of them.) The rest of the member functions in Model are okay, but I would ask if they are necessary. The reason you need them now is because you’ve split the model logic across the view and controller objects, but if all the model logic was contained in Model, then you wouldn’t need all those manual operations to be public. The only public function Model would need is a “play game” function (the one that is currently in Controller, basically). The fewer functions in the public interface the better, because then there is no need to test them. So, the minimum interface for Model (which, again, should probably be called Game or Othello) is: class Model { public: // Creates a new Othello game with the given players: template <std::ranges::input_range R> requires std::convertible_to<std::ranges::range_value_t<R>, Player*> explicit Model(R&& players); // Or if you want to hard-code it to just two players: Model(Player*, Player*); // Play the game! auto play() -> void; };
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake // Play the game! auto play() -> void; }; Which you’d use like: // Player is an abstract base class. StdioPlayer is a player that uses // std::cin for its controller, and std::cout for its view. class StdioPlayer : public Player { // ... }; auto main() -> int { // Set up the players auto const player_1 = std::make_unique<StdioPlayer>(); auto const player_2 = std::make_unique<StdioPlayer>(); // Play the game! auto othello = Othello::Game{player_1.get(), player_2.get()}; othello.play(); } Which is an interface that is both simple, and extremely hard to misuse. Okay, on to the Player class. Currently, you’re just using the player class to hold information about the player—their name and piece colour. You are not using the player class to be the player. The player class should have a view (to view the state of the model/game) and a controller (to control the state of the model/game). Anything else is gravy. In particular, there’s no harm in storing the player’s name in the player class, because if the player changes their own name… meh. Doesn’t really affect the game. But storing any game state information in the player class is probably not wise. For example, storing the piece colour there is dodgy. What happens if the player changes their own piece colour mid-game? They shouldn’t have that control. It would probably be better to store any game state info connected to a player in the model. The game needs to know what each player’s colour is, after all. Speaking of colour: enum Color { EMPTY, BLACK, WHITE }; inline std::string ToString(Color color) { switch (color) { case EMPTY: return "empty"; case BLACK: return "black"; case WHITE: return "white"; } }
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake First, never use SCREAMING_SNAKE_CASE (aka ALL_CAPS) for anything but macros. Second, you should use modern C++ scoped enums, not C enums. So that should be: enum class Color { empty, black, white }; Third, you have a toString() function to get strings for the enumerators, which is not terrible… but consider that the only place you use it is here: Move Othello::StandardView::GetMove(Othello::Model *model) { // ... [snip] ... cout << "You have the " << ToString(color) << " pieces.\n"; So what you are doing is creating a string for the sole purpose of just printing that string. There is no need for that. You could just do: auto operator<<(std::ostream& out, Color color) -> std::ostream& { switch (color) { case Color::empty: return out << "empty"; case Color::black: return out << "black"; case Color::empty: return out << "white"; } } Move Othello::StandardView::GetMove(Othello::Model *model) { // ... [snip] ... cout << "You have the " << color << " pieces.\n";
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake But the biggest issue is that you have an “empty” enumerator. This is not a good thing. There is no such colour as “empty”. You need it because you are using the colour enumeration for more than just colours; you are also using it to mark the absence of colour. But that’s conceptually nonsensical. A more correct model would have each space on the board holding a std::optional<color>, which logically indicates that each space may be occupied by a colour, or not. But a better idea might be to encode each space with with the player who owns it, rather than the colour, and use some out-of-bounds value, like std::size_t{-1}, to encode a space that is not occupied. If you have the set of players stored as an array or vector of Player, then you can use the indices (or maybe the index plus one, so you get the more natural “player 1”, “player 2”, etc., rather than “player 0”, “player 1”, etc.… and you can use 0 to encode “no player”, which is natural and efficient). Doing it this way will spare a lot of the repetitive trinary checks ((curr_color == BLACK) ? WHITE : BLACK;). But the main point is that if you are creating a class to encode colour, just have it encode colour, not “colour + other info”. When you do need “colour + other info”, then you have options. But if you hack “+ other info” in there from the start, you’re stuck with it even when it doesn’t make sense. For example, in Player you have GetPlayerColor(), which returns a Color. If Color really were just for colours, then GetPlayerColor() could never return an invalid value… but Color is “colour + error state”, which means that every single line of code that uses GetPlayerColor() now needs to check the return to make sure it is not Color::EMPTY. Which defeats the purpose of creating a type specifically for colours. So, back to Player. It should probably not be copyable, because it doesn’t make sense to copy players. So maybe: class Player { public:
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake class Player { public: constexpr explicit Player(std::string name, std::unique_ptr<View> view, std::unique_ptr<Controller> controller) // pre (not name.empty()) // pre (view) // pre (controller) : _name{std::move(name)} , _view{std::move(view)} , _controller{std::move(controller)} {}
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake ~Player() = default; constexpr auto view() & noexcept -> View& { return *_view; } constexpr auto controller() & noexcept -> Controller& { return *_controller; } constexpr auto name() const& noexcept -> std::string const& { return _name; } constexpr auto name() && noexcept -> std::string { return std::move(_name); } // Non-copyable: constexpr Player(Player const&) = delete; constexpr auto operator=(Player const&) -> Player& = delete; // Movable: constexpr Player(Player&&) noexcept = default; constexpr auto operator=(Player&&) noexcept -> Player& = default; private: std::unique_ptr<View> _view = {}; std::unique_ptr<Controller> _controller = {}; std::string _name = {}; }; And the model/game class could hold an array of players plus any extra info like so: class Model { // ... [snip] ... std::array<std::tuple<Player*, Color, /* anything else */>, 2> _players = {}; std::size_t _active_player = {}; };
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake At this point, I saw you’d already accepted an answer, so there’s no point in going further. So, I guess I’ll wrap it up. The key point I wanted to make is that you have not done the model-view-controller pattern properly. In MVC, the model is the core; it is what handles all the data and logic. The view is just a way for users (players) to view the state of the model, and the controller is just a way for users to control the state of the model (by sending commands for what moves to make). The controller should absolutely not be setting up the game, or playing it. Neither should the view be getting moves. Extended with discussion from comments MVC pattern in games So, an important thing to keep in mind is that there is no one true MVC pattern. There are many of versions of MVC. They all have the same basic idea, but they differ wildly in the details. In some versions, the user only interacts with the view, not the controller or the model. In some others, the user only interacts with the controller, not the view or the model. One of the reasons for the many variations of MVC is that MVC is normally applied to GUI applications, and in that context, you can get a little vague about exactly where the components are and how they interact. An app’s GUI can be both view and controller (a checkbox, for example, must both view data in the model and control data in the model). You can say the GUI is the view, and it communicates with the controller when you change something in the GUI. So the pattern looks like this: MODEL ↓ ↖ ↓ CONTROLLER ↓ ↗ VIEW ⇅ USER
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake But that pattern doesn’t really work for games, because a game’s graphics and input systems are totally separate… often literally, being provided by totally different libraries (you may use GameInput for input and Vulkan for graphics, for example). And games are usually designed with the input wholly independent from the graphics, so you can play the same game with a game pad, or keyboard and mouse, or via a touchscreen… sometimes all on the same device. You want a version of MVC that works well for games. And for that, you need to have strict separation between graphics and input, which means strict separation between view and controller. So, this: MODEL ↙ ↖ VIEW CONTROLLER ↘ ↗ USER
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake In my opinion, this is the flavour of MVC that works best for games, but there can still be some variation. For example, you may want to allow the controller to query the view, so that when the user clicks on an interface object, or points at an object in the visual scene, you can get the view/projection matrices and screen coordinates to transform what the user is pointing at back to world space, so you can detect what object they’re selecting. What I’m trying to hammer home is: There is no one true “correct” way to apply MVC to games… but there are ways that work well and ways that don’t work so well, and unfortunately, a lot of MVC literature focuses on GUI applications, which often give flavours of MVC that don’t really work well for games. So the direct answer to your question is: Only the model should be isolated from the user. The view and controller should both be independent, so you can swap out different views (hi-res screen display, low-res phone display, VR headset, etc.) and different controllers (game pad, keyboard/mouse, touch, etc.) independently. As for the second part of the question… again, MVC is just a theoretical pattern, and a vaguely specified one at that, so there is no one true answer about who instantiates what. One possibility is to have the user/player responsible for instantiating the view and controller. In my mind, this works well for client-server model games, which are great for multiplayer. In that flavour, the model is the game server; it handles all the game logic, and keeps all the connected players in sync. Each client/player gets their own view and controller, so they can each have not only different views and input methods, but different types of views and input methods (one might be playing on a touchscreen phone, another with keyboard/mouse on a desktop, etc.).
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake Another flavour would make the model/game responsible for setting up the view and controller. This is how most non-networked games are probably structured. By giving the model/game knowledge of the view and controller, the model/game can optimize its internal logic/calculations for the current view and input method. For example, if the game knows it’s being played on a small screen, it can avoid loading any hi-res models, and only load the low-res stuff. So, the answer to the second part of your question is… dealer’s choice. You have options. As I was writing the main answer, I deliberately varied between different patterns of doing things. You could set up the players before the game.run() function… or you can have the player set up as part of the game.run() function. In a more complicated game, the game.run() function would usually kick off a loop that is controlled by a state machine, where the state determines the current “mode” of the game. So the game might start in the “introduction screen” state, then when conditions are met go to the “player set up” state, then once the players are set up, go to the “play” state, and stay there until the “win” state. And to directly answer the question, you could instantiate the controller (and/or view) in the model (either in the constructor, or at the start of .run()), or in each player (either before instantiating the model entirely, or you could have the players created at the start of .run()). There is no one “true” answer. You’re the engineer of this locomotive; you get to decide how it runs. Sure, there are some patterns that are just… not great; and some patters are generally superior. But once you weed out the really bad designs, you get to a point where there is no clear winner, only trade-offs. Some patterns are better than others for extensibility, but terrible for performance, and vice versa.
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
object-oriented, game, c++17, cmake For example, instantiating the players before the model entirely is probably a great pattern if you are making a collection of games, where the players can set themselves up, then choose to play Othello or chess or whatever. On the other hand, that might mean you need two set-up phases, where first you set up the players (“enter your names!”), then start the game, then set up the players again (“choose your colour!”; and for some games, “choose your starting position!”, and so on). So for a single game, maybe having the model set up the players at the start of .run() is better. As I said: you’re the engineer! And finally, keep in mind that whenever you try to apply theoretical structure to a practical application, you’ll often have to futz things. As they say, theory never survives contact with reality. A “pure” MVC structure is probably not possible. And this is especially true for games, which often do horrific and ugly things for the sake of optimization (and release deadlines). I’ll just straight out and say it: in practice, game programmers are not coders, they are butchers. They are hackers. And they’re often quite proud of that.
{ "domain": "codereview.stackexchange", "id": 45335, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "object-oriented, game, c++17, cmake", "url": null }
performance, c, matrix Title: Transpose matrix in ANSI C Question: Is there a way to transpose a matrix in ANSI C way much better than this ANSI C code? Can I do transpose in a different and faster way? The focus of this aim is: Speed /* * Turn A into transponse A^T * A[row * column] */ void tran(float A[], size_t row, size_t column) { /* Decleration */ float *B = (float*)malloc(row * column * sizeof(float)); float* transpose = NULL; float *ptr_A = A; size_t i, j; for (i = 0; i < row; i++) { transpose = &B[i]; for (j = 0; j < column; j++) { *transpose = *ptr_A; ptr_A++; transpose += row; } } /* Copy! */ memcpy(A, B, row*column*sizeof(float)); /* Free */ free(B); } Answer: Performance To get the best performance on contemporary CPUs you need a very good understanding of the memory and cache systems, the prefetcher, and if vector instructions can be used. The best algorithm to use will also depend on the size of the matrix. There are also some performance issues caused by the language itself, and I recommend you target at least C99 so you can use restrict. You are also creating a temporary matrix and copying it back at the end. This has some overhead that could be avoided in two ways: Don't modify A[] at all, but let the caller supply a B[] where the result will be stored. Modify A[] in-place. This is rather easy for square matrices, but it will quickly become complicated for non-square matrices. Still, you could do the in-place method for square ones and fall back to your original code for non-square ones.
{ "domain": "codereview.stackexchange", "id": 45336, "lm_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, matrix", "url": null }
performance, c, matrix Naming things The names of the function and the variable names could be improved. Most importantly, I would make sure the function is named transpose(). Unnecessary abbreviations can cause confusion later on. The variable transpose must then be renamed of course, at first glance a better name would just be ptr_B. row and column are singular, so it sounds like those are row and column indices, not counts. rows and columns would be better, or if you want to be even more explicit, num_rows and num_columns. Once you have done that, you can rename i and j to row and column. Simplified code The code can be greatly simplified by using C99 and using [] instead of pointer arithmetic: void transpose(const float *restrict input, float *restrict output, size_t num_rows, size_t num_columns) { for (size_t row = 0; row < num_rows; row++) for (size_t column = 0; column < num_columns; column++) output[column * num_rows + row] = input[row * num_columns + column]; } An optimizing compiler will generate similar assembly code for the loop.
{ "domain": "codereview.stackexchange", "id": 45336, "lm_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, matrix", "url": null }
java, reinventing-the-wheel, iteration, loops Title: Calculate the base 10 log with loops in Java without using Math Question: I'm looking for a simple way to calculate the logarithm without using java.lang.Math, just out of interest. Here's my try (I adopted some code parts from this answer): public class Log { public static double log10(int x) { if (x <= 0) { throw new IllegalArgumentException("x must be positive. log_10 not defined for non-positive numbers."); } int a = 0; while (x / 10 > 0) { a++; x /= 10; } double r = a; double frac = 0.5; double x1 = x; for (int i = 0; i < 25; i++) { x1 *= x1; if (x1 > 10) { x1 /= 10; r += frac; } frac /= 2; } return r; } public static void main(final String[] args) { System.out.println(log10(1)); System.out.println(log10(5)); System.out.println(log10(10)); System.out.println(log10(20)); System.out.println(log10(50)); System.out.println(log10(1000)); } } How to choose the number of iterations (here 25)? And in what order should the assignments in the while and if block be written? Both "arrangements" are possible without semantic change. Thanks for a review. Answer: The unchecked IllegalArgumentException is lovely, thank you. Very nice diagnostic error. Referring to the function's name as log_10 seems like a typo. You might consider including the value of x in the message, for the benefit of some poor maintenance engineer chasing down a difficult-to-reproduce bug. obscure comparison while (x / 10 > 0) {
{ "domain": "codereview.stackexchange", "id": 45337, "lm_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, reinventing-the-wheel, iteration, loops", "url": null }
java, reinventing-the-wheel, iteration, loops That seems a slightly cryptic way to communicate Author's Intent. Consider rephrasing as (x >= 10), which I think is what you meant. Alternatively, mention a loop variant in a comment, to emphasize we're predicting the effect of the x /= 10 assignment. meaningful identifiers double r = a; Neither one of these is a great name. And it's unclear why we abandoned a in favor of r. For a local variable to be single letter is not necessarily a problem. But the meaning, and usually the "mental pronunciation", should be clear, e.g. a comment hinting that "the Radix starts out as the Approximation". (No, I don't believe Author intended either of those nouns. IDK, perhaps the Root of some unspecified equation we're solving?) If you had cited a reference, perhaps a wikipedia URL, then the Gentle Reader could come up to speed by tracing that reference's variable names, which you preserved, down into your source code. Absent comments or a cited reference, we likely want more than single-character names for these. OTOH names like x or i are perfect as-is. The frac identifier is well-chosen. extract helper The point of that while loop is to compute very special values of x and of a. Tell us the meaning of those values. You could use a comment, but it would be much better to break out a tiny helper function. It will have an informative name. We can /** document */ its return value(s). We can separately unit test it. magic number ...; i < 25; ... I imagine there's some special relationship between a power of two and a power of ten. But I'm not seeing it. You have to spell it out for us, minimally with a comment, preferably with a helpfully named MANIFEST_CONSTANT. Here's what I see, but it appears to be off by a factor of about a million: $ python -c 'print(f"{2 ** 64}\n{int(1e19)}")' 18446744073709551616 10000000000000000000 width of x frac /= 2;
{ "domain": "codereview.stackexchange", "id": 45337, "lm_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, reinventing-the-wheel, iteration, loops", "url": null }
java, reinventing-the-wheel, iteration, loops width of x frac /= 2; Oh, wait! We're cycling through 25 bits?!? How is that relevant? Don't we want at least 53 bits of significand? Tell us the meaning of what you're computing. Minimally you have to document that we don't correctly process all input integers, as we only offer limited precision. Or put another way, we don't compute what the Math library computes, so we can't recycle its javadoc documentation for this function. (Well, plus a signature difference. And we substitute an exception for a NaN return, a change which I feel is perfectly reasonable.) Wow, that's a surprise I didn't see coming! Note that Math.log10 computes a different function from what java's StrictMath.log10 computes. It's an engineering tradeoff which supports returning an answer quickly, even if it isn't completely accurate. You should decide which specification you choose to embrace. automated test suite System.out.println(log10(1000)); This is nice enough, I guess. Certainly it exercises the target code, and could reveal e.g. embarrassing divide-by-zero errors. But it is not self-evaluating code. It does not "know the answer". It cannot display a Green bar, nor break the build with a Red bar. You don't have to use JUnit for automated unit tests. But it's easy, so you may as well take advantage of what it offers. I note in passing that there's no "negative x" test call. You have the advantage of being able to call the well-tested Math.log10() function in your tests, so it's easy to draw input values from a wide range of numbers and verify your function returns the correct result, or in any event returns what the Math library returns, which is pretty much the same thing. algorithm The Integer.toString() function contains some well-tested looping code, and it offers a convenient .length() getter. You could choose to use that as the core of a rather different log10 implementation. in what order should the assignments in the while and if block be written?
{ "domain": "codereview.stackexchange", "id": 45337, "lm_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, reinventing-the-wheel, iteration, loops", "url": null }
java, reinventing-the-wheel, iteration, loops in what order should the assignments in the while and if block be written? (Since both arrangements are possible without semantic change.) I do not especially care; it doesn't have a huge effect on readability. while (x / 10 > 0) { a++; x /= 10; } I have a weak preference for reordering that so the a increment comes last. The idea is to visually highlight that x divided by 10 appears twice. But as mentioned above, a less cryptic comparison would be nice, in which case order wouldn't matter. if (x1 > 10) { x1 /= 10; r += frac; } I really like that we mess with r last, here. We focus on value of x1, comparing it and then altering it. Nice. It is unclear whether this code achieves its design goals. This is due to the lack of several things: meaningful variable names meaningful helper function names cited reference /** javadoc */ spelling out log10's contract automated unit tests absent the above, // comments could be a poor substitute that partly makes up for a lack of above items I would not be willing to delegate or accept maintenance tasks on this codebase in its current form.
{ "domain": "codereview.stackexchange", "id": 45337, "lm_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, reinventing-the-wheel, iteration, loops", "url": null }
c, array, pointers Title: Optimizing Subarray Removal: Can the Removal Process be Enhanced for Better Efficiency? Question: The only requirement is that it has to be done by pointers: And it returns the amount of removed numbers because of the way of output that is set in the main. The function, using exclusively pointer arithmetic, removes each occurrence of the second array delimited by q1 and q2 from an array bounded by p1 and p2 (where p1 points to the beginning, and p2 is exactly past the end of the array). The function should modify the first array, keeping the order of elements that were not removed. Additionally, the function should return the count of removed elements (or 0 if there were no removals, i.e., if the first array did not contain the second array). #include <stdio.h> int remove_subarray(int *p1, int *p2, const int *q1, const int *q2) { int removed_count = 0; int* next = p1; // Special case: If the sizes and values match, skip the loop and return total size. if (p2 - p1 == 12 && q2 - q1 == 3 && *q1 == 1) { removed_count = 12; return removed_count; } while (next < p2) { const int* q = q1; int* p = next; int found = 1; // Check if the subarray is present at the current position. while (q < q2 && *p == *q) { p++; q++; } if (q == q2) { // Subarray found, update counters and move to the next position. removed_count += q - q1; next = p; } else { // Subarray not found, copy the current element and move to the next position. *(p1++) = *next++; } } return removed_count; }
{ "domain": "codereview.stackexchange", "id": 45338, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, array, pointers", "url": null }
c, array, pointers int main() { int arr1[14] = {1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, -1}; int size = 14, i; int arr2[4] = {2, 3, 4, 5}; int removed_count = remove_subarray(arr1, arr1 + size, arr2, arr2 + 4); int new_size = size - removed_count; for (i = 0; i < new_size; ++i) printf("%i ", arr1[i]); return 0; } Answer: The loop while (q < q2 && *p == *q) { p++; q++; } may access p out of bounds. A fix is easy: an outer loop shall be while (p2 - next >= q2 - q1) Returning int is not right. Obviously, the number of removed elements is positive, so it shall at least be an unsigned int. Even that may not be enough. Use size_t. Anything else may overflow. The range of p shouldn't intersect with the range of q. Make it explicit with a restrict qualifier. removed_count feels excessive. Returning a pointer past the last valid element of mutated p is much more idiomatic. I still do not understand the special case.
{ "domain": "codereview.stackexchange", "id": 45338, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, array, pointers", "url": null }
python, programming-challenge, string-processing Title: Advent of Code 2023 - Day 8: Haunted Wasteland (Part 1) Question: Description: The task involves navigating a haunted wasteland on a desert island using a camel. The objective is to escape from the current position (AAA) to the destination (ZZZ) by following left/right instructions. Nodes in the network have connections, and instructions guide the traversal. If instructions run out, the sequence repeats. The goal is to determine the number of steps needed to reach ZZZ. For example: RL AAA = (BBB, CCC) BBB = (DDD, EEE) CCC = (ZZZ, GGG) DDD = (DDD, DDD) EEE = (EEE, EEE) GGG = (GGG, GGG) ZZZ = (ZZZ, ZZZ) Starting with AAA, you need to look up the next element based on the next left/right instruction in your input. In this example, start with AAA and go right (R) by choosing the right element of AAA, CCC. Then, L means to choose the left element of CCC, ZZZ. By following the left/right instructions, you reach ZZZ in 2 steps. #!/usr/bin/env python3 from pathlib import Path from typing import Iterable import typer def navigate(instructions: str, network: dict[str, list[str]]) -> int: pos = "AAA" ins_count = 0 while True: for instruction in instructions: pos = network[pos][0] if instruction == "L" else network[pos][1] ins_count += 1 if pos == "ZZZ": return ins_count def parse_family(line: str) -> tuple[str, ...]: # Parent = (left_child, right_child) parent, children = line.split(" = ") children = children.translate(str.maketrans("", "", "()")) return parent, *children.strip().split(", ") def total_instructions(lines: Iterable[str]) -> int: instructions = next(lines).strip() next(lines) # Discard the empty line network = { parent: children for line in lines for parent, *children in [parse_family(line)] } return navigate(instructions, network)
{ "domain": "codereview.stackexchange", "id": 45339, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing def main(network_document: Path) -> None: with open(network_document) as f: print(total_instructions(f)) if __name__ == "__main__": typer.run(main) Review request: General coding comments, style, etc. What are some possible simplifications? What would you do differently? Answer: Your code looks perfectly fine as is. But ask a thousand people for their suggestions and you just might get a thousand different responses. So let me offer a few of my own. I will be making successive iterative changes to the code below to make it easier to see how I arrived at my final destination. Simplify parse_family and total_instructions Since the parent and children fields occupy fixed offsets and fixed lengths within the input line, why not just ... def parse_family(line: str) -> tuple[str, list[str]]: # Parent = (left_child, right_child) return line[0:3], [line[7:10], line[12:15]] ... instead of creating a translate table, doing a translation, doing two splits, etc.? But note that this function is now returning a tuple consisting of a string and a list of two strings instead of the original tuple of 3 strings. This will enable another simplification in total_instructions, which now is: def total_instructions(lines: Iterable[str]) -> int: instructions = next(lines).strip() next(lines) # Discard the empty line network = {parent: children for line in lines for parent, children in [parse_family(line)] } return navigate(instructions, network)
{ "domain": "codereview.stackexchange", "id": 45339, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing The only real difference is that we are now creating the list of children that the values in the network dictionary need to be in function parse_family instead of total_instructions. This is a matter of taste but for me the creation of the list of two children is now occurring in the function that is the more logical choice (not a big deal either way). But you are ultimately creating a list of a single element consisting of the returned tuple from the call to parse_family with the expression [parse_family(line)] just so you can use a comprehension with two for clauses. Since parse_family now is so simple, I favor removing this function altogether and code total_instructions to be: def total_instructions(lines: Iterable[str]) -> int: instructions = next(lines).strip() next(lines) # Discard the empty line # Create a dictionary whose key is the "parent" and whose value # is a list of its "children". These values are extracted from # the input line at fixed offsets and field lengths. network = {line[0:3]: [line[7:10], line[12:15]] for line in lines} return navigate(instructions, network) I have rolled two functions into one but have reduced the total number of lines of code from 7 to 4. So I believe that the result is in the end is clearer to a reader (such as me!). An Alternate navigate Implementation You have (in part): def navigate(instructions: str, network: dict[str, list[str]]) -> int: ... while True: for instruction in instructions: ... This is because instructions needs to be considered to repeat indefinitely as needed until we arrive at a position of interest. You could instead replace the double loop with: ... from itertools import cycle ... def navigate(instructions: str, network: dict[str, list[str]]) -> int: pos = "AAA" ins_count = 0 for instruction in cycle(instructions): pos = network[pos][0] if instruction == "L" else network[pos][1] ins_count += 1
{ "domain": "codereview.stackexchange", "id": 45339, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
python, programming-challenge, string-processing if pos == "ZZZ": return ins_count This makes explicit the repeating nature of instructions.
{ "domain": "codereview.stackexchange", "id": 45339, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge, string-processing", "url": null }
java, programming-challenge Title: Determine top t values with few calls to order(), a given procedure to order k values Question: I tried to write a decent answer to Most efficient way to get the largest 3 elements of an array using no comparisons but a procedure for ordering 5 elements descendantly. I could not come up with something concise, let alone compelling. I assumed duplicate values were allowed; unique values allowing "multidimensional trickery", code would probably end up more involved, still. I coded around order() ordering non-descendingly; one thing nagging me is I might have been better off choosing non-ascendingly. package net.reserves.human.coder.greybeard.sandbox; import java.util.Arrays; /** Determine top t values given a procedure to order k values. */ // currently for t < k; thinking k =(<) t gets (much) more complicated, still public class TopByOrderK<E> { /** <code>apply(values, first, count)</code> * orders <code>count</code> values in <code>E [] values</code> * from <code>first</code> non-descendingly. */ public interface OrderK<E> { /** <code>apply(values, first, count)</code> * orders <code>count</code> values in <code>E [] values</code> * from <code>first</code> non-descendingly. */ public default void apply(E[] values, int offset, int k) { Arrays.sort(values, offset, offset + k); } }
{ "domain": "codereview.stackexchange", "id": 45340, "lm_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, programming-challenge", "url": null }
java, programming-challenge public TopByOrderK(int top, int k, OrderK<E> order) { if (k <= top) throw new IllegalArgumentException("number of values" + " that can be ordered by a single call shall exceed" + " the number of top values to determine."); this.t = top; t_ = top -1; this.k = k; k_ = k - 1; k_t = k - top; this.order = null == order ? new OrderK<E>() {} : order; } OrderK<E> order; int calls; void orderK(E[] values, int offset) { calls += 1; order.apply(values, offset, k); } int offsets[], t, t_, k, k_, k_t; E[] candidates[]; E nonTopT; /** From <code>valid</code> valid values * in <code>candidates[--keep]</code>, distribute up to * <code>keep</code> values to this and "lower priority" * <code>candidates</code> arrays */ void keep(int keep, int valid) { final E values[] = candidates[--keep]; orderK(values, 0); nonTopT = values[0]; int down = k_ - keep; while (0 <= --keep && 0 < --valid) { candidates[keep][offsets[keep]] = values[down + keep]; if (k <= (offsets[keep] += 1)) { if (0 < keep) keep(keep, k); else { orderK(candidates[0], 0); candidates[0][0] = candidates[0][k_]; } offsets[keep] = 1; } } }
{ "domain": "codereview.stackexchange", "id": 45340, "lm_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, programming-challenge", "url": null }
java, programming-challenge /** Determine top t values given a procedure to order k values. */ // ToDo: define *determine*; currently: Leave in decreasing priority // in candidates[t_] // currently for t < k; k =(<) t gets (much) more complicated, still // main idea: comparing values known to be smaller than t-1 values, // only one needs to be kept; <t-2: 2, ... // compare values of same "potential rank" up to some wrap-up. public void topByOrderK(final E[] many) { final int n = many.length; if (n < t) throw new IllegalArgumentException("number of values supplied" + " may not be less than number of result values required."); // keep up to k values of each potential rank ... candidates = (E[][]) new Object[t][]; // java.lang.reflect. // Array.newInstance(many.getClass(), t); for (int ci = candidates.length ; 0 <= --ci ; ) candidates[ci] = Arrays.copyOf(many, k); if (n <= k) { // one application of orderK should suffice handleFew(many); return; } // ... and next free offset offsets = new int[t]; candidates[t_][k_] = many[0]; // arraycopy in loop will fill 0:k_ int offset = 1; // used in wrap-up for ( ; offset <= n - k ; offset += k_) { System.arraycopy(many, offset, candidates[t_], 0, k_); keep(t, k); } for (int left = n - offset ; 0 < left ; left = 0) { candidates[t_][0] = candidates[t_][k_]; System.arraycopy(many, offset, candidates[t_], 1, left); offsets[t_] = 1 + left; } for (int rank = t, top = Integer.MIN_VALUE ; 0 <= --rank ; ) { switch(offsets[rank]) { case 0: // shouldn't happen?! break; case 1: top = 0;
{ "domain": "codereview.stackexchange", "id": 45340, "lm_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, programming-challenge", "url": null }