How can I fix this code that uses a HashMap<i32, PriorityQueue<i32, i32>> to sort a matrix diagonally?

grokus

This is the c++ solution to this programming problem (LeetCode 1329. Sort the Matrix Diagonally).

vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {
    int m = mat.size();
    int n = mat[0].size();
    map<int, priority_queue<int>> mq;
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            mq[i - j].push(-mat[i][j]);
        }
    }
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            priority_queue<int>& q = mq[i - j];
            mat[i][j] = -q.top();
            q.pop();
        }
    }
    return mat;
}

When I was converting this C++ code to Rust, I ran into a problem that I couldn't figure out.

use std::collections::HashMap;
use priority_queue::PriorityQueue;

fn diagonal_sort(mat: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
    let mut mat = mat.clone();
    let m = mat.len();
    let n = mat[0].len();
    let mut mq: HashMap<i32, PriorityQueue<i32, i32>> = HashMap::new();
    println!("m {}, n {}", m, n);
    for i in 0..mat.len() {
        for j in 0..mat[0].len() {
            mq.entry(i as i32 - j as i32).or_insert(PriorityQueue::new()).push(mat[i][j], mat[i][j]);
        }
    }
    for i in 0..mat.len() {
        for j in 0..mat[0].len() {
            // Ideally, how do I pop here and use the results directly?
            let res = mq[&(i as i32 - j as i32)].peek();
            mat[i][j] = *(match res {
                Some((x, _y)) => x,
                None => &(-1),
            });
            // Or how do I pop from the priority queue here without peeking?
            // mq[&(i as i32 - j as i32)].pop();
        }
    }
    mat
}
wasmup

Pop from the priority queue here without peeking:

 let v = d.get_mut(&key).unwrap();
 mat[i][j] = v.pop().unwrap().0;

Result (output):

input:
9 8 7
6 5 4
3 2 1
output:
1 4 7
2 5 8
3 6 9

And you may use std::cmp::Reverse for reverse ordering:

use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::collections::HashMap;

pub fn diagonal_sort(mat: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
    let mut mat = mat.clone();
    let mut mh: HashMap<i32, BinaryHeap<_>> = HashMap::new();
    for i in 0..mat.len() {
        for j in 0..mat[0].len() {
            let key = i as i32 - j as i32;
            mh.entry(key)
                .or_insert(BinaryHeap::new())
                .push(Reverse(mat[i][j]));
        }
    }
    for i in 0..mat.len() {
        for j in 0..mat[0].len() {
            let key = i as i32 - j as i32;
            let q = mh.get_mut(&key).unwrap();
            match q.pop().unwrap() {
                Reverse(v) => mat[i][j] = v,
            }
        }
    }
    mat
}

fn main() {
    let m = vec![vec![9, 8, 7], vec![6, 5, 4], vec![3, 2, 1]];
    show("input:", &m);
    let s = diagonal_sort(m);
    show("output:", &s);
}
fn show(s: &str, mat: &Vec<Vec<i32>>) {
    println!("{}", s);
    let m = mat.len();
    let n = mat[0].len();
    for i in 0..m {
        for j in 0..n {
            print!("{} ", mat[i][j]);
        }
        println!();
    }
}


Result (output):

input:
9 6 3
8 5 2
7 4 1
output:
1 2 3
4 5 6
7 8 9

Try this (for diagonally distinct elements):

use priority_queue::PriorityQueue;
use std::collections::HashMap;

fn diagonal_sort(mat: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
    let mut d: HashMap<i32, PriorityQueue<i32, i32>> = HashMap::new();
    let mut mat = mat.clone();
    let m = mat.len();
    let n = mat[0].len();
    for i in 0..m {
        for j in 0..n {
            let key = i as i32 - j as i32;
            let v = -mat[i][j];
            d.entry(key).or_insert(PriorityQueue::new()).push(v, v);
        }
    }

    for i in 0..m {
        for j in 0..n {
            let key = i as i32 - j as i32;
            let v = d.get_mut(&key).unwrap();
            mat[i][j] = -v.pop().unwrap().0;
        }
    }
    mat
}

fn main() {
    let m = vec![vec![9, 6, 3], vec![8, 5, 2], vec![7, 4, 1]];
    show("input:", &m);
    let s = diagonal_sort(m);
    show("output:", &s);
}
fn show(s: &str, mat: &Vec<Vec<i32>>) {
    println!("{}", s);
    let m = mat.len();
    let n = mat[0].len();
    for i in 0..m {
        for j in 0..n {
            print!("{} ", mat[i][j]);
        }
        println!();
    }
}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

행렬을 대각선으로 정렬하기 위해 HashMap <i32, PriorityQueue <i32, i32 >>를 사용하는이 코드를 어떻게 수정할 수 있습니까?

분류에서Dev

Rust 오류 예상 유형`()`발견 유형`(i32, i32)`

분류에서Dev

유형이 일치하지 않는 오류 : 'collections :: vec :: Vec <i32>'예상, '& collections :: vec :: Vec <i32>'발견

