Skip to content

Commit

Permalink
Add problem 1409: Queries on a Permutation With Key
Browse files Browse the repository at this point in the history
  • Loading branch information
Spxg committed Dec 17, 2024
1 parent 9c4e6ab commit 7774d80
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,7 @@ pub mod problem_1390_four_divisors;
pub mod problem_1395_count_number_of_teams;
pub mod problem_1396_design_underground_system;
pub mod problem_1405_longest_happy_string;
pub mod problem_1409_queries_on_a_permutation_with_key;
pub mod problem_1417_reformat_the_string;
pub mod problem_1418_display_table_of_food_orders_in_a_restaurant;
pub mod problem_1433_check_if_a_string_can_break_another_string;
Expand Down
22 changes: 22 additions & 0 deletions src/problem_1409_queries_on_a_permutation_with_key/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
pub mod rotate;

pub trait Solution {
fn process_queries(queries: Vec<i32>, m: i32) -> Vec<i32>;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [
((&[3, 1, 2, 1] as &[_], 5), &[2, 1, 2, 1] as &[_]),
((&[4, 1, 2, 2], 4), &[3, 1, 2, 0]),
((&[7, 5, 5, 8, 3], 8), &[6, 5, 0, 7, 5]),
];

for ((queries, m), expected) in test_cases {
assert_eq!(S::process_queries(queries.to_vec(), m), expected);
}
}
}
28 changes: 28 additions & 0 deletions src/problem_1409_queries_on_a_permutation_with_key/rotate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
pub struct Solution;

impl Solution {
pub fn process_queries(queries: Vec<i32>, m: i32) -> Vec<i32> {
let mut result = Vec::with_capacity(queries.len());
let mut nums: Vec<i32> = (1..=m).collect();
for query in queries {
let pos = nums.iter().position(|&x| x == query).unwrap();
result.push(pos as i32);
nums[0..=pos].rotate_right(1);
}
result
}
}

impl super::Solution for Solution {
fn process_queries(queries: Vec<i32>, m: i32) -> Vec<i32> {
Self::process_queries(queries, m)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}

0 comments on commit 7774d80

Please sign in to comment.