RogerBW's Blog

 Perl Weekly Challenge 126: Count Sweeper 20 August 2021 I’ve been doing the Weekly Challenges. The latest involved numbers excluding 1, and Minesweeper. (Note that this is open until 22 August 2021.) TASK #1 › Count Numbers You are given a positive integer `\$N`. Write a script to print count of numbers from 1 to `\$N` that don’t contain digit 1. I came up with four separate approaches to this. Simplest: generate all the numbers in the range, ignore anything with a 1 in it, count what's left. This is doable with standard Unix commands: `seq 1 \$N |grep -vc 1` But for example given the range 1..200 that will generate and then throw away all the numbers from 100 to 199 inclusive. Which seems wasteful. Next thought: generate the numbers, but regex replace a 1 with a 2 whenever it shows up. That jumps over the gap from 99 to 200 in a single step. (If I'm incrementing by 1 each time, the only numbers with 1 in them that I see will take the form `xxx1000`, with arbitrary numbers of `x`s and `0`s.) That still starts to bog down a bit when it's counting numbers from 1 to 100,000,000. Using regular expressions on numbers is ugly, so version three: generate the numbers, split then into digits with integer division, then do basically the same thing as above. On Perl at least, this turns out to be rather slower. All of these approaches seem as though they're basically `O(n log n)`: we have to iterate through something like each number, and do something related to the number of digits in that number. But look at it another way. What we have here is a sequence (specifically OEIS #A052383, though we're ignoring the leading zero). Given a number (that may lie in that sequence or may not), we want to find out how many terms come before it. If it is a number in that sequence, then that's simply the input interpreted as base 9, with `2..9` in the input becoming `1..8`. If it's not in that sequence (i.e. it has a 1 in it), we need the highest number in the sequence that's less than it. The highest number in the sequence that's less than `xxx1yyy` (in our special input format) is `xxx0888` (base 9) – assuming none of the `x`s is a 1. And I think this is more like `O(log n)`, because it just scales with the length of the number. Without arbitrary-length arrays this wasn't amenable to PostScript. I'll use the Rust version to explain: ``````fn cn(n: i64) -> i64 { let mut k=n; let mut digits: Vec=vec![]; `````` I'm going to break down the input, pushing its digits into `digits`, least significant first. `````` while k>0 { let mut d=k % 10; `````` If the digit is a 1, then all the less-significant digits become 8. (Which is slightly wasteful, I suppose, because I've already calcuated them; if I did it left-to-right I could short-circuit the process. But this was simpler.) `````` if d==1 { digits=vec![8;digits.len()]; } `````` If the digit wasn't a 0, then subtract 1 (i.e. 1 becomes 0 with the special case dealt with above, 2 becomes 1, etc.) `````` if d>0 { d -= 1; } digits.push(d); k /= 10; } `````` Now we have an array of base-9 digits, and we build those back up into a number. `````` let mut tc: i64=0; for i in (0..=digits.len()-1).rev() { tc *= 9; tc += digits[i]; } return tc; } `````` TASK #2 › Minesweeper Game You are given a rectangle with points marked with either `x` or `*`. Please consider the `x` as a land mine. Write a script to print a rectangle with numbers and `x` as in the Minesweeper game. ``````A number in a square of the minesweeper game indicates the number of mines within the neighbouring squares (usually 8), also implies that there are no bombs on that square. `````` Well, sadly it's not really amenable to my normal test-based approach… ``````my @in=( [qw(x * * * x * x x x x)], [qw(* * * * * * * * * x)], [qw(* * * * x * x * x *)], [qw(* * * x x * * * * *)], [qw(x * * * x * * * * x)], ); my \$ymax=\$#in; my \$xmax=\$#{\$in[0]}; `````` I have a second array `mn` ("mine neighbours") initialised to 0. ``````my @mn; foreach (0..\$ymax) { push @mn,[(0) x (\$xmax+1)]; } `````` I scan across each cell, and for each one that has a mine in it I add 1 to the neighbouring values in `mn`. (Basically the same approach as the naïve Conway's Life algorithm. I constrain the edges with `max` and `min`.) ``````foreach my \$y (0..\$ymax) { my @sy=(max(0,\$y-1)..min(\$ymax,\$y+1)); foreach my \$x (0..\$xmax) { my @sx=(max(0,\$x-1)..min(\$xmax,\$x+1)); if (\$in[\$y][\$x] eq 'x') { foreach my \$yi (@sy) { foreach my \$xi (@sx) { if (\$xi==\$x && \$yi==\$y) { next; } \$mn[\$yi][\$xi]++; } } } } } `````` Then replace the values in the mine cells with `x` for display purposes, and print each line. ``````foreach my \$y (0..\$ymax) { foreach my \$x (0..\$xmax) { if (\$in[\$y][\$x] eq 'x') { \$mn[\$y][\$x]='x'; } } print join(' ',@{\$mn[\$y]}),"\n"; } `````` Full code on github. Comments on this post are now closed. If you have particular grounds for adding a late comment, comment on a more recent post quoting the URL of this one. Search 10 per page 20 per page 50 per page 100 per page Archive Tags 1920s 1930s 1940s 1950s 1960s 1970s 1980s 1990s 2000s 2010s 3d printing action advent of code aeronautics aikakirja anecdote animation anime army astronomy audio audio tech aviation base commerce battletech beer boardgaming book of the week bookmonth chain of command children chris chronicle church of no redeeming virtues cold war comedy computing contemporary cornish smuggler cosmic encounter coup covid-19 crime cthulhu eternal cycling dead of winter doctor who documentary drama driving drone ecchi economics en garde espionage essen 2015 essen 2016 essen 2017 essen 2018 essen 2019 essen 2022 essen 2023 existential risk falklands war fandom fanfic fantasy feminism film firefly first world war flash point flight simulation food garmin drive gazebo genesys geocaching geodata gin gkp gurps gurps 101 gus harpoon historical history horror hugo 2014 hugo 2015 hugo 2016 hugo 2017 hugo 2018 hugo 2019 hugo 2020 hugo 2022 hugo-nebula reread in brief avoid instrumented life javascript julian simpson julie enfield kickstarter kotlin learn to play leaving earth linux liquor lovecraftiana lua mecha men with beards mpd museum music mystery naval noir non-fiction one for the brow opera parody paul temple perl perl weekly challenge photography podcast politics postscript powers prediction privacy project woolsack pyracantha python quantum rail raku ranting raspberry pi reading reading boardgames social real life restaurant reviews romance rpg a day rpgs ruby rust scala science fiction scythe second world war security shipwreck simutrans smartphone south atlantic war squaddies stationery steampunk stuarts suburbia superheroes suspense television the resistance the weekly challenge thirsty meeples thriller tin soldier torg toys trailers travel type 26 type 31 type 45 vietnam war war wargaming weather wives and sweethearts writing about writing x-wing young adult Special All book reviews, All film reviews
Produced by aikakirja v0.1