Andrija's blog

By Andrija, 6 weeks ago, In English

I would like to use this post as a proposal to add Zig as one of the available programming languages on Codeforces. It's a pretty cool, simple and effective language that I think would be great to have here.

In the meantime, I'll show you an interesting workaround on how to write your solution in Zig, and submit it to Codeforces using WebAssembly through Node.js. The process is surprisingly simple.

I'll demonstrate on the example of this problem: 2035A - Sliding. First, write your solution in Zig:

export fn solve(n: i32, m: i32, r: i32, c: i32) i64 {
    return @as(i64, 2) * m * (n — r) — n + r + m — c;
}

Compile it to WASM with this command:

  • zig build-exe sol.zig -target wasm32-freestanding -fno-entry -OReleaseSmall --export=solve

That will produce sol.wasm. To get a byte array out of that file contents, use:

  • Unix: od -An -t u1 -v sol.wasm | tr -s ' ' ',' | sed 's/^,//; s/$/,/'
  • Windows:(get-content -asbytestream -raw -path "sol.wasm") -join ','

Lastly, let's combine it into a single JavaScript source file that's ready to be submitted to CF (set Node.js as language):

// Zig solution:
//
// export fn solve(n: i32, m: i32, r: i32, c: i32) i64 {
//     return @as(i64, 2) * m * (n — r) — n + r + m — c;
// }
//
const zig_code = Uint8Array.from([
  // pasted contents of the WASM module
  0,97,115,109,1,0,0,0,1,9,1,96,4,127,127,127,127,1,126,3,2,1,0,5,3,1,0,
  16,6,9,1,127,1,65,128,128,192,0,11,7,18,2,6,109,101,109,111,114,121,2,
  0,5,115,111,108,118,101,0,0,10,36,1,34,1,1,126,32,1,172,34,4,32,2,172,
  124,32,0,172,32,3,172,124,125,32,4,32,0,32,2,107,172,126,66,1,134,124,11
]);

// Header for handling standard IO in Node.js
let input = "";
process.stdin.on('data', s => input += s);
process.stdin.on('end', _ => main());
const stdin = function*() { yield* input.split('\n'); } ();
const readline = () => stdin.next().value;
const print = console.log;

// Javascript main function (for task IO and calling to Zig)
async function main() {
  const zig = (await WebAssembly.instantiate(zig_code)).instance.exports;

  let n = readline();
  while (n--) {
    const [n, m, r, c] = readline().split(' ');
    print(zig.solve(n, m, r, c).toString());
  }
}

Here's the submission from above: 290115694.

  • Vote: I like it
  • +9
  • Vote: I do not like it

»
6 weeks ago, # |
  Vote: I like it 0 Vote: I do not like it

Wow! This is really cool!

»
6 weeks ago, # |
  Vote: I like it 0 Vote: I do not like it

I don't think the language is stable enough yet..

»
6 weeks ago, # |
  Vote: I like it +8 Vote: I do not like it

Totaly agree!!!! check my nickname, xd

»
5 weeks ago, # |
  Vote: I like it 0 Vote: I do not like it

I really hope we get Zig soon! I was considering making a proposal myself. It's nice to have the option to use Zig!

»
5 weeks ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Totally agree!!!