분류에서Dev

오류 : 비 스칼라 캐스트 :`core :: option :: Option <i32>`as`usize`

분류에서Dev

WebAssembly에서 "i32"유형의 값은 어떻게 평가됩니까?

분류에서Dev

i32 숫자의 Vec <>를 문자열로 결합하려면 어떻게해야합니까?

분류에서Dev

텍스트 파일의 줄을 i32의 튜플 벡터로 어떻게 읽어들일까요?

분류에서Dev

4 요소 & [u8]을 i32로 변환하는 방법은 무엇입니까?

분류에서Dev

How can I foreach a hashmap?

분류에서Dev

Rust가 스레드를 스페이싱하는 동안 i32의 경우 이동을 강제로 사용하는 이유는 무엇입니까?

분류에서Dev

VHDL: How can I shorten a 32bit expression?

분류에서Dev

How can I pack a Date and Time into 32-bits?

분류에서Dev

How can I fix my Boot problem?

분류에서Dev

How can I bloat a numpy matrix?

분류에서Dev

How can I program two simultaneous key press events in tkinter to move a canvas item diagonally using a dictionary of keypress events?

분류에서Dev

How can I sort 5 positive integers?

분류에서Dev

프로그램의 메인이 i32를 반환하는 경우 $는 왜입니까? (그것을 호출 한 쉘에서 측정 한대로) 8 비트로 잘렸습니까?

분류에서Dev

How can I fix a pdf that can only be opened with mupdf?

분류에서Dev

How can I get a column of value from hashmap

분류에서Dev

How can I use a custom hash function in a HashSet or HashMap?

분류에서Dev

how do I fix this code - variable not defined in function

분류에서Dev

How can I use CURAND_RNG_QUASI_SOBOL32 generator using device API? CUDA

분류에서Dev

How can I switch a 32-bit installation to a 64-bit one?

분류에서Dev

Java plugin doesn't work in Chrome -- how can I fix this?

분류에서Dev

How can I fix "dpkg: error: parsing file"?

분류에서Dev

how can I fix time duration to fill up a form

분류에서Dev

How can I fix my Debian's /etc/network/interfaces?

분류에서Dev

How can I fix this error on fetching text from pastebin?

분류에서Dev

Why is JavaCC not working on my mac and how can I fix it?

Related 관련 기사

  1. 1

    행렬을 대각선으로 정렬하기 위해 HashMap <i32, PriorityQueue <i32, i32 >>를 사용하는이 코드를 어떻게 수정할 수 있습니까?

  2. 2

    Rust 오류 예상 유형`()`발견 유형`(i32, i32)`

  3. 3

    유형이 일치하지 않는 오류 : 'collections :: vec :: Vec <i32>'예상, '& collections :: vec :: Vec <i32>'발견

  4. 4

    오류 : 비 스칼라 캐스트 :`core :: option :: Option <i32>`as`usize`

  5. 5

    WebAssembly에서 "i32"유형의 값은 어떻게 평가됩니까?

  6. 6

    i32 숫자의 Vec <>를 문자열로 결합하려면 어떻게해야합니까?

  7. 7

    텍스트 파일의 줄을 i32의 튜플 벡터로 어떻게 읽어들일까요?

  8. 8

    4 요소 & [u8]을 i32로 변환하는 방법은 무엇입니까?

  9. 9

    How can I foreach a hashmap?

  10. 10

    Rust가 스레드를 스페이싱하는 동안 i32의 경우 이동을 강제로 사용하는 이유는 무엇입니까?

  11. 11

    VHDL: How can I shorten a 32bit expression?

  12. 12

    How can I pack a Date and Time into 32-bits?

  13. 13

    How can I fix my Boot problem?

  14. 14

    How can I bloat a numpy matrix?

  15. 15

    How can I program two simultaneous key press events in tkinter to move a canvas item diagonally using a dictionary of keypress events?

  16. 16

    How can I sort 5 positive integers?

  17. 17

    프로그램의 메인이 i32를 반환하는 경우 $는 왜입니까? (그것을 호출 한 쉘에서 측정 한대로) 8 비트로 잘렸습니까?

  18. 18

    How can I fix a pdf that can only be opened with mupdf?

  19. 19

    How can I get a column of value from hashmap

  20. 20

    How can I use a custom hash function in a HashSet or HashMap?

  21. 21

    how do I fix this code - variable not defined in function

  22. 22

    How can I use CURAND_RNG_QUASI_SOBOL32 generator using device API? CUDA

  23. 23

    How can I switch a 32-bit installation to a 64-bit one?

  24. 24

    Java plugin doesn't work in Chrome -- how can I fix this?

  25. 25

    How can I fix "dpkg: error: parsing file"?

  26. 26

    how can I fix time duration to fill up a form

  27. 27

    How can I fix my Debian's /etc/network/interfaces?

  28. 28

    How can I fix this error on fetching text from pastebin?

  29. 29

    Why is JavaCC not working on my mac and how can I fix it?

뜨겁다태그

보관