Louis Jones

Louis Jones

1646919166

Implementing and Optimizing a Wordle Solver in Rust

Implementing and Optimizing a Wordle Solver in Rust

In this tutorial, you'll learn how to implement and optimize a Wordle Solver in Rust programming

We implement a Wordle solver in Rust based off on the excellent video on the same topic: https://morioh.com/p/a9d1f372f900 


And then we profile and optimize it to improve the runtime from our initial naive implementation by ~13500x. You can find the code at
https://github.com/jonhoo/roget 

0:00:00 Introduction
0:01:00 Wordle intro
0:04:50 What we're doing today
0:11:24 Gathering our datasets
0:27:22 Structure the solver
0:44:04 The correctness of a guess
1:14:28 Testing the play machinery
1:30:16 Outlining the algorithm
1:38:55 Does a word match a pattern?
2:21:12 Reusing correctness computation
2:26:06 Computing a word's "goodness"
2:49:20 Running the naive implementation
2:57:59 Profiling to the rescue
3:04:44 Avoiding allocations
3:22:05 Comparing bytes, not characters
3:31:58 Correctness computing is faster
3:42:23 HashMap iteration is slow
3:47:40 Compare bytes again
3:50:20 Trying to avoid bounds checks
3:54:42 Keep words as length 5 arrays
4:07:36 Only initialize remaining once
4:21:00 Back to length 5 arrays
4:32:14 Where is compute spending time?
4:51:20 Short break
4:55:20 What if we don't set the first word?
5:02:49 What if we start with another word?
5:07:15 Precalculating matches
5:31:20 Prefer more likely words
5:38:05 Prune known-empty patterns
5:56:24 Don't even consider unlikely words
6:07:36 Closing thoughts

#rust #programming 

What is GEEK

Buddha Community

Implementing and Optimizing a Wordle Solver in Rust

Serde Rust: Serialization Framework for Rust

Serde

*Serde is a framework for serializing and deserializing Rust data structures efficiently and generically.*

You may be looking for:

Serde in action

Click to show Cargo.toml. Run this code in the playground.

[dependencies]

# The core APIs, including the Serialize and Deserialize traits. Always
# required when using Serde. The "derive" feature is only required when
# using #[derive(Serialize, Deserialize)] to make Serde work with structs
# and enums defined in your crate.
serde = { version = "1.0", features = ["derive"] }

# Each data format lives in its own crate; the sample code below uses JSON
# but you may be using a different one.
serde_json = "1.0"

 

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let point = Point { x: 1, y: 2 };

    // Convert the Point to a JSON string.
    let serialized = serde_json::to_string(&point).unwrap();

    // Prints serialized = {"x":1,"y":2}
    println!("serialized = {}", serialized);

    // Convert the JSON string back to a Point.
    let deserialized: Point = serde_json::from_str(&serialized).unwrap();

    // Prints deserialized = Point { x: 1, y: 2 }
    println!("deserialized = {:?}", deserialized);
}

Getting help

Serde is one of the most widely used Rust libraries so any place that Rustaceans congregate will be able to help you out. For chat, consider trying the #rust-questions or #rust-beginners channels of the unofficial community Discord (invite: https://discord.gg/rust-lang-community), the #rust-usage or #beginners channels of the official Rust Project Discord (invite: https://discord.gg/rust-lang), or the #general stream in Zulip. For asynchronous, consider the [rust] tag on StackOverflow, the /r/rust subreddit which has a pinned weekly easy questions post, or the Rust Discourse forum. It's acceptable to file a support issue in this repo but they tend not to get as many eyes as any of the above and may get closed without a response after some time.

Download Details:
Author: serde-rs
Source Code: https://github.com/serde-rs/serde
License: View license

#rust  #rustlang 

Louis Jones

Louis Jones

1646919166

Implementing and Optimizing a Wordle Solver in Rust

Implementing and Optimizing a Wordle Solver in Rust

In this tutorial, you'll learn how to implement and optimize a Wordle Solver in Rust programming

We implement a Wordle solver in Rust based off on the excellent video on the same topic: https://morioh.com/p/a9d1f372f900 


And then we profile and optimize it to improve the runtime from our initial naive implementation by ~13500x. You can find the code at
https://github.com/jonhoo/roget 

0:00:00 Introduction
0:01:00 Wordle intro
0:04:50 What we're doing today
0:11:24 Gathering our datasets
0:27:22 Structure the solver
0:44:04 The correctness of a guess
1:14:28 Testing the play machinery
1:30:16 Outlining the algorithm
1:38:55 Does a word match a pattern?
2:21:12 Reusing correctness computation
2:26:06 Computing a word's "goodness"
2:49:20 Running the naive implementation
2:57:59 Profiling to the rescue
3:04:44 Avoiding allocations
3:22:05 Comparing bytes, not characters
3:31:58 Correctness computing is faster
3:42:23 HashMap iteration is slow
3:47:40 Compare bytes again
3:50:20 Trying to avoid bounds checks
3:54:42 Keep words as length 5 arrays
4:07:36 Only initialize remaining once
4:21:00 Back to length 5 arrays
4:32:14 Where is compute spending time?
4:51:20 Short break
4:55:20 What if we don't set the first word?
5:02:49 What if we start with another word?
5:07:15 Precalculating matches
5:31:20 Prefer more likely words
5:38:05 Prune known-empty patterns
5:56:24 Don't even consider unlikely words
6:07:36 Closing thoughts

#rust #programming 

Rust Lang Course For Beginner In 2021: Guessing Game

 What we learn in this chapter:
- Rust number types and their default
- First exposure to #Rust modules and the std::io module to read input from the terminal
- Rust Variable Shadowing
- Rust Loop keyword
- Rust if/else
- First exposure to #Rust match keyword

=== Content:
00:00 - Intro & Setup
02:11 - The Plan
03:04 - Variable Secret
04:03 - Number Types
05:45 - Mutability recap
06:22 - Ask the user
07:45 - First intro to module std::io
08:29 - Rust naming conventions
09:22 - Read user input io:stdin().read_line(&mut guess)
12:46 - Break & Understand
14:20 - Parse string to number
17:10 - Variable Shadowing
18:46 - If / Else - You Win, You Loose
19:28 - Loop
20:38 - Match
23:19 - Random with rand
26:35 - Run it all
27:09 - Conclusion and next episode

#rust 

Lydia  Kessler

Lydia Kessler

1626318000

ULTIMATE Rust Lang Tutorial! - Publishing a Rust Crate

The ultimate Rust lang tutorial. Follow along as we go through the Rust lang book chapter by chapter.

ūüďĚGet the FREE Rust Cheatsheet: https://letsgetrusty.com/cheatsheet

The Rust book: https://doc.rust-lang.org/stable/book/‚Äč‚Äč

Chapters:
0:00‚Äč Intro
0:43 Release Profiles
3:00 Documentation Comments
4:32 Commonly Used Sections
5:04 Documentation Comments as Tests
5:50 Commenting Contained Items
6:29 Exporting a Public API
8:44 Setting up Creates.io Account
9:54 Adding Metadata to a New Create
12:14 Publishing to Crates.io
12:49 Removing Version from Crates.io
13:37 Outro

#letsgetrusty‚Äč‚Äč #rust‚Äčlang‚Äč #tutorial

#rust #rust lang #rust crate

Identicon Implementation in Rust for Polkadot

Crate plot_icon

Overview

This is a lib crate for generating standard 19-circle icons in png and in svg format.

Output is Vec<u8> png data, or svg::Document with svg data, both could be easily printed into files.

The identicon color scheme and elements arrangement follow the published javascript code for polkadot identicon generation. This crate is intended mainly for use by Signer.

Input

Identicon is generated for &[u8] input slice. During identicon generation, this input slice gets hashed, therefore, any length would be acceptable.

Typical input slice is a public key. Public key is often encountered as a hexadecimal string (d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d) or as a base58 network-specific string (5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY), both could be easily transformed into &[u8] input.

