started at ; stage 2 at ; ended at
I'm a lazy painter, so your challenge this round is to flood fill. submissions can be written in python, c, rust, or typescript (node).
flood fill is a class of simple algorithms that fill a contiguous region of identical cells in a 2D array starting from a given point, the same way the bucket tool fills in areas in a paint program.
for example, this is the result of flood filling the following grid with #
, from the point indicated by *
:
.#... .####
..#.* ..###
##... --> #####
.#### .####
..#.. ..#..
your challenge, given a 2D boolean array of arbitrary size and a point on it, is simple: find the contiguous region of false
values the point is contained by, and replace them all with true
. only orthagonal adjacency is considered; each cell has at most 4 neighbours.
the APIs for each language are as follows:
def entry(grid: list[list[bool]], x: int, y: int) -> list[list[bool]]
. the function may mutate the original list and return the same one.function entry(grid: bool[][], x: number, y: number): bool[][]
. the function may mutate the original list and return the same one.void entry(char *grid, size_t width, size_t height, size_t x, size_t y)
fn entry(grid: Vec<bool>, width: usize, _height: usize, x: usize, y: usize) -> Vec<bool>
you can download all the entries
written by Olivia
submitted at
4 likes
written by indigo (away until 9/26)
submitted at
1 like
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | def str_to_grid(g: str): return [*map(lambda l: [*map(lambda c: c == '#', l)], g.split('\n'))] def fill_coord(g: str): return def grid_to_str(g: list[list[bool]]): return '\n'.join(map(lambda r: ''.join('#' if b else '.' for b in r), g)) def entry(grid: list[list[bool]], x: int, y: int): # Basic flood-fill algorithm; # if the cell is filled, add its adjacent cells to the to-be-filled list # repeat until no more cells are to be filled. queue = [(y, x)] # stored in row-major order while queue: (row, col) = queue.pop(0) if (0 <= row < len(grid) and 0 <= col < len(grid[row]) and not grid[row][col]): grid[row][col] = True queue.append((row + 1, col)) queue.append((row - 1, col)) queue.append((row, col + 1)) queue.append((row, col - 1)) return grid |
written by LyricLy
submitted at
5 likes
1 2 3 4 5 6 7 8 9 | target libraries logs world versions crashreports *.json !tick.json !load.json |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "adler" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" [[package]] name = "byteorder" version = "1.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" [[package]] name = "cesu8" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "crc32fast" version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d" dependencies = [ "cfg-if", ] [[package]] name = "flate2" version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f82b0f4c27ad9f8bfd1f3208d882da2b09c301bc1c828fd3a00d0216d2fbbff6" dependencies = [ "crc32fast", "miniz_oxide", ] [[package]] name = "hematite-nbt" version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "670d0784ee67cfb57393dc1837867d2951f9a59ca7db99a653499c854f745739" dependencies = [ "byteorder", "cesu8", "flate2", "serde", ] [[package]] name = "mc21" version = "0.1.0" dependencies = [ "hematite-nbt", "serde", ] [[package]] name = "miniz_oxide" version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f5c75688da582b8ffc1f1799e9db273f32133c49e048f614d22ec3256773ccc" dependencies = [ "adler", ] [[package]] name = "proc-macro2" version = "1.0.42" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c278e965f1d8cf32d6e0e96de3d3e79712178ae67986d9cf9151f51e95aac89b" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bcdf212e9776fbcb2d23ab029360416bb1706b1aea2d1a5ba002727cbcab804" dependencies = [ "proc-macro2", ] [[package]] name = "serde" version = "1.0.140" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc855a42c7967b7c369eb5860f7164ef1f6f81c20c7cc1141f2a604e18723b03" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.140" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f2122636b9fe3b81f1cb25099fcf2d3f542cdb1d45940d56c713158884a05da" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "syn" version = "1.0.98" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c50aef8a904de4c23c788f104b7dddc7d6f79c647c7c8ce4cc8f73eb0ca773dd" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "unicode-ident" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "15c61ba63f9235225a22310255a29b806b907c9b8c964bcbd0a2c70f3f2deea7" |
1 2 3 4 5 6 7 8 9 10 11 12 | [package] name = "mc21" version = "0.1.0" edition = "2021" [dependencies] hematite-nbt = "0.5" serde = "1.0" [lib] name = "mc21" path = "lib.rs" |
1 2 | execute store result score density mc21 if entity @e[type=pig, distance=..1] scoreboard players operation minDensity mc21 < density mc21 |
1 2 3 4 5 | kill @e[type=marker, tag=origin] execute as @e[type=pig] run data modify storage mc21:out Data append from entity @s Pos kill @e[type=pig] scoreboard players set denseTime mc21 -2147483648 stop |
1 2 3 | #By changing the setting below to TRUE you are indicating your agreement to our EULA (https://aka.ms/MinecraftEULA). #Tue Aug 02 02:54:40 CEST 2022 eula=true |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 | use serde::{Serialize, Deserialize, de::Error}; use std::fs::{File, create_dir_all, copy}; use std::path::PathBuf; struct Triple<T>(T, T, T); impl<T: Serialize + Copy> Serialize for Triple<T> { fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { vec![self.0, self.1, self.2].serialize(s) } } impl<'de, T: Deserialize<'de> + Copy> Deserialize<'de> for Triple<T> { fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> { let v = Vec::deserialize(d)?; match &v[..] { &[x, y, z] => Ok(Self(x, y, z)), _ => Err(D::Error::custom("list had wrong number of elements")), } } } #[derive(Serialize)] struct Block { #[serde(rename = "Name")] name: &'static str, } #[derive(Serialize)] struct BlockRef { state: i32, pos: Triple<i32>, } #[derive(Serialize)] struct EntityData { id: &'static str, #[serde(rename = "Tags")] tags: &'static [&'static str], } #[derive(Serialize)] struct Entity { pos: Triple<f64>, #[serde(rename = "blockPos")] block_pos: Triple<i32>, nbt: EntityData, } #[derive(Serialize)] struct Structure { #[serde(rename = "DataVersion")] data_version: i32, size: Triple<i32>, palette: &'static [Block], entities: Vec<Entity>, blocks: Vec<BlockRef>, } // This is rather stupid. #[derive(Deserialize)] struct Storage { data: StorageData, } #[derive(Deserialize)] struct StorageData { contents: StorageContents, } #[derive(Deserialize)] struct StorageContents { out: StorageResult, } #[derive(Deserialize)] struct StorageResult { #[serde(rename = "Data")] data: Vec<Triple<f64>>, } const PATHS: [(&'static str, &[&'static str]); 4] = [ ("world/generated/minecraft/structures/", &[]), ("world/datapacks/mc21/", &["pack.mcmeta"]), ("world/datapacks/mc21/data/mc21/functions/", &["load.mcfunction", "tick.mcfunction", "end.mcfunction", "do_density.mcfunction"]), ("world/datapacks/mc21/data/minecraft/tags/functions/", &["tick.json", "load.json"]), ]; pub fn entry(mut grid: Vec<bool>, width: usize, height: usize, x: usize, y: usize) -> Vec<bool> { let mut blocks = Vec::new(); for y in 0..height { for x in 0..width { let state = grid[y*width+x] as i32; blocks.push(BlockRef { state, pos: Triple(x as i32, 0, y as i32)}); blocks.push(BlockRef { state, pos: Triple(x as i32, 1, y as i32) }); } } let entity = Entity { pos: Triple(x as f64, 0.0, y as f64), block_pos: Triple(x as i32, 0, y as i32), nbt: EntityData { id: "minecraft:marker", tags: &["origin"] }, }; let structure = Structure { data_version: 3117, size: Triple(width as i32, 2, height as i32), palette: &[ Block { name: "air" }, Block { name: "stone" }, ], entities: vec![entity], blocks, }; for (dir, files) in PATHS { create_dir_all(dir).unwrap(); for file in files { let path: PathBuf = [dir, file].iter().collect(); copy(file, path).unwrap(); } } nbt::to_gzip_writer(&mut File::create("world/generated/minecraft/structures/start.nbt").unwrap(), &structure, None).unwrap(); std::process::Command::new("java") .args(["-jar", "server.jar", "nogui"]) .spawn() .unwrap(); loop { std::thread::sleep(std::time::Duration::from_secs(20)); if let Ok(file) = File::open("world/data/command_storage_mc21.dat") { let storage: Storage = nbt::from_gzip_reader(file).unwrap(); for Triple(x, _, y) in storage.data.contents.out.data { grid[y as usize*width+x as usize] = true; } return grid; } } } |
1 2 3 4 5 | { "values": [ "mc21:load" ] } |
1 2 3 4 5 6 7 | scoreboard objectives add mc21 dummy scoreboard players reset denseTime mc21 data modify storage mc21:out Data set value [] kill @e[type=pig] place template minecraft:start 0 -62 0 gamerule doMobLoot false gamerule maxEntityCramming 12 |
1 2 3 4 5 6 | { "pack": { "pack_format": 10, "description": "cg #21" } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | #Minecraft server properties #Tue Aug 02 02:54:40 CEST 2022 allow-flight=true allow-nether=false broadcast-console-to-ops=true broadcast-rcon-to-ops=true difficulty=easy enable-command-block=false enable-jmx-monitoring=false enable-query=false enable-rcon=false enable-status=true enforce-secure-profile=true enforce-whitelist=false entity-broadcast-range-percentage=100 force-gamemode=true function-permission-level=4 gamemode=spectator generate-structures=false generator-settings={} hardcore=false hide-online-players=false level-name=world level-seed= level-type=flat max-chained-neighbor-updates=1000000 max-players=20 max-tick-time=60000 max-world-size=29999984 motd=cg \#21 network-compression-threshold=256 online-mode=true op-permission-level=4 player-idle-timeout=0 prevent-proxy-connections=false previews-chat=false pvp=false query.port=25565 rate-limit=0 rcon.password= rcon.port=25575 require-resource-pack=false resource-pack= resource-pack-prompt= resource-pack-sha1= server-ip=localhost server-port=25565 simulation-distance=10 spawn-animals=true spawn-monsters=false spawn-npcs=false spawn-protection=0 sync-chunk-writes=true text-filtering-config= use-native-transport=true view-distance=10 |
1 2 3 4 5 | { "values": [ "mc21:tick" ] } |
1 2 3 4 5 | execute at @e[type=marker, tag=origin] run summon pig ~ ~ ~ {Invulnerable:1b, Fire:32668s} scoreboard players set minDensity mc21 1000 execute as @e[type=pig] at @s run function mc21:do_density execute if score minDensity mc21 matches 2.. run scoreboard players add denseTime mc21 1 execute if score denseTime mc21 matches 150.. run function mc21:end |
written by IFcoltransG
submitted at
2 likes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | # // Code by SoundOfSpouting#2573 (UID: 319753218592866315) import itertools def entry(grid, x, y): h = len(grid); w = len(grid[0]); u = []; f = [] o = [[] for i in range(h)] m = [[None for j in range(w)] for i in range(h)] grid[x][y] = False for i in range(h): for j in range(w): m[i][j] = (i, j, grid[i][j]) for i in range(h): for rle in itertools.groupby(m[i], g): o[i].append((rle[0], list(rle[1]))) r = [find(o, x, y)] while len(r) != 0: for item in r: i = item[0]; j = item[1] k = o[i][j][1] b = k[0]; e = k[-1] for a in [i - 1, i + 1]: if 0 <= a and a < h: bd = find(o, a, b[1]); be = find(o, a, e[1]) for c in o[a][bd[1] : be[1] + 1]: if not c[0]: v = c[1][0] v = find(o, v[0], v[1]) if v not in u: f.append(v) u.extend(r) r = f; f = [] for item in u: for value in o[item[0]][item[1]][1]: grid[value[0]][value[1]] = True blank = "...\n...\n..." return grid def find(o, x, y): w = len(o[x]) for i in range(w): d = o[x][i][1] if d[0][1] <= y and y <= d[-1][1]: return (x, i) raise ValueError(x, y) def g(a): return a[2] # ################## # # #### #### # # ## ## # # ## snes undertale ## # # ## ## # # ## ###### ## # # ## ###### ## # # ## ###### ## ###### ## # # ## ###### ## # # #### ## ## #### # # ## ###################### ## # # ## ## ## ## ## ## ## # # #### ############## #### # # ########## ########## # # ## ############################## ## # # #### ## ## ## ## ## #### # # ## ## ###### ###### ## ## # # ## #### ###### ## ###### #### ### # ## ## ## ## ## ### # ## ## ## ## ## ### # ## ## #### #### ## ## # # #### ## ## ## ## #### # # ###### ############## ###### # # #### ############## #### # # ################################## # # ################ ################ # # ############ ############ # # ###### ## ## ###### # # ## #### #### ## # # ########## ########## # |
written by olus2000
submitted at
5 likes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | // ca.c #include <stddef.h> #define written_by char #define with_help_from size_t #define impersonating void #define and while #define think_like return #define uh for #define m if #define k else written_by *SoundOfSpouting; with_help_from RocketRace; with_help_from LyricLy; impersonating ISO_4683_1(with_help_from Razetime, with_help_from firecubez, written_by LyricLy) { SoundOfSpouting[Razetime + firecubez * RocketRace] = SoundOfSpouting[Razetime + firecubez * RocketRace] % 3 + 3 * LyricLy; } impersonating firecubez(with_help_from ISO_4683_1, with_help_from Razetime) { SoundOfSpouting[ISO_4683_1 + Razetime * RocketRace] = SoundOfSpouting[ISO_4683_1 + Razetime * RocketRace] / 3; } written_by Palaiologos(with_help_from no_one, with_help_from she_is_self_sufficient) { think_like no_one >= RocketRace || she_is_self_sufficient >= LyricLy ? 0 : SoundOfSpouting[no_one + she_is_self_sufficient * RocketRace] % 3; } written_by Razetime(with_help_from deadbraincoral, with_help_from GNU_Radio_Shows) { think_like Palaiologos(deadbraincoral - 1, GNU_Radio_Shows) > 1 || Palaiologos(deadbraincoral, GNU_Radio_Shows - 1) > 1 || Palaiologos(deadbraincoral + 1, GNU_Radio_Shows) > 1 || Palaiologos(deadbraincoral, GNU_Radio_Shows + 1) > 1 ? 2 : 0; } written_by olus2000() { written_by Razetime = 0; uh (with_help_from IFcoltransG = 0; IFcoltransG < RocketRace; IFcoltransG++) uh (with_help_from deadbraincoral = 0; deadbraincoral < LyricLy; deadbraincoral++) { firecubez(IFcoltransG, deadbraincoral); m (Palaiologos(IFcoltransG, deadbraincoral) > 1) Razetime = 1; } think_like Razetime; } impersonating Hildegunst_Taillemythes() { uh (with_help_from olus2000 = 0; olus2000 < RocketRace; olus2000++) uh (with_help_from gollark = 0; gollark < LyricLy; gollark++) { m (Palaiologos(olus2000, gollark) == 0) { m (Razetime(olus2000, gollark)) ISO_4683_1(olus2000, gollark, 2); } k ISO_4683_1(olus2000, gollark, 1); } } impersonating entry(written_by *Palaiologos, with_help_from ISO_4683_1, with_help_from Pyrotelekinetic, with_help_from Haru, with_help_from firecubez) { SoundOfSpouting = Palaiologos; RocketRace = ISO_4683_1; LyricLy = Pyrotelekinetic; SoundOfSpouting[Haru + firecubez * RocketRace] = 2; do Hildegunst_Taillemythes(); and (olus2000()); } |
written by Kestrel
submitted at
2 likes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | // it used to be even more complicated, but even i couldn't handle 300 lines of pure spaghetti const needs_more_closure = (() => { class linkedCell { value: number; north: linkedCell; east: linkedCell; south: linkedCell; west: linkedCell; }; let border = new linkedCell; border.value = 1; let x: number, y: number, arr: linkedCell[][] = [], passarr: linkedCell[] = []; const marks: [ (px: number) => ((py: number) => void), (cell: number) => number, (e: number[]) => number, (e: number[]) => number[][] ] = [ (px: number) => ((py: number) => { x = px; y = py }), (cell: number) => { let me = new linkedCell; me.value = cell; me.north = border; me.east = border; me.south = border; me.west = border; if (passarr.length > 0) { let prev = passarr[passarr.length - 1]; prev.east = me; me.west = prev; } passarr.push(me); return 0; }, (e: number[]) => { passarr.map((a, b) => { if (arr.length > 0) { let c = arr[arr.length - 1][b]; a.north = c; c.south = a; } }); arr.push([...passarr]); passarr = []; return 0; }, (e: number[]) => { let d: number; arr[x][y].value = 2; do { d = 0 for (let n of arr) { for (let m of n) { if (m.value == 0) { if (m.north.value == 2 || m.east.value == 2 || m.south.value == 2 || m.west.value == 2) { m.value = 2; d = 1; } } } } } while (d) return arr.map(n => n.map(m => [0, 1, 1][m.value])); } ] return marks; })() function entry(grid: boolean[][], x: number, y: number): boolean[][] { needs_more_closure[0](x)(y); return needs_more_closure[3] (grid.map( a => needs_more_closure[2] (a.map( b => needs_more_closure[1](Number(b)) )) )) .map(a => a.map(b => Boolean(b))); } |
written by Edgex42
submitted at
3 likes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | def entry(grid, x, y): p=[(x,)+(y,),] for _ in[...]*len(grid)*len(grid[0]): for q in[*p]:p=[*filter(lambda r:grid[r[1]][r[0]]^1,[*({*p+[(q[0]-1,q[1])*q[0],q[1]*(q[0],q[1]-1),(q[0]+1,q[1])*(len(grid[0])-1-q[0]),(len(grid)-1-q[1])*(q[0],q[1]+1)]}-{()})])] for p in p:grid[p[1]][p[0]]=True """ ⠀⠀⠀⣴⣴⡤ ⠀⣠⠀⢿⠇⡇⠀⠀⠀⠀⠀⠀⠀⢰⢷⡗ ⠀⢶⢽⠿⣗⠀⠀⠀⠀⠀⠀⠀⠀⣼⡧⠂⠀⠀⣼⣷⡆ ⠀⠀⣾⢶⠐⣱⠀⠀⠀⠀⠀⣤⣜⣻⣧⣲⣦⠤⣧⣿⠶ ⠀⢀⣿⣿⣇⠀⠀⠀⠀⠀⠀⠛⠿⣿⣿⣷⣤⣄⡹⣿⣷ ⠀⢸⣿⢸⣿⠀⠀⠀⠀⠀⠀⠀⠀⠈⠙⢿⣿⣿⣿⣿⣿ ⠀⠿⠃⠈⠿⠆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠹⠿⠿⠿ ⠀⢀⢀⡀⠀⢀⣤⠀⠀⠀⠀⠀⠀⠀⡀⡀ ⠀⣿⡟⡇⠀⠭⡋⠅⠀⠀⠀⠀⠀⢰⣟⢿ ⠀⣹⡌⠀⠀⣨⣾⣷⣄⠀⠀⠀⠀⢈⠔⠌ ⠰⣷⣿⡀⢐⢿⣿⣿⢻⠀⠀⠀⢠⣿⡿⡤⣴⠄⢀⣀⡀ ⠘⣿⣿⠂⠈⢸⣿⣿⣸⠀⠀⠀⢘⣿⣿⣀⡠⣠⣺⣿⣷ ⠀⣿⣿⡆⠀⢸⣿⣿⣾⡇⠀⣿⣿⣿⣿⣿⣗⣻⡻⠿⠁ ⠀⣿⣿⡇⠀⢸⣿⣿⡇⠀⠀⠉⠉⠉⠉⠉⠉⠁ """ |
written by razetime
submitted at
2 likes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | use rand::prelude::*; use std::collections::VecDeque; use std::iter::FromIterator; fn adjacent( x: isize, y: isize, width: isize, height: isize, ) -> impl Iterator<Item = (usize, usize)> { vec![(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)] .into_iter() .filter(move |&(a, b)| a < width && b < height && a >= 0 && b >= 0) .map(|(x, y)| (x as usize, y as usize)) } fn entry(grid: Vec<bool>, width: usize, _height: usize, x: usize, y: usize) -> Vec<bool> { let mut result: Vec<bool> = grid; result[x + width * y] = true; let mut pairs: VecDeque<(usize, usize)> = VecDeque::from_iter([(x, y)]); while !pairs.is_empty() { let (x1, y1) = pairs.pop_front().unwrap(); result[x1 + width * y1] = true; for (x2, y2) in adjacent(x1 as isize, y1 as isize, width as isize, _height as isize) { if !result[x2 + width * y2] { result[x2 + width * y2] = true; pairs.push_back((x2, y2)); } } } result } fn disp(grid: Vec<bool>, width: usize) { for (i, &item) in grid.iter().enumerate() { if i % width == 0 { println!(); } print!("{}", if item { "#" } else { "." }); } println!() } fn debug(grid: Vec<bool>, width: usize, _height: usize, x: usize, y: usize) { println!("x = {}, y = {}", x, y); let out: Vec<bool> = entry(grid.clone(), width, _height, x, y); disp(grid, width); println!("---"); disp(out, width); println!("==="); } fn rand_debug() { let mut rng = rand::thread_rng(); let width: usize = rng.gen_range(10..20); let height: usize = rng.gen_range(10..20); let x: usize = rng.gen_range(0..width); let y: usize = rng.gen_range(0..height); let size: usize = width * height; let mut grid: Vec<bool> = Vec::with_capacity(size); for _ in 0..size { grid.push(rand::random()); } debug(grid, width, height, x, y); } fn main() { debug( vec![ false, true, false, false, false, false, false, true, false, false, true, true, false, false, false, false, true, true, true, true, false, false, true, false, false, ], 5, 5, 4, 1, ); for _ in 0..20 { rand_debug(); } } |
1 |
post a comment