Skip to content
XavionMPublic

About

Mahjong hand analyzer: precomputed target sets scanned by a memory-mapped C engine, exposed through ctypes and Android JNI, with a FastAPI web app and a React Native app.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Mahjong Analyzer

Mahjong Analyzer

Give it a 14-tile Mahjong hand — typed or photographed — and it tells you which scoring hands you are closest to, accounting for jokers, exposed tiles, and tiles already visible on the field.

Runs locally as a FastAPI web app or as an Android app. There is no hosted demo yet — see Roadmap.


Why this exists

The naive version of this problem is easy to state and brutal to compute.

"How close am I to each scoring hand?" is not a lookup. A scoring hand like Wriggly Snake isn't one arrangement of tiles — it's every arrangement that satisfies the pattern, across every suit, with every legal joker substitution. Enumerate all 86 scoring hands that way and you get 21,235,279 distinct target configurations for a single seat wind.

I wrote that in Python first. It worked, and it was unusable:

build_targets("WE")   116.0 s     21,235,279 targets held in memory
evaluate_hand(...)      9.5 s     one 14-tile hand scanned against them
                     ────────
cold start            125.4 s     per query

Two minutes to answer one question, and the whole target set had to be rebuilt from scratch every time the process restarted. No amount of micro-optimizing Python was going to close a gap that size — the work was 21 million tight integer comparisons, which is the one thing CPython is worst at.

So I stopped trying to make the scan faster and changed what gets scanned.

Precompute, then memory-map

Target generation is deterministic: for a given seat wind, the answer never changes. That makes it a build-time problem, not a runtime one. generate_binary.py enumerates every configuration once and writes a flat binary (.mhj) laid out for sequential scanning:

┌──────────────────────────────────────────────────────┐
│ header    'MHJ1' + version + counts + section offsets│  24 B
├──────────────────────────────────────────────────────┤
│ hand types   name, concealed/exposed, points, text,  │
│              and (start, count) into the target array│  1 per hand
├──────────────────────────────────────────────────────┤
│ targets   ┌─ 1 B  hand_type_id                       │
│           └─ 34 B tile counts, one byte per tile     │  35 B × N
└──────────────────────────────────────────────────────┘

One record is 35 bytes: a hand-type id plus a 34-byte histogram, one byte per distinct tile in the game. No pointers, no deserialization, no object graph — a target is just an offset, and scanning is a linear walk over bytes the CPU can prefetch.

The file is never read() into memory. It's mapped, so the OS pages in only the regions actually touched and the same physical pages are shared across processes:

#ifdef _WIN32
    m->hMap = CreateFileMappingA(m->hFile, NULL, PAGE_READONLY, 0, 0, NULL);
    m->data = (const char *)MapViewOfFile(m->hMap, FILE_MAP_READ, 0, 0, 0);
#else
    m->data = (const char *)mmap(NULL, m->size, PROT_READ, MAP_PRIVATE, m->fd, 0);
    madvise((void *)m->data, m->size, MADV_SEQUENTIAL);
#endif

MADV_SEQUENTIAL matters more than it looks: the scan is a pure forward sweep, so telling the kernel to read ahead aggressively and drop pages behind it keeps a 161 MB file running in a small resident set.

Factoring out the pathological case

One hand dominated the precompute. Seven Twins is "any seven pairs" — combinatorially enormous, and 16,417,104 of the 21.2 M configurations were that single hand. Storing them was 77% of the file for 1 of 86 hands.

But "is this hand seven pairs?" is a two-line check, not a search. So generate_binary.py excludes it from the binary and the C engine evaluates it algorithmically:

ALGORITHMIC_HANDS = {'SEVEN TWINS'}

That drops the stored set from 21.2 M to 4,818,175 targets per wind — a 4.4× smaller file and a 4.4× shorter scan, with identical results.

Results

Measured on an AMD Ryzen 9 9900X (12-core), 64 GB RAM, Windows 11, over data/targets_WE.mhj:

Pure Python C engine + mmap
Load target set 116.0 s (rebuild) 2.7 ms (mmap) ~43,000×
Evaluate one hand 9,458 ms 68 – 217 ms ~47×
Cold start to first answer 125.4 s ~0.2 s ~600×

Per-hand timings are medians of 7 runs after a warm page cache; the range reflects hand complexity — a hand with many joker placements costs more than one that prunes early.

The Python implementation is still in the tree and still correct. It runs automatically when the compiled engine or the binaries are missing, so the project degrades to slow-but-working rather than broken.


Architecture