Crate also supports generation of identicon-like images with user-provided colors in RGBA format.

PNG

Signer uses images in png format, since svg format is not sufficiently supported on devices side and might be non-deterministic. Therefore, this crate sticks mostly to png generation. Feature "pix" (enabled by default) enables generation of png images.

Function generate_png produces png data for identicon, and requires:

  • &[u8] slice
  • target image size in pixels (u16)
    png images are generated pixel-by-pixel, and the quality of final image is determined by the image size. Each png pixel (with integer coordinates) falling within the identicon circle element (with float circle parameters) gets the color of the circle. Below certain image size (approximately 100 pix) the circles become too pixelated. Also, images with even number of pixels size are off-centered by a pixel.

Signer needs small png identicon icons. Exact parameters are yet TBD (at the moment, identicons are 30 pix and device-independent), however, the straightforward approach with generate_png does not produce acceptable results.

Possible solution is to generate larger identicon and then scale it down in Signer frontend, but it was noticed that the scaling results (pixelation, color distribution) are device-dependent and although a minor thing, it should definitely be avoided in identicon.

To generate reproducible small identicons, the rescaling is performed within the crate. A larger png is generated, and then scaled down to originally desired size. This procedure results in both less pixelated circles and compensated off-centering.

Function generate_png_scaled_custom performs the scaling with custom parameters, and requires:

  • &[u8] slice
  • target identicon size in pixels (u8 - it is for small identicons, after all)
  • scaling factor (u8), how much larger the larger png actually is
  • filter (FilterType) used for image resize

The scaling factor reasonable values are in range [4..=8], below it the pixelation persists, above it the images are not visibly improving anymore, and may even seem blurry.

All filters produce reasonable results, except FilterType::Nearest that yields visibly distorted images and therefore is not recommended.

Function generate_png_scaled_default performs the scaling with default scaling parameters (scaling factor 5 and filter FilterType::Lanczos3) for image with default Signer identicon size (30 pix), and requires only:

  • &[u8] slice
    If somehow the generation of the identicon fails, function outputs default-sized (30x30) transparent png image, i.e. it never produces an error.

Function generate_png_with_colors is similar to generate_png, but accepts identicon colors directly, and does not generate color set itself. This is intended mainly for tests. Function generate_png_with_colors requires:

  • [[u8; 4]; 19] 19-element set of colors in RGBA format
  • target image size in pixels (u16)

Function generate_png_scaled_custom_with_colors is similar to generate_png_scaled_custom, but accepts identicon colors directly, and does not generate color set itself. This is intended mainly for tests. Function generate_png_scaled_custom_with_colors requires:

  • [[u8; 4]; 19] 19-element set of colors in RGBA format
  • target identicon size in pixels (u8)
  • scaling factor (u8)
  • filter (FilterType) used for image resize

SVG

Feature "vec" (enabled by default) enables infallible generation of identicon pictures in svg format. Since svg is a vector format, no image size parameters are needed.

Function generate_svg reqires only &[u8] input slice.

Function generate_svg_with_colors uses pre-set colors and is intended mainly for tests. It requires only the color set ([[u8; 4]; 19] 19-element set of colors in RGBA format).

Tests and Examples

Tests in colors.rs module check if the color sets calculated for Alice and Bob are identical to the colors in the corresponding well-known icons.

Doc tests in lib.rs produce various test pics, both png (through different functions and parameters) and svg.

Notes

There are several uncertainties about how the original published code was designed to work, those should be clarified, eventually.

For example, calculated HSL color saturation could range 30..109, and is processed as percents. Crate palette (currently used here) processes saturation values over 100 as percents over 100, and gives some results (slightly different from results for 100% saturation), but it is necessary to check if the calculations in js and here are matching.

See details in code comments.

Download Details:
Author: paritytech
Source Code: https://github.com/paritytech/polkadot-identicon-rust
License: Apache-2.0 License

#blockchain #rust  #polkadot  #smartcontract  #substrate #rust