I thought that rewriting "Mathematical puzzles to train the programmer's brain" with Rust might be just right for preventing blurring.
Ruby
q61_2.rb
N = 20
z = Hash.new(0)
z[[0,0]] = 1
1.upto(N) do |n|
1.upto(N) do |k|
z[[n,k]] = z[[n, k - 1]] + z[[n - 1, n - k]]
end
end
puts 2 * z[[N, N]]
Somehow, in the code of book p.287, the range of the inner loop is different between Ruby and JavaScript ... The correct result is obtained in Ruby, but it happens that it is initialized with 0.
Rust
main.rs
fn main() {
println!("{}", q61());
}
pub fn q61() -> i64 {
let mut z = [[0i64; 21]; 21];
z[0][0] = 1;
for n in 1..=20 {
for k in 1..=n {
let un = n as usize;
let uk = k as usize;
z[un][uk] = z[un][uk - 1] + z[un - 1][un - uk];
}
}
return z[20][20] * 2;
}
Since the size of the array cannot be specified as a variable, it is solid for the time being. Rust is rather grateful to be panicked when something happens. When you solve the puzzle, you can rest assured that the boundary value will be recognized.
SQL
By the way, in mathematical puzzles, there are many questions that mathematically answer the question "how many patterns are there?". In actual work, even if the pattern number calculation can be used for estimation, there are many situations where "No, I want the expanded pattern itself". The main reason is "I want to create test data". I wrote the SQL version of the "alternate permutation" in this question, thinking that it might be useful for creating test data.
q61.sql
SELECT
*
FROM
(SELECT 1 AS v UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4) AS c1,
(SELECT 1 AS v UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4) AS c2,
(SELECT 1 AS v UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4) AS c3,
(SELECT 1 AS v UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4) AS c4
WHERE
(c1.v <> c2.v AND c1.v <> c3.v AND c1.v <> c4.v) AND
(c2.v <> c3.v AND c2.v <> c4.v) AND
(c3.v <> c4.v)
AND (
(c1.v < c2.v AND c2.v > c3.v AND c3.v < c4.v) OR
(c1.v > c2.v AND c2.v < c3.v AND c3.v > c4.v))
When executed, it looks like this.
+---+---+---+---+
| v | v | v | v |
+---+---+---+---+
| 4 | 2 | 3 | 1 |
| 3 | 2 | 4 | 1 |
| 3 | 4 | 1 | 2 |
| 4 | 1 | 3 | 2 |
| 3 | 1 | 4 | 2 |
| 2 | 4 | 1 | 3 |
| 1 | 4 | 2 | 3 |
| 2 | 1 | 4 | 3 |
| 2 | 3 | 1 | 4 |
| 1 | 3 | 2 | 4 |
+---+---+---+---+
10 rows in set (0.00 sec)
Since SQL can be considered in set theory, data can be extracted with the extremely simple idea of "extracting elements that match the conditions from a possible set".
Recommended Posts