International_Mahjong_Hands.csv   86 scoring hands: type, points, criteria
              │
              ▼
         mahjong.py                Python core — hand patterns, target
              │                    enumeration, scoring, pure-Python fallback
              ▼
    generate_binary.py             precompute → data/targets_{WE,WS,WW,WN}.mhj
              │
              ▼
    engine/mhj_engine.c            C scanner — Win32 CreateFileMapping /
              │                    POSIX mmap + madvise, joker assignment,
              │                    distance ranking
        ┌─────┴─────┐
        ▼           ▼
  mhj_bindings.py   mhj_jni.c      ctypes (desktop)  |  JNI (Android)
        │           │
        ▼           ▼
     app.py      MahjongApp        FastAPI + static web UI  |  React Native
   :8000         (Android)

Both bindings compile the same scanner source rather than reimplementing it. The Android build keeps a copy of mhj_engine.c and mhj_engine.h under MahjongApp/android/app/src/main/jni/, compiles it through CMake alongside mhj_jni.c, and ships the .mhj files as APK assets, so the phone runs the same scanning logic as the desktop. The two copies are currently byte-identical; keeping them that way is manual, and that is the weak point of this layout.

Path What it is
mahjong.py Hand patterns, target enumeration, scoring, pure-Python fallback
generate_binary.py Writes the .mhj binaries and copies them into the Android assets
engine/mhj_engine.c The scanner — mmap, joker assignment, distance ranking
mhj_bindings.py ctypes wrapper (MhjEngine)
app.py FastAPI server: /api/analyze, /api/vision
public/ Web front end
MahjongApp/ React Native Android app
MahjongApp/…/jni/ Android copy of the engine plus mhj_jni.c and CMakeLists.txt
helpers/ One-off scripts that transcribed the scoring tables into CSV

Quickstart

Requirements: Python 3.10+, a C compiler (gcc — TDM-GCC on Windows), and ~644 MB of free disk.

git clone https://github.com/XavionM/Mahjong.git
cd Mahjong
pip install fastapi uvicorn pillow google-genai pydantic

Generate the data first — the repo ships without it

A fresh clone cannot run until you do this step. The four .mhj binaries total ~644 MB, so they are deliberately not committed. They are generated, not authored — this step reproduces them exactly:

python generate_binary.py

Takes roughly two minutes per wind on the machine above — target enumeration alone is ~81 s — and writes data/targets_{WE,WS,WW,WN}.mhj (161 MB each), copying every file into MahjongApp/android/app/src/main/assets/data/ for the Android build. To build a single seat wind while developing:

python generate_binary.py WE

If data/ is missing or empty, the app falls back to the pure-Python path and every query takes roughly two minutes. That is the symptom of a skipped step, not a bug.

Build the C engine

./build_engine.bat

On Linux/macOS:

gcc -shared -fPIC -O2 -o engine/libmhj_engine.so engine/mhj_engine.c -lm

Run the web app

python -m uvicorn app:app --port 8000 --reload

Then open http://localhost:8000.

Run the Android app

cd MahjongApp
npm install
npx react-native run-android

See walkthrough.md for release bundling and adb deployment.


Photo-to-tiles (bring your own API key)

Typing 14 tiles is tedious, so you can photograph the hand instead and have a vision model read it. This is the one feature that needs a credential, and no key ships with this repo.

  • Android — enter your key in Settings; it is stored on-device with AsyncStorage and never leaves the phone except in the request to Google.
  • Web / scripts — set GEMINI_API_KEY in your environment:
cp .env.example .env    # then edit it
export GEMINI_API_KEY=your-key-here

Get a key at aistudio.google.com/apikey. Everything else — typed hands, scoring, ranking — works with no key at all.


A note on the hand data

International_Mahjong_Hands.csv is the source table for the 86 scoring hands this engine recognizes. The rules of Mahjong are not anyone's property, but the wording used to describe them can be, so every criteria string here is written from scratch rather than copied from any published source. The photographed pages originally used to compile the list are not part of this repository.

Two details worth knowing if you read the table closely: Hachi Ban appears twice with equivalent criteria, and mahjong.py splits Dragon's Tail into a first and second version, so the CSV's 86 rows and the binary's 86 hand types line up in count but not one-to-one.


Roadmap

  • Android release on Google Play. The app builds and runs today; the remaining work is signing, store assets, and shrinking the ~644 MB of target data to something shippable over the wire.
  • Mac App Store release. The C engine is already POSIX-clean (mmap + madvise), so the scanning core ports without changes; the front end does not exist yet.
  • A hosted demo, so the project can be tried without a local build.

License

MIT © 2026 Xavion Mirchandani


Built by Xavion Mirchandani — xavion.me · @XavionM

About

Mahjong hand analyzer: precomputed target sets scanned by a memory-mapped C engine, exposed through ctypes and Android JNI, with a FastAPI web app and a React Native app.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages