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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
// use rand::random_range;
use std::array::from_fn;
use std::collections::{HashMap, HashSet};
use std::fmt::{Debug, Formatter, Result};

macro_rules! input {
    (from $iter:expr, $($r:tt)*) => {
        input_inner!{$iter, $($r)*}
    };
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

#[derive(PartialEq, Eq, Hash, Clone)]
struct Matrix<const N: usize, const M: usize = N> {
    data: [[u8; N]; M],
}

impl<const N: usize, const M: usize> Matrix<N, M> {
    fn new(data: [[u8; N]; M]) -> Self {
        Self { data }
    }

    fn get_sub_matrix<const SUB_N: usize, const SUB_M: usize>(
        &self,
        start_i: usize,
        start_j: usize,
    ) -> Matrix<SUB_N, SUB_M> {
        let mut result = [[0u8; SUB_N]; SUB_M];

        for i in 0..SUB_N {
            for j in 0..SUB_M {
                result[i][j] = self.data[start_i + i][start_j + j];
            }
        }

        Matrix::<SUB_N, SUB_M>::new(result)
    }

    fn insert_sub_matrix<const SUB_N: usize, const SUB_M: usize>(
        &mut self,
        start_i: usize,
        start_j: usize,
        sub_matrix: Matrix<SUB_N, SUB_M>,
    ) {
        for i in 0..SUB_M {
            for j in 0..SUB_N {
                self.data[start_i + i][start_j + j] = sub_matrix.data[i][j];
            }
        }
    }

    fn shuffle(&mut self) {
        self.shuffle_rows();
        self.shuffle_columns();
    }

    fn shuffle_rows(&mut self) {
        // for i in (1..N).rev() {
        //     let j = random_range(0..=i);

        //     // eprintln!("swap row {} with {}", i, j);

        //     self.data.swap(i, j);
        // }
    }

    fn shuffle_columns(&mut self) {
        // for col in (1..M).rev() {
        //     let target = random_range(0..=col);

        //     // eprintln!("swap column {} with {}", col, target);

        //     for row in 0..M {
        //         self.data[row].swap(col, target);
        //     }
        // }
    }

    fn swap_row(&mut self, i: usize, j: usize) {
        self.data.swap(i, j);
    }

    fn swap_column(&mut self, i: usize, j: usize) {
        for row in 0..N {
            self.data[row].swap(i, j);
        }
    }

    fn get_columns_from_binary(&self) -> Vec<u8> {
        (3..N)
            .map(|col| binary_to_value(&from_fn(|row| self.data[row][col])))
            .collect::<Vec<_>>()
    }

    fn get_rows_from_binary(&self) -> Vec<u8> {
        (3..N)
            .map(|row| binary_to_value(&from_fn(|col| self.data[row][col])))
            .collect::<Vec<_>>()
    }

    fn get_missing_column(&self) -> u8 {
        let columns = self.get_columns_from_binary();
        let valid_columns = vec![0, 1, 2, 3, 4, 5, 6, 7];
        let columns_set: HashSet<_> = columns.iter().collect();
        let missing_columns: Vec<_> = valid_columns
            .iter()
            .filter(|x| !columns_set.contains(x))
            .collect();

        if missing_columns.len() > 1 {
            panic!("Missing column: {:?}", missing_columns);
        }

        missing_columns.into_iter().next().cloned().unwrap()
    }

    fn get_missing_row(&self) -> u8 {
        let rows = self.get_rows_from_binary();
        let valid_rows = vec![0, 1, 2, 3, 4, 5, 6, 7];
        let rows_set: HashSet<_> = rows.iter().collect();
        let missing_rows: Vec<_> = valid_rows
            .iter()
            .filter(|x| !rows_set.contains(x))
            .collect();

        if missing_rows.len() > 1 {
            panic!("Missing column: {:?}", missing_rows);
        }

        missing_rows.into_iter().next().cloned().unwrap()
    }

    fn fix_ordering(&mut self) {
        let mut columns = self.get_columns_from_binary();
        let mut rows = self.get_rows_from_binary();

        let missing_column = self.get_missing_column();
        let missing_row = self.get_missing_row();

        for i in 0..columns.len() {
            if columns[i] > missing_column {
                columns[i] -= 1;
            }
        }
        for i in 0..rows.len() {
            if rows[i] > missing_row {
                rows[i] -= 1;
            }
        }

        // eprintln!("columns: {:?}, rows: {:?}", columns, rows);

        for i in 0..rows.len() {
            let source = i + 3;
            let target = rows.iter().position(|&r| r == i as u8).unwrap();

            // eprintln!("swapping row {source} with row {target}");

            self.swap_row(source, target + 3);
            rows.swap(i, target);
        }

        for i in 0..columns.len() {
            let source = i + 3;
            let target = columns.iter().position(|&r| r == i as u8).unwrap();

            // eprintln!(
            //     "swapping columns {source} with row {target}"
            // );

            self.swap_column(source, target + 3);
            columns.swap(i, target);
        }
    }

    fn unshuffle(&mut self, valid_qrs: &[Matrix<3>]) {
        let valid_qrs_set: HashSet<_> = valid_qrs.iter().map(|qr| qr.data).collect();
        let mut valid_matrixes: Vec<Matrix<N, M>> = Vec::new();
        let qr1 = Matrix::new([
            get_last_n_bits::<3>(0 as u128),
            get_last_n_bits::<3>(1 as u128),
            get_last_n_bits::<3>(3 as u128),
        ]);
        let qr2 = Matrix::new([
            get_last_n_bits::<3>(1 as u128),
            get_last_n_bits::<3>(3 as u128),
            get_last_n_bits::<3>(7 as u128),
        ]);

        // eprintln!("valid_qrs_set: {:?}", valid_qrs_set);

        for i1 in 0..N {
            for i2 in 0..N {
                for i3 in 0..N {
                    let rows = [i1, i2, i3];

                    for j1 in 0..N {
                        for j2 in 0..N {
                            for j3 in 0..N {
                                let cols = [j1, j2, j3];
                                let mut shuffled_matrix = Matrix::new(self.data.clone());

                                // eprintln!("{rows:?} {cols:?}");

                                shuffled_matrix.swap_row(0, rows[0]);
                                shuffled_matrix.swap_row(1, rows[1]);
                                shuffled_matrix.swap_row(2, rows[2]);
                                shuffled_matrix.swap_column(0, cols[0]);
                                shuffled_matrix.swap_column(1, cols[1]);
                                shuffled_matrix.swap_column(2, cols[2]);

                                let qr = shuffled_matrix.get_sub_matrix::<3, 3>(0, 0);

                                if valid_qrs_set.contains(&qr.data) {
                                    let columns = shuffled_matrix.get_columns_from_binary();
                                    let rows = shuffled_matrix.get_rows_from_binary();
                                    let rows_set =
                                        rows.iter().collect::<std::collections::HashSet<_>>();
                                    let columns_set =
                                        columns.iter().collect::<std::collections::HashSet<_>>();

                                    if rows_set.len() == 7 && columns_set.len() == 7 {
                                        let missing_column = shuffled_matrix.get_missing_column();
                                        let missing_row = shuffled_matrix.get_missing_row();

                                        shuffled_matrix.fix_ordering();

                                        // eprintln!("{shuffled_matrix:?}");
                                        // eprintln!("columns: {columns:?}");
                                        // eprintln!("{columns_set:?}");
                                        // eprintln!("rows: {rows:?}");
                                        // eprintln!("{rows_set:?}");
                                        // eprintln!(
                                        //     "missing column {missing_column}, missing row {missing_row}"
                                        // );

                                        // eprintln!("{shuffled_matrix:?}");

                                        if (qr == qr1 && missing_column == 0 && missing_row == 0)
                                            || ((qr == qr2)
                                                && (missing_column > 0 || missing_row > 0))
                                        {
                                            self.data = shuffled_matrix.data;
                                            valid_matrixes.push(shuffled_matrix);
                                            return;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        eprintln!("{valid_matrixes:#?}");
        eprintln!(
            "{}",
            valid_matrixes
                .windows(2)
                .all(|w| w[0].get_sub_matrix::<7, 7>(3, 3) == w[1].get_sub_matrix::<7, 7>(3, 3))
        );

        eprintln!("{N} {M}");

        assert!(
            valid_matrixes
                .windows(2)
                .all(|w| w[0].get_sub_matrix::<7, 7>(3, 3) == w[1].get_sub_matrix::<7, 7>(3, 3))
        );

        let mut result = valid_matrixes.into_iter().next().unwrap();

        result.fix_ordering();

        self.data = result.data;
    }
}

impl<const N: usize, const M: usize> Debug for Matrix<N, M> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        // writeln!(f)?;
        for row in &self.data {
            for &val in row {
                write!(f, "{}", val)?;
            }
            writeln!(f)?;
        }
        Ok(())
    }
}

fn binary_to_value(binary: &[u8; 3]) -> u8 {
    (binary[0] << 2) | (binary[1] << 1) | binary[2]
}

fn get_last_n_bits<const N: usize>(n: u128) -> [u8; N] {
    from_fn(|i| ((n >> (N - 1 - i)) & 1) as u8)
}

fn encode_qr(n: u128, valid_qrs: &[Matrix<3>]) -> Matrix<3> {
    // valid_qrs[n as usize].clone()
    valid_qrs[0].clone()
}

fn encode_number(n: u128) -> Matrix<7> {
    let bits = get_last_n_bits::<49>(n);
    let result: [[u8; 7]; 7] = unsafe { std::mem::transmute(bits) };

    Matrix::<7>::new(result)
}

fn decode_number(matrix: &Matrix<7>) -> u128 {
    let mut n: u128 = 0;

    for i in 0..7 {
        for j in 0..7 {
            let bit_pos = 48 - (i * 7 + j);
            n |= (matrix.data[i][j] as u128 & 1) << bit_pos;
        }
    }

    n
}

fn decode_qr(matrix: &Matrix<3>, valid_qrs: &[Matrix<3>]) -> u128 {
    valid_qrs.iter().position(|valid| matrix == valid).unwrap() as u128
}

fn decode(matrix: &Matrix<10, 10>, valid_qrs: &[Matrix<3, 3>]) -> u128 {
    let qr = matrix.get_sub_matrix::<3, 3>(0, 0);
    let number_matrix = matrix.get_sub_matrix::<7, 7>(3, 3);

    // eprintln!("qr: {:?}, number: {:?}", qr, number_matrix);

    let qr_value = decode_qr(&qr, valid_qrs);
    let number_value = decode_number(&number_matrix);

    // eprintln!("qr_value: {}, number_value: {}", qr_value, number_value);

    let missing_column = matrix.get_missing_column();
    let missing_row = matrix.get_missing_row();

    let mut result: u128 = (missing_row as u128) << 52;

    result += (missing_column as u128) << 49;

    result += number_value;

    // eprintln!(
    //     "missing_column: {:?}, missing_row: {:?}",
    //     missing_column, missing_row
    // );

    result
}

fn encode(n: u128, valid_qrs: &[Matrix<3>]) -> Matrix<10> {
    let mut form: Matrix<10> = Matrix::new([
        [3, 3, 3, 0, 0, 0, 1, 1, 1, 1],
        [3, 3, 3, 0, 1, 1, 0, 0, 1, 1],
        [3, 3, 3, 1, 0, 1, 0, 1, 0, 1],
        [0, 0, 1, 2, 2, 2, 2, 2, 2, 2],
        [0, 1, 0, 2, 2, 2, 2, 2, 2, 2],
        [0, 1, 1, 2, 2, 2, 2, 2, 2, 2],
        [1, 0, 0, 2, 2, 2, 2, 2, 2, 2],
        [1, 0, 1, 2, 2, 2, 2, 2, 2, 2],
        [1, 1, 0, 2, 2, 2, 2, 2, 2, 2],
        [1, 1, 1, 2, 2, 2, 2, 2, 2, 2],
    ]);
    let number_matrix = encode_number(n);

    // eprintln!("{:?}", get_last_n_bits::<55>(n));

    let mut leftover = n >> 49;

    // eprintln!("leftover: {}", leftover);

    let qr = if leftover == 0 {
        Matrix::new([
            get_last_n_bits::<3>(0 as u128),
            get_last_n_bits::<3>(1 as u128),
            get_last_n_bits::<3>(3 as u128),
        ])
    } else {
        Matrix::new([
            get_last_n_bits::<3>(1 as u128),
            get_last_n_bits::<3>(3 as u128),
            get_last_n_bits::<3>(7 as u128),
        ])
    };

    let column_bits = get_last_n_bits::<3>(leftover);

    leftover >>= 3;

    let row_bits = get_last_n_bits::<3>(leftover);

    let missing_column = binary_to_value(&column_bits);
    let missing_row = binary_to_value(&row_bits);

    let mut rows = vec![0, 1, 2, 3, 4, 5, 6, 7];
    let mut columns = vec![0, 1, 2, 3, 4, 5, 6, 7];

    rows.retain(|&x| x != missing_row);
    columns.retain(|&x| x != missing_column);

    // eprintln!("rows: {:?}, columns: {:?}", rows, columns);

    for (idx, &row) in rows.iter().enumerate() {
        // eprintln!("row: {:?}", row);

        form.insert_sub_matrix(3 + idx, 0, Matrix::new([get_last_n_bits::<3>(row as u128)]));
    }

    for (idx, &column) in columns.iter().enumerate() {
        // eprintln!("column: {:?}", column);
        let value = get_last_n_bits::<3>(column as u128);

        form.insert_sub_matrix(
            0,
            3 + idx,
            Matrix::new([[value[0]], [value[1]], [value[2]]]),
        );
    }

    // eprintln!(
    //     "missing_column: {:?}, missing_row: {:?}",
    //     missing_column, missing_row
    // );
    // eprintln!("column_bits: {:?}, row_bits: {:?}", column_bits, row_bits);

    // eprintln!("{:?}", qr);
    // eprintln!("{:?}", number_matrix);

    form.insert_sub_matrix(0, 0, qr);
    form.insert_sub_matrix(3, 3, number_matrix);

    form
}

fn get_valid_qrs() -> Vec<Matrix<3>> {
    // let mut result: Vec<Matrix<3>> = Vec::new();
    // let mut seen: HashSet<[usize; 3]> = HashSet::new();

    // for i in 0..8 {
    //     for j in 0..8 {
    //         for k in 0..8 {
    //             let mut key = [i, j, k];

    //             key.sort();

    //             if seen.insert(key) {
    //                 let qr_matrix = Matrix::new([
    //                     get_last_n_bits::<3>(i as u128),
    //                     get_last_n_bits::<3>(j as u128),
    //                     get_last_n_bits::<3>(k as u128),
    //                 ]);

    //                 result.push(qr_matrix);
    //             }
    //         }
    //     }
    // }

    // eprintln!("{seen:#?}");
    // eprintln!("valid_qrs_map: {:?}", result_map);

    // result

    vec![
        Matrix::new([
            get_last_n_bits::<3>(0 as u128),
            get_last_n_bits::<3>(1 as u128),
            get_last_n_bits::<3>(3 as u128),
        ]),
        Matrix::new([
            get_last_n_bits::<3>(1 as u128),
            get_last_n_bits::<3>(3 as u128),
            get_last_n_bits::<3>(7 as u128),
        ]),
    ]
}

fn main() {
    let stdin = std::io::stdin();
    let mut lines = stdin.lines();
    let name = lines.next().unwrap().unwrap();
    let data = lines.next().unwrap().unwrap();
    let parts: Vec<usize> = data
        .split_whitespace()
        .map(|s| s.parse().unwrap())
        .collect();
    let n = parts[0];
    let t = parts[1];

    eprintln!("name: {}, n: {}, t: {}", name, n, t);

    let valid_qrs: Vec<Matrix<3>> = get_valid_qrs();

    match name.as_str() {
        "Algosia" => {
            for _ in 0..t {
                let n: u128 = lines.next().unwrap().unwrap().trim().parse().unwrap();

                let mut encoded = encode(n, &valid_qrs);

                // eprintln!("encoded: {:?}", encoded);

                encoded.shuffle();

                print!("{:?}", encoded);
            }
        }
        "Bajtek" => {
            // eprintln!("valid_qrs: {:?}", valid_qrs);
            // eprintln!("{}", valid_qrs.len());
            // eprintln!("{:?}", get_last_n_bits::<49>(562949953421311 as u128));
            // eprintln!(
            //     "{:?}",
            //     get_last_n_bits::<49>(30000000000000000 >> 49 as u128)
            // );

            for _ in 0..t {
                let raw_matrix_vec: Vec<String> = (0..10)
                    .map(|_| lines.next().unwrap().unwrap().trim().to_string())
                    .collect();

                // eprintln!("{raw_matrix_vec:?}");

                let raw_matrix: [[u8; 10]; 10] = raw_matrix_vec
                    .iter()
                    .map(|line| {
                        let row: Vec<u8> = line.chars().map(|c| c as u8 - b'0').collect();
                        let row: [u8; 10] = row.try_into().unwrap();
                        row
                    })
                    .collect::<Vec<[u8; 10]>>()
                    .try_into()
                    .unwrap();

                let mut matrix = Matrix::new(raw_matrix);

                // eprintln!("{:?}", matrix);

                // matrix.shuffle();

                // eprintln!("{:?}", matrix);

                // matrix.shuffle();

                // eprintln!("{:?}", matrix);
                // eprintln!("------------------");

                matrix.unshuffle(&valid_qrs);

                // eprintln!("{:?}", matrix);

                let decoded_n = decode(&matrix, &valid_qrs);

                println!("{:?}", decoded_n);
            }
        }
        _ => {
            panic!("Unknown name: {}", name);
        }
    }
}