3803 lines
142 KiB
HTML
3803 lines
142 KiB
HTML
<!DOCTYPE HTML>
|
||
<html lang="en" class="coal" dir="ltr">
|
||
<head>
|
||
<!-- Book generated using mdBook -->
|
||
<meta charset="UTF-8">
|
||
<title>rust codewar - Andrew's Blog</title>
|
||
|
||
|
||
<!-- Custom HTML head -->
|
||
|
||
<meta name="description" content="Andrew Ryan's Blog">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
<meta name="theme-color" content="#ffffff">
|
||
|
||
<link rel="icon" href="../../favicon.svg">
|
||
<link rel="shortcut icon" href="../../favicon.png">
|
||
<link rel="stylesheet" href="../../css/variables.css">
|
||
<link rel="stylesheet" href="../../css/general.css">
|
||
<link rel="stylesheet" href="../../css/chrome.css">
|
||
|
||
<!-- Fonts -->
|
||
<link rel="stylesheet" href="../../FontAwesome/css/font-awesome.css">
|
||
<link rel="stylesheet" href="../../fonts/fonts.css">
|
||
|
||
<!-- Highlight.js Stylesheets -->
|
||
<link rel="stylesheet" href="../../highlight.css">
|
||
<link rel="stylesheet" href="../../tomorrow-night.css">
|
||
<link rel="stylesheet" href="../../ayu-highlight.css">
|
||
|
||
<!-- Custom theme stylesheets -->
|
||
<link rel="stylesheet" href="../../src/style/custom.css">
|
||
|
||
<!-- MathJax -->
|
||
<script async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
|
||
</head>
|
||
<body class="sidebar-visible no-js">
|
||
<div id="body-container">
|
||
<!-- Provide site root to javascript -->
|
||
<script>
|
||
var path_to_root = "../../";
|
||
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "coal" : "coal";
|
||
</script>
|
||
|
||
<!-- Work around some values being stored in localStorage wrapped in quotes -->
|
||
<script>
|
||
try {
|
||
var theme = localStorage.getItem('mdbook-theme');
|
||
var sidebar = localStorage.getItem('mdbook-sidebar');
|
||
|
||
if (theme.startsWith('"') && theme.endsWith('"')) {
|
||
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
|
||
}
|
||
|
||
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
|
||
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
|
||
}
|
||
} catch (e) { }
|
||
</script>
|
||
|
||
<!-- Set the theme before any content is loaded, prevents flash -->
|
||
<script>
|
||
var theme;
|
||
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
|
||
if (theme === null || theme === undefined) { theme = default_theme; }
|
||
var html = document.querySelector('html');
|
||
html.classList.remove('coal')
|
||
html.classList.add(theme);
|
||
var body = document.querySelector('body');
|
||
body.classList.remove('no-js')
|
||
body.classList.add('js');
|
||
</script>
|
||
|
||
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
|
||
|
||
<!-- Hide / unhide sidebar before it is displayed -->
|
||
<script>
|
||
var body = document.querySelector('body');
|
||
var sidebar = null;
|
||
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
|
||
if (document.body.clientWidth >= 1080) {
|
||
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
|
||
sidebar = sidebar || 'visible';
|
||
} else {
|
||
sidebar = 'hidden';
|
||
}
|
||
sidebar_toggle.checked = sidebar === 'visible';
|
||
body.classList.remove('sidebar-visible');
|
||
body.classList.add("sidebar-" + sidebar);
|
||
</script>
|
||
|
||
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
|
||
<div class="sidebar-scrollbox">
|
||
<ol class="chapter"><li class="chapter-item affix "><a href="../../index.html">Andrew's Blog</a></li><li class="chapter-item "><a href="../../posts/linux/linux.html"><strong aria-hidden="true">1.</strong> linux</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/linux/install_linux.html"><strong aria-hidden="true">1.1.</strong> install linux</a></li><li class="chapter-item "><a href="../../posts/linux/bash_profile.html"><strong aria-hidden="true">1.2.</strong> bash profile</a></li><li class="chapter-item "><a href="../../posts/linux/command_list.html"><strong aria-hidden="true">1.3.</strong> command list</a></li><li class="chapter-item "><a href="../../posts/linux/git_guide.html"><strong aria-hidden="true">1.4.</strong> git guide</a></li><li class="chapter-item "><a href="../../posts/linux/tar.html"><strong aria-hidden="true">1.5.</strong> tar</a></li><li class="chapter-item "><a href="../../posts/linux/run_x86_elf_in_x64_setup.html"><strong aria-hidden="true">1.6.</strong> run x86 elf in x64 setup</a></li></ol></li><li class="chapter-item "><a href="../../posts/mac/mac.html"><strong aria-hidden="true">2.</strong> mac</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/mac/macos_profiles.html"><strong aria-hidden="true">2.1.</strong> macos profiles</a></li></ol></li><li class="chapter-item "><a href="../../posts/swift/swift.html"><strong aria-hidden="true">3.</strong> swift</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/swift/learn_swift.html"><strong aria-hidden="true">3.1.</strong> learn swift basics</a></li><li class="chapter-item "><a href="../../posts/swift/swift_extensions.html"><strong aria-hidden="true">3.2.</strong> Swift extensions</a></li><li class="chapter-item "><a href="../../posts/swift/swiftui_extension.html"><strong aria-hidden="true">3.3.</strong> SwiftUI extensions</a></li><li class="chapter-item "><a href="../../posts/swift/install_swift.html"><strong aria-hidden="true">3.4.</strong> install swift</a></li><li class="chapter-item "><a href="../../posts/swift/task_planner.html"><strong aria-hidden="true">3.5.</strong> implment task panner app with SwiftUI</a></li><li class="chapter-item "><a href="../../posts/swift/swift_cheat_sheet.html"><strong aria-hidden="true">3.6.</strong> Swift Cheat Sheet</a></li><li class="chapter-item "><a href="../../posts/swift/yinci_url.html"><strong aria-hidden="true">3.7.</strong> Personal privacy protocol</a></li><li class="chapter-item "><a href="../../posts/swift/swift_regular_exressions.html"><strong aria-hidden="true">3.8.</strong> Swift regular exressions</a></li><li class="chapter-item "><a href="../../posts/ios/how_to_create_beautiful_ios_charts_in_swift.html"><strong aria-hidden="true">3.9.</strong> How to Create Beautiful iOS Charts in鑱絊wift</a></li><li class="chapter-item "><a href="../../posts/swift/swiftui_source_code.html"><strong aria-hidden="true">3.10.</strong> SwiftUI source code</a></li><li class="chapter-item "><a href="../../posts/swift/use_swift_fetch_iciba_api.html"><strong aria-hidden="true">3.11.</strong> use swift fetch iciba API</a></li></ol></li><li class="chapter-item "><a href="../../posts/ios/ios.html"><strong aria-hidden="true">4.</strong> ios</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/ios/cocaposd_setup_and_install_for_ios_project.html"><strong aria-hidden="true">4.1.</strong> cocaposd setup and install for ios project</a></li><li class="chapter-item "><a href="../../posts/ios/swiftui_show_gif_image.html"><strong aria-hidden="true">4.2.</strong> SwiftUI show gif image</a></li><li class="chapter-item "><a href="../../posts/ios/implement_task_planner_app.html"><strong aria-hidden="true">4.3.</strong> implement Task planner App</a></li></ol></li><li class="chapter-item "><a href="../../posts/objective_c/objective_c.html"><strong aria-hidden="true">5.</strong> objective_c</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/objective_c/objective_c_cheat_sheet.html"><strong aria-hidden="true">5.1.</strong> Objective-C Cheat Sheet</a></li><li class="chapter-item "><a href="../../posts/objective_c/objective_c_for_absolute_beginners_read_note.html"><strong aria-hidden="true">5.2.</strong> Objective-C Note</a></li></ol></li><li class="chapter-item "><a href="../../posts/dart/dart.html"><strong aria-hidden="true">6.</strong> dart</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/dart/flutter.html"><strong aria-hidden="true">6.1.</strong> Flutter Cheat Sheet</a></li><li class="chapter-item "><a href="../../posts/dart/dart_cheat_sheet.html"><strong aria-hidden="true">6.2.</strong> Dart Cheat Sheet</a></li><li class="chapter-item "><a href="../../posts/flutter/flutter_dev_test.html"><strong aria-hidden="true">6.3.</strong> Flutter dev test</a></li></ol></li><li class="chapter-item "><a href="../../posts/rust/rust.html"><strong aria-hidden="true">7.</strong> rust</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/rust/offline_use_rust.html"><strong aria-hidden="true">7.1.</strong> Offline use rust</a></li><li class="chapter-item "><a href="../../posts/rust/rust_grammer.html"><strong aria-hidden="true">7.2.</strong> rust grammar</a></li><li class="chapter-item "><a href="../../posts/rust/pase_string_and_decimal_conversion.html"><strong aria-hidden="true">7.3.</strong> pase string and decimal conversion</a></li><li class="chapter-item "><a href="../../posts/rust/parse_types.html"><strong aria-hidden="true">7.4.</strong> rust types</a></li><li class="chapter-item "><a href="../../posts/rust/rust_life_cycle.html"><strong aria-hidden="true">7.5.</strong> Rust life cycle</a></li><li class="chapter-item "><a href="../../posts/rust/rust_generic.html"><strong aria-hidden="true">7.6.</strong> rust generics</a></li><li class="chapter-item "><a href="../../posts/rust/rust_implment_matrix.html"><strong aria-hidden="true">7.7.</strong> Rust implement matrix</a></li><li class="chapter-item "><a href="../../posts/rust/rust_sort.html"><strong aria-hidden="true">7.8.</strong> Rust implement sort algorithms</a></li><li class="chapter-item "><a href="../../posts/rust/implement_aes_encryption.html"><strong aria-hidden="true">7.9.</strong> Rust implement AEC encryption and decryption</a></li><li class="chapter-item "><a href="../../posts/rust/implement_trie_data_structure.html"><strong aria-hidden="true">7.10.</strong> implement trie data structure</a></li><li class="chapter-item "><a href="../../posts/rust/rust_implement_tree.html"><strong aria-hidden="true">7.11.</strong> implement tree data_structure</a></li><li class="chapter-item "><a href="../../posts/rust/list_dir.html"><strong aria-hidden="true">7.12.</strong> list dir</a></li><li class="chapter-item "><a href="../../posts/rust/fast_way_to_implment_object_trait.html"><strong aria-hidden="true">7.13.</strong> fast way to implment object trait</a></li><li class="chapter-item "><a href="../../posts/rust/compress_rust_binary_size.html"><strong aria-hidden="true">7.14.</strong> compress rust binary size</a></li><li class="chapter-item "><a href="../../posts/rust/implment_file_upload_backend.html"><strong aria-hidden="true">7.15.</strong> impliment file upload</a></li><li class="chapter-item "><a href="../../posts/rust/this_is_add_post_cli_implementation_in_rust.html"><strong aria-hidden="true">7.16.</strong> this is add_post cli implementation in rust</a></li><li class="chapter-item "><a href="../../posts/rust/use_rust_implment_a_copyclipbord_cli.html"><strong aria-hidden="true">7.17.</strong> Use rust implment a copyclipbord CLI</a></li><li class="chapter-item "><a href="../../posts/rust/sqlite_database_add_delete_update_show_in_rust.html"><strong aria-hidden="true">7.18.</strong> sqlite database add delete update show in rust</a></li><li class="chapter-item "><a href="../../posts/rust/implementing_tokio_joinhandle_for_wasm.html"><strong aria-hidden="true">7.19.</strong> Implementing tokio JoinHandle for wasm</a></li><li class="chapter-item "><a href="../../posts/rust/rust_implement_a_crate_for_encode_and_decode_brainfuck_and_ook.html"><strong aria-hidden="true">7.20.</strong> rust implement a crate for encode and decode brainfuck and ook</a></li><li class="chapter-item "><a href="../../posts/rust/slint_builtin_elements.html"><strong aria-hidden="true">7.21.</strong> Slint Builtin Elements</a></li><li class="chapter-item "><a href="../../posts/rust/corporate_network_install_rust_on_windows.html"><strong aria-hidden="true">7.22.</strong> Corporate network install Rust on windows</a></li><li class="chapter-item "><a href="../../posts/rust/rust_binary_file_how_to_judge_static_link_or_dynamic_link_in_macos.html"><strong aria-hidden="true">7.23.</strong> rust binary file how to judge static link or dynamic link in Macos</a></li><li class="chapter-item "><a href="../../posts/rust/rust_binary_include_dir_and_get_contents.html"><strong aria-hidden="true">7.24.</strong> rust binary include dir and get contents</a></li><li class="chapter-item "><a href="../../posts/rust/rust_logger_non-block.html"><strong aria-hidden="true">7.25.</strong> rust logger non-block</a></li><li class="chapter-item "><a href="../../posts/rust/rust_connect_sql_server_database.html"><strong aria-hidden="true">7.26.</strong> rust connect sql server database</a></li><li class="chapter-item "><a href="../../posts/rust/rust_websocket_implment.html"><strong aria-hidden="true">7.27.</strong> rust websocket implment</a></li></ol></li><li class="chapter-item "><a href="../../posts/java/java.html"><strong aria-hidden="true">8.</strong> java</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/java/java_grammar.html"><strong aria-hidden="true">8.1.</strong> java grammar and codewar</a></li><li class="chapter-item "><a href="../../posts/java/run_jar.html"><strong aria-hidden="true">8.2.</strong> java run .jar</a></li><li class="chapter-item "><a href="../../posts/java/java_pomxml_add_defaultgoal_to_build.html"><strong aria-hidden="true">8.3.</strong> Java pomxml add defaultGoal to build</a></li><li class="chapter-item "><a href="../../posts/java/java_set_mvn_mirror.html"><strong aria-hidden="true">8.4.</strong> Java set mvn mirror</a></li></ol></li><li class="chapter-item "><a href="../../posts/python/python.html"><strong aria-hidden="true">9.</strong> python</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/python/convert_pesn.html"><strong aria-hidden="true">9.1.</strong> convert pesn</a></li><li class="chapter-item "><a href="../../posts/python/find_remove_dir.html"><strong aria-hidden="true">9.2.</strong> find and remove dir</a></li><li class="chapter-item "><a href="../../posts/python/timing_message.html"><strong aria-hidden="true">9.3.</strong> wechat send message</a></li><li class="chapter-item "><a href="../../posts/python/use_python_openpyxl_package_read_and_edit_excel_files.html"><strong aria-hidden="true">9.4.</strong> Use python openpyxl package read and edit excel files</a></li></ol></li><li class="chapter-item "><a href="../../posts/go/go.html"><strong aria-hidden="true">10.</strong> go</a></li><li class="chapter-item "><a href="../../posts/js/js.html"><strong aria-hidden="true">11.</strong> js</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/js/js_tutorial.html"><strong aria-hidden="true">11.1.</strong> js tutorial</a></li><li class="chapter-item "><a href="../../posts/js/js_tutorial_map.html"><strong aria-hidden="true">11.2.</strong> ja map</a></li><li class="chapter-item "><a href="../../posts/js/js_tutorial_math.html"><strong aria-hidden="true">11.3.</strong> js math</a></li><li class="chapter-item "><a href="../../posts/js/js_tutorial_object.html"><strong aria-hidden="true">11.4.</strong> js object</a></li><li class="chapter-item "><a href="../../posts/js/js_tutorial_set.html"><strong aria-hidden="true">11.5.</strong> js set</a></li><li class="chapter-item "><a href="../../posts/js/single_thread_and_asynchronous.html"><strong aria-hidden="true">11.6.</strong> single thread and asynchronous</a></li><li class="chapter-item "><a href="../../posts/js/this.html"><strong aria-hidden="true">11.7.</strong> js this</a></li><li class="chapter-item "><a href="../../posts/js/js_implment_aes.html"><strong aria-hidden="true">11.8.</strong> js implment aes</a></li><li class="chapter-item "><a href="../../posts/js/getting_started_with_ajax.html"><strong aria-hidden="true">11.9.</strong> getting started with ajax</a></li><li class="chapter-item "><a href="../../posts/js/BinarySearchTree.html"><strong aria-hidden="true">11.10.</strong> binary search tree</a></li><li class="chapter-item "><a href="../../posts/js/goole_zx.html"><strong aria-hidden="true">11.11.</strong> goole zx</a></li><li class="chapter-item "><a href="../../posts/js/es6.html"><strong aria-hidden="true">11.12.</strong> es6</a></li></ol></li><li class="chapter-item "><a href="../../posts/ruby/ruby.html"><strong aria-hidden="true">12.</strong> ruby</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/ruby/rails_setup_env.html"><strong aria-hidden="true">12.1.</strong> ruby on rails setup environment</a></li><li class="chapter-item "><a href="../../posts/ruby/learn_ruby.html"><strong aria-hidden="true">12.2.</strong> learn ruby</a></li><li class="chapter-item "><a href="../../posts/ruby/ruby_note.html"><strong aria-hidden="true">12.3.</strong> Ruby Note</a></li><li class="chapter-item "><a href="../../posts/ruby/setup_ruby_for_ctf.html"><strong aria-hidden="true">12.4.</strong> Setup ruby for CTF</a></li></ol></li><li class="chapter-item "><a href="../../posts/react/react.html"><strong aria-hidden="true">13.</strong> react</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/react/react_life_cycle.html"><strong aria-hidden="true">13.1.</strong> react life cycle</a></li><li class="chapter-item "><a href="../../posts/react/react_router.html"><strong aria-hidden="true">13.2.</strong> react router</a></li><li class="chapter-item "><a href="../../posts/react/react_this.html"><strong aria-hidden="true">13.3.</strong> react this</a></li><li class="chapter-item "><a href="../../posts/react/react_interviw.html"><strong aria-hidden="true">13.4.</strong> react interview</a></li><li class="chapter-item "><a href="../../posts/react/important_react_interview.html"><strong aria-hidden="true">13.5.</strong> important react interview</a></li><li class="chapter-item "><a href="../../posts/react/react_quick_reference.html"><strong aria-hidden="true">13.6.</strong> react quick reference</a></li><li class="chapter-item "><a href="../../posts/react/redux_quick_reference.html"><strong aria-hidden="true">13.7.</strong> redux quick reference</a></li></ol></li><li class="chapter-item "><a href="../../posts/vue/vue.html"><strong aria-hidden="true">14.</strong> vue</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/vue/vue_ajax.html"><strong aria-hidden="true">14.1.</strong> vue ajax</a></li></ol></li><li class="chapter-item "><a href="../../posts/angular/angular.html"><strong aria-hidden="true">15.</strong> angular</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/angular/controller_communication.html"><strong aria-hidden="true">15.1.</strong> controller communication</a></li><li class="chapter-item "><a href="../../posts/angular/creating_custom_directives.html"><strong aria-hidden="true">15.2.</strong> creating custom directives</a></li><li class="chapter-item "><a href="../../posts/angular/directive_notes.html"><strong aria-hidden="true">15.3.</strong> directive notes</a></li><li class="chapter-item "><a href="../../posts/angular/directive_communication.html"><strong aria-hidden="true">15.4.</strong> directive communication</a></li><li class="chapter-item "><a href="../../posts/angular/post_params.html"><strong aria-hidden="true">15.5.</strong> post params</a></li><li class="chapter-item "><a href="../../posts/angular/read_json_angular.html"><strong aria-hidden="true">15.6.</strong> read json angular</a></li><li class="chapter-item "><a href="../../posts/angular/same_route_reload.html"><strong aria-hidden="true">15.7.</strong> same route reload</a></li></ol></li><li class="chapter-item "><a href="../../posts/css/css.html"><strong aria-hidden="true">16.</strong> css</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/css/use_css_media.html"><strong aria-hidden="true">16.1.</strong> use css media</a></li></ol></li><li class="chapter-item "><a href="../../posts/php/php.html"><strong aria-hidden="true">17.</strong> php</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/php/for_php_string_implment_some_extemtion_functions.html"><strong aria-hidden="true">17.1.</strong> for php string implment some extemtion functions</a></li><li class="chapter-item "><a href="../../posts/php/php_cheatsheet.html"><strong aria-hidden="true">17.2.</strong> PHP cheatsheet</a></li></ol></li><li class="chapter-item expanded "><a href="../../posts/leetcode/leetcode.html"><strong aria-hidden="true">18.</strong> leetcode</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/leetcode/rust_leetcode.html"><strong aria-hidden="true">18.1.</strong> rust leetcode</a></li><li class="chapter-item expanded "><a href="../../posts/leetcode/rust_codewar.html" class="active"><strong aria-hidden="true">18.2.</strong> rust codewar</a></li><li class="chapter-item "><a href="../../posts/leetcode/swift_codewar.html"><strong aria-hidden="true">18.3.</strong> swift codewar</a></li><li class="chapter-item "><a href="../../posts/leetcode/js_leetcode.html"><strong aria-hidden="true">18.4.</strong> js leetcode</a></li><li class="chapter-item "><a href="../../posts/leetcode/java_leetcode.html"><strong aria-hidden="true">18.5.</strong> java leetcode</a></li><li class="chapter-item "><a href="../../posts/leetcode/rust_huawei.html"><strong aria-hidden="true">18.6.</strong> huawei test</a></li><li class="chapter-item "><a href="../../posts/leetcode/rust_utils.html"><strong aria-hidden="true">18.7.</strong> rust common functions</a></li><li class="chapter-item "><a href="../../posts/leetcode/olympiad_training.html"><strong aria-hidden="true">18.8.</strong> Computer olympiad training</a></li></ol></li><li class="chapter-item "><a href="../../posts/ctf/CTF.html"><strong aria-hidden="true">19.</strong> ctf</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../posts/ctf/CTF_Note.html"><strong aria-hidden="true">19.1.</strong> CTF Note</a></li><li class="chapter-item "><a href="../../posts/ctf/0.1_Web.html"><strong aria-hidden="true">19.2.</strong> Web</a></li><li class="chapter-item "><a href="../../posts/ctf/4.1_Misc.html"><strong aria-hidden="true">19.3.</strong> Misc</a></li><li class="chapter-item "><a href="../../posts/ctf/3.2_PWN_note.html"><strong aria-hidden="true">19.4.</strong> PWN</a></li><li class="chapter-item "><a href="../../posts/ctf/3.1_Crypto.html"><strong aria-hidden="true">19.5.</strong> Crypto</a></li><li class="chapter-item "><a href="../../posts/ctf/3.4_RSA_note.html"><strong aria-hidden="true">19.6.</strong> Rsa attack</a></li><li class="chapter-item "><a href="../../posts/ctf/3.5_Base64.html"><strong aria-hidden="true">19.7.</strong> Base64</a></li><li class="chapter-item "><a href="../../posts/ctf/0.0_SQL Injection Cheatsheet.html"><strong aria-hidden="true">19.8.</strong> SQL Injection Cheatsheet</a></li><li class="chapter-item "><a href="../../posts/ctf/1.1_SQL_injection.html"><strong aria-hidden="true">19.9.</strong> SQL Injection</a></li><li class="chapter-item "><a href="../../posts/ctf/1.2_SQL_injection_UNION_attacks.html"><strong aria-hidden="true">19.10.</strong> SQL Injection UNION attacks</a></li><li class="chapter-item "><a href="../../posts/ctf/1.3_Blind SQL injection.html"><strong aria-hidden="true">19.11.</strong> Blind SQL Injection</a></li><li class="chapter-item "><a href="../../posts/ctf/1.4_Code Injection.html"><strong aria-hidden="true">19.12.</strong> Code Injection</a></li><li class="chapter-item "><a href="../../posts/ctf/1.5_SSRF.html"><strong aria-hidden="true">19.13.</strong> SSRF</a></li><li class="chapter-item "><a href="../../posts/ctf/1.6_OS command injection.html"><strong aria-hidden="true">19.14.</strong> OS command injection</a></li><li class="chapter-item "><a href="../../posts/ctf/1.7_Local file inclusion.html"><strong aria-hidden="true">19.15.</strong> Local file inclusion</a></li><li class="chapter-item "><a href="../../posts/ctf/1.8_Remote file inclusion.html"><strong aria-hidden="true">19.16.</strong> Remote file inclusion</a></li><li class="chapter-item "><a href="../../posts/ctf/1.9_CSRFm.html"><strong aria-hidden="true">19.17.</strong> CSRF</a></li><li class="chapter-item "><a href="../../posts/ctf/1.10_NoSQL injection.html"><strong aria-hidden="true">19.18.</strong> NoSQL injection</a></li><li class="chapter-item "><a href="../../posts/ctf/1.11_JSON injection.html"><strong aria-hidden="true">19.19.</strong> JSON injection</a></li><li class="chapter-item "><a href="../../posts/ctf/1.12_CTF_Web_SQL_Note.html"><strong aria-hidden="true">19.20.</strong> CTF Web SQL Note</a></li><li class="chapter-item "><a href="../../posts/ctf/2.1_XXE.html"><strong aria-hidden="true">19.21.</strong> XXE</a></li><li class="chapter-item "><a href="../../posts/ctf/2.2_XSS.html"><strong aria-hidden="true">19.22.</strong> XSS</a></li><li class="chapter-item "><a href="../../posts/ctf/2.3_Upload File.html"><strong aria-hidden="true">19.23.</strong> Upload File</a></li><li class="chapter-item "><a href="../../posts/ctf/2.4_serialize_unserialize.html"><strong aria-hidden="true">19.24.</strong> serialize unserialize</a></li><li class="chapter-item "><a href="../../posts/ctf/2.5_Race condition.html"><strong aria-hidden="true">19.25.</strong> Race condition</a></li><li class="chapter-item "><a href="../../posts/ctf/3.2_PWN_note.html"><strong aria-hidden="true">19.26.</strong> PWN_note</a></li><li class="chapter-item "><a href="../../posts/ctf/3.3_pwn HCTF2016 brop.html"><strong aria-hidden="true">19.27.</strong> pwn HCTF2016 brop</a></li><li class="chapter-item "><a href="../../posts/ctf/pwn_patch_defense_skill.html"><strong aria-hidden="true">19.28.</strong> PWN Patch defense skill</a></li><li class="chapter-item "><a href="../../posts/ctf/pwn_stack_overflow.html"><strong aria-hidden="true">19.29.</strong> PWN stack overflow</a></li><li class="chapter-item "><a href="../../posts/ctf/pwn_heap_overflow.html"><strong aria-hidden="true">19.30.</strong> PWN heap overflow</a></li><li class="chapter-item "><a href="../../posts/ctf/pwn_format_string_vulnerability.html"><strong aria-hidden="true">19.31.</strong> PWN Format String Vulnerability</a></li><li class="chapter-item "><a href="../../posts/ctf/kali_linux_tutorials.html"><strong aria-hidden="true">19.32.</strong> Kali linux tutorials</a></li><li class="chapter-item "><a href="../../posts/ctf/google_dorks_2023_lists.html"><strong aria-hidden="true">19.33.</strong> Google Dorks 2023 Lists</a></li><li class="chapter-item "><a href="../../posts/ctf/dvwa_writeup.html"><strong aria-hidden="true">19.34.</strong> DVWA WriteUp</a></li><li class="chapter-item "><a href="../../posts/ctf/bwapp_writeup.html"><strong aria-hidden="true">19.35.</strong> bWAPP WriteUp</a></li><li class="chapter-item "><a href="../../posts/ctf/sqlilabs_writeup.html"><strong aria-hidden="true">19.36.</strong> sqlilabs WriteUp</a></li><li class="chapter-item "><a href="../../posts/ctf/ctf_train_at_hangzhou.html"><strong aria-hidden="true">19.37.</strong> ctf train at hangzhou</a></li><li class="chapter-item "><a href="../../posts/ctf/ctf_common_mindmap_list.html"><strong aria-hidden="true">19.38.</strong> ctf common mindmap list</a></li><li class="chapter-item "><a href="../../posts/ctf/error_based_sql_injection.html"><strong aria-hidden="true">19.39.</strong> Error Based SQL Injection</a></li><li class="chapter-item "><a href="../../posts/ctf/urlfinder_tutorial.html"><strong aria-hidden="true">19.40.</strong> URLFinder Tutorial</a></li><li class="chapter-item "><a href="../../posts/ctf/observer_ward_tutorial.html"><strong aria-hidden="true">19.41.</strong> observer_ward Tutorial</a></li><li class="chapter-item "><a href="../../posts/ctf/mysql_udf_.html"><strong aria-hidden="true">19.42.</strong> MySQL UDF 提权</a></li><li class="chapter-item "><a href="../../posts/ctf/nuclei__tutorial.html"><strong aria-hidden="true">19.43.</strong> Nuclei Tutorial</a></li><li class="chapter-item "><a href="../../posts/ctf/2024_ctf_solution_thinking.html"><strong aria-hidden="true">19.44.</strong> 2024 ctf solution thinking</a></li><li class="chapter-item "><a href="../../posts/ctf/man_che_si_te_bian_ma.html"><strong aria-hidden="true">19.45.</strong> 曼彻斯特编码</a></li></ol></li></ol>
|
||
</div>
|
||
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
|
||
<div class="sidebar-resize-indicator"></div>
|
||
</div>
|
||
</nav>
|
||
|
||
<!-- Track and set sidebar scroll position -->
|
||
<script>
|
||
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
|
||
sidebarScrollbox.addEventListener('click', function(e) {
|
||
if (e.target.tagName === 'A') {
|
||
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
|
||
}
|
||
}, { passive: true });
|
||
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
|
||
sessionStorage.removeItem('sidebar-scroll');
|
||
if (sidebarScrollTop) {
|
||
// preserve sidebar scroll position when navigating via links within sidebar
|
||
sidebarScrollbox.scrollTop = sidebarScrollTop;
|
||
} else {
|
||
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
|
||
var activeSection = document.querySelector('#sidebar .active');
|
||
if (activeSection) {
|
||
activeSection.scrollIntoView({ block: 'center' });
|
||
}
|
||
}
|
||
</script>
|
||
|
||
<div id="page-wrapper" class="page-wrapper">
|
||
|
||
<div class="page">
|
||
<div id="menu-bar-hover-placeholder"></div>
|
||
<div id="menu-bar" class="menu-bar sticky">
|
||
<div class="left-buttons">
|
||
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
|
||
<i class="fa fa-bars"></i>
|
||
</label>
|
||
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
|
||
<i class="fa fa-paint-brush"></i>
|
||
</button>
|
||
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
|
||
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
|
||
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
|
||
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
|
||
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
|
||
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
|
||
</ul>
|
||
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
|
||
<i class="fa fa-search"></i>
|
||
</button>
|
||
</div>
|
||
|
||
<h1 class="menu-title">Andrew's Blog</h1>
|
||
|
||
<div class="right-buttons">
|
||
<a href="https://gitlink.org.cn/dnrops/dnrops.gitlink.net.git" title="Git repository" aria-label="Git repository">
|
||
<i id="git-repository-button" class="fa fa-github"></i>
|
||
</a>
|
||
|
||
</div>
|
||
</div>
|
||
|
||
<div id="search-wrapper" class="hidden">
|
||
<form id="searchbar-outer" class="searchbar-outer">
|
||
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
|
||
</form>
|
||
<div id="searchresults-outer" class="searchresults-outer hidden">
|
||
<div id="searchresults-header" class="searchresults-header"></div>
|
||
<ul id="searchresults">
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
|
||
<script>
|
||
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
|
||
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
|
||
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
|
||
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
|
||
});
|
||
</script>
|
||
|
||
<div id="content" class="content">
|
||
<main>
|
||
<h1 id="codewar-rust-implementation"><a class="header" href="#codewar-rust-implementation">Codewar rust implementation</a></h1>
|
||
<h2 id="kata-1-vec-删除重复的元素返回-unique-vec"><a class="header" href="#kata-1-vec-删除重复的元素返回-unique-vec">Kata 1 (vec 删除重复的元素,返回 Unique Vec)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>use std::collections::BTreeSet;
|
||
fn unique_in_order(vec: Vec<i32>) -> Vec<i32> {
|
||
let mut bset = BTreeSet::new();
|
||
for i in vec {
|
||
bset.insert(i);
|
||
}
|
||
let mut re_vec = Vec::new();
|
||
for item in &bset {
|
||
re_vec.push(*item);
|
||
}
|
||
re_vec
|
||
}
|
||
fn unique_in_order<T>(sequence: T) -> Vec<T::Item>
|
||
where
|
||
T: std::iter::IntoIterator,
|
||
T::Item: std::cmp::PartialEq + std::fmt::Debug,
|
||
{
|
||
let mut v: Vec<_> = sequence.into_iter().collect();
|
||
v.dedup();
|
||
v
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-2-寻找-k-大元素删除重复"><a class="header" href="#kata-2-寻找-k-大元素删除重复">Kata 2 (寻找 k 大元素,删除重复)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust">/**
|
||
* Kata1
|
||
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
|
||
* @param a int整型一维数组
|
||
* @param n int整型
|
||
* @param K int整型 * @return int整型
|
||
*/
|
||
struct Kata1 {}
|
||
impl Kata1 {
|
||
fn new() -> Self {
|
||
Kata1 {}
|
||
}
|
||
#[allow(non_snake_case)]
|
||
#[allow(dead_code)]
|
||
#[allow(unused_variables)]
|
||
pub fn findKth(&self, a: Vec<i32>, n: i32, K: i32) -> i32 {
|
||
// write code here
|
||
use std::collections::BTreeSet;
|
||
fn unique_in_order(vec: Vec<i32>) -> Vec<i32> {
|
||
let mut bset = BTreeSet::new();
|
||
for i in vec {
|
||
bset.insert(i);
|
||
}
|
||
let mut re_vec = Vec::new();
|
||
for item in &bset {
|
||
re_vec.push(*item);
|
||
}
|
||
re_vec
|
||
}
|
||
let mut a_ = a.clone();
|
||
a_ = unique_in_order(a_.clone());
|
||
a_.sort();
|
||
// dbg!(&a_);
|
||
// println!("{:?}", unique_in_order(a_.clone()));
|
||
return a_[a_.len() - K as usize];
|
||
}
|
||
}
|
||
fn main{
|
||
println!("{}",Kata1::findKth(&Kata1::new(),vec![1,5,14,65,2,5],6,3)); //return 5
|
||
}</code></pre></pre>
|
||
<h2 id="kata-3-三个数的最大乘积"><a class="header" href="#kata-3-三个数的最大乘积">Kata 3 (三个数的最大乘积)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>struct Solution{}
|
||
impl Solution {
|
||
fn new() -> Self {
|
||
Solution{}
|
||
}
|
||
/**
|
||
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
|
||
* 最大乘积
|
||
* @param A int整型一维数组
|
||
* @return long长整型
|
||
*/
|
||
pub fn solve(&self, A: Vec<i32>) -> i64 {
|
||
let mut vec = A;
|
||
vec.sort();
|
||
fn contain_minus(vec: Vec<i32>) -> bool {
|
||
let mut re = false;
|
||
for i in vec {
|
||
if i < 0 {
|
||
re = true;
|
||
}
|
||
}
|
||
re
|
||
}
|
||
if contain_minus(vec.clone()) {
|
||
if vec[0] as i64 * vec[1] as i64 > vec[vec.len() - 2] as i64 * vec[vec.len() - 3] as i64 {
|
||
return vec[vec.len() - 1] as i64 * vec[0] as i64 * vec[1] as i64;
|
||
}
|
||
}
|
||
return vec[vec.len() - 1] as i64 * vec[vec.len() - 2] as i64 * vec[vec.len() - 3] as i64; }
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-4-排序算法的实现-sort-algorithm-in-rust"><a class="header" href="#kata-4-排序算法的实现-sort-algorithm-in-rust">Kata 4 (排序算法的实现 Sort Algorithm in Rust)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust">fn bubble_sort<T>(slice: &mut [T])
|
||
where
|
||
T: Ord,
|
||
{
|
||
let mut swapped = true;
|
||
while swapped {
|
||
swapped = false;
|
||
for i in 1..slice.len() {
|
||
if slice[i - 1] > slice[i] {
|
||
slice.swap(i - 1, i);
|
||
swapped = true;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
fn isertion_sort<T>(slice: &mut [T])
|
||
where
|
||
T: Ord,
|
||
{
|
||
for unsorted in 1..slice.len() {
|
||
let i = match slice[..unsorted].binary_search(&slice[unsorted]) {
|
||
Ok(i) => i,
|
||
Err(err) => err,
|
||
};
|
||
slice[i..=unsorted].rotate_right(1);
|
||
}
|
||
}
|
||
fn main() {
|
||
let mut vec1 = vec![1, 2, 30, 40, 5, 6, 7];
|
||
bubble_sort(&mut vec1);
|
||
assert_eq!(vec1, vec![1, 2, 5, 6, 7, 30, 40]);
|
||
println!("buble_sort {:?}", vec1);
|
||
let mut vec2 = vec![10, 2, 30, 40, 5, 6, 7];
|
||
isertion_sort(&mut vec2);
|
||
assert_eq!(vec2, vec![2, 5, 6, 7, 10, 30, 40]);
|
||
println!("isertion_sort {:?}", vec2);
|
||
}</code></pre></pre>
|
||
<h2 id="kata-5-最小移动次数每次操作-n-1-各元素加-1最终值相等"><a class="header" href="#kata-5-最小移动次数每次操作-n-1-各元素加-1最终值相等">Kata 5 (最小移动次数,每次操作 n-1 各元素加 1,最终值相等)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust">#[allow(dead_code)]
|
||
/**
|
||
* 输入:nums = [1,2,3]
|
||
输出:3
|
||
解释:
|
||
只需要3次操作(注意每次操作会增加两个元素的值):
|
||
[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
|
||
*/
|
||
struct Solution {}
|
||
impl Solution {
|
||
pub fn min_moves(nums: Vec<i128>) -> i128 {
|
||
nums.iter().sum::<i128>() - nums.iter().min().unwrap() * nums.len() as i128
|
||
}
|
||
}
|
||
fn main() {
|
||
println!(
|
||
"{}",
|
||
Solution::min_moves(vec![11515115151, 100000000, 20000000000000000000000000])
|
||
);
|
||
println!("{}", Solution::min_moves(vec![1, 2, 3]));
|
||
}</code></pre></pre>
|
||
<h2 id="kata-6-vec-中所有类型转化为-string"><a class="header" href="#kata-6-vec-中所有类型转化为-string">Kata 6 (Vec 中所有类型转化为 String)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust">macro_rules! vec_strs {
|
||
(
|
||
$($element:expr),*
|
||
) => {
|
||
{
|
||
let mut v = Vec::new();
|
||
$(
|
||
v.push(format!("{}", $element));
|
||
)*
|
||
v
|
||
}
|
||
};
|
||
}
|
||
fn main() {
|
||
let s = vec_strs![1, "a", true, 3.14159f32];
|
||
println!("{:?}", s); //["1", "a", "true", "3.14159"]
|
||
assert_eq!(s, &["1", "a", "true", "3.14159"]);
|
||
}</code></pre></pre>
|
||
<h2 id="kata-7--kmp-算法"><a class="header" href="#kata-7--kmp-算法">Kata 7 ( kmp 算法)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>/**
|
||
描述
|
||
给你一个文本串 T ,一个非空模板串 S ,问 S 在 T 中出现了多少次
|
||
数据范围:1 \le len(S) \le 500000, 1 \le len(T) \le 10000001≤len(S)≤500000,1≤len(T)≤1000000
|
||
要求:空间复杂度 O(len(S))O(len(S)),时间复杂度 O(len(S)+len(T))O(len(S)+len(T))
|
||
示例1
|
||
输入:
|
||
"ababab","abababab"
|
||
复制
|
||
返回值:
|
||
2
|
||
* */
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-8-数字的幂-i64pow2-as-u32"><a class="header" href="#kata-8-数字的幂-i64pow2-as-u32">Kata 8 (数字的幂 i64.pow(2 as u32))</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span>#![allow(unused_imports)]
|
||
#![allow(unused_macros)]
|
||
#![allow(dead_code)]
|
||
#![allow(unused_variables)]
|
||
<span class="boring">fn main() {
|
||
</span>use proconio::{input, marker::*};
|
||
use std::cmp::*;
|
||
use std::collections::*;
|
||
//solution for problem A
|
||
pub mod a {
|
||
pub fn run() {
|
||
proconio::input! {
|
||
a: i32, b: i32
|
||
}
|
||
println!("{}", 32i64.pow((a - b) as u32))
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-9-判断输入的两个字符串中的-chars-是否相同是-yes否-no"><a class="header" href="#kata-9-判断输入的两个字符串中的-chars-是否相同是-yes否-no">Kata 9 (判断输入的两个字符串中的 chars 是否相同,是->Yes,否->No)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span>#![allow(unused_imports)]
|
||
#![allow(unused_macros)]
|
||
#![allow(dead_code)]
|
||
#![allow(unused_variables)]
|
||
<span class="boring">fn main() {
|
||
</span>use proconio::{input, marker::*};
|
||
use std::cmp::*;
|
||
use std::collections::*;
|
||
//solution for problem B
|
||
pub mod b {
|
||
pub fn run() {
|
||
use proconio::{input, marker::*};
|
||
input! {
|
||
mut s: Chars,
|
||
t: Chars,
|
||
}
|
||
if s.iter().zip(t.iter()).all(|(a, b)| a == b) {
|
||
println!("Yes");
|
||
} else {
|
||
let mut f = false;
|
||
for i in 0..s.len() - 1 {
|
||
s.swap(i, i + 1);
|
||
f |= s.iter().zip(t.iter()).all(|(a, b)| a == b);
|
||
s.swap(i, i + 1);
|
||
}
|
||
if f {
|
||
println!("Yes");
|
||
} else {
|
||
println!("No");
|
||
}
|
||
}
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-10-select-mul把-string-分为二parse-以后相乘放到数组里-返回最大的-item"><a class="header" href="#kata-10-select-mul把-string-分为二parse-以后相乘放到数组里-返回最大的-item">Kata 10 (Select Mul,把 String 分为二,parse 以后相乘,放到数组里 返回最大的 item)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>/**
|
||
* Sample Input 1
|
||
123
|
||
Sample Output 1
|
||
63
|
||
As described in Problem Statement, there are six ways to separate it:
|
||
12 and 3,
|
||
21 and 3,
|
||
13 and 2,
|
||
31 and 2,
|
||
23 and 1,
|
||
32 and 1.
|
||
The products of these pairs, in this order, are 36, 63, 26, 62, 23, 32, with 63 being the maximum.
|
||
*/
|
||
//solution for problem C
|
||
pub mod c {
|
||
pub fn run() {
|
||
use proconio::{input, marker::*};
|
||
use std::collections::BTreeMap;
|
||
input! {
|
||
mut s: Chars,
|
||
}
|
||
//reverse
|
||
fn reverse(phrase: String) -> String {
|
||
let mut i = phrase.len();
|
||
let mut reversed = String::new();
|
||
while i > 0 {
|
||
reversed.push(phrase.chars().nth(i - 1).unwrap());
|
||
i -= 1;
|
||
}
|
||
reversed
|
||
}
|
||
let s = s.iter_mut().map(|x| x.to_string()).collect::<Vec<_>>();
|
||
//generate bmap
|
||
fn generate_bmap(s: Vec<String>) {
|
||
let s_string = s.join("").to_string();
|
||
let mut bmap: BTreeMap<String, String> = BTreeMap::new();
|
||
for i in 1..s_string.len() {
|
||
let mut s_string = s.clone().join("").to_string();
|
||
let s_string_l = s_string.split_off(i);
|
||
bmap.insert(s_string, s_string_l);
|
||
}
|
||
for i in 1..s_string.len() {
|
||
let mut s_string = reverse(s.clone().join("").to_string());
|
||
let s_string_l = s_string.split_off(i);
|
||
bmap.insert(s_string, s_string_l);
|
||
}
|
||
let mut first_last_string = s.clone()[s.len() - 1].to_string();
|
||
first_last_string.push_str(&s.clone()[0].to_owned());
|
||
let mut middle_string = String::new();
|
||
for i in 1..s.len() - 1 {
|
||
middle_string.push_str(&s.clone()[i]);
|
||
}
|
||
bmap.insert(first_last_string, middle_string);
|
||
let mut vec = vec![];
|
||
for (v, k) in &bmap {
|
||
vec.push(
|
||
v.to_owned().parse::<i128>().unwrap() * k.to_owned().parse::<i128>().unwrap(),
|
||
);
|
||
}
|
||
vec.sort();
|
||
println!("{:?}", vec[vec.len() - 1]);
|
||
// println!("{:?}", bmap);
|
||
// println!("{:?}", vec);
|
||
}
|
||
generate_bmap(s.clone());
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-11-online-games"><a class="header" href="#kata-11-online-games">Kata 11 (Online games)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>//https://atcoder.jp/contests/abc221/tasks/abc221_d
|
||
mod d {
|
||
pub fn run() {
|
||
proconio::input! {
|
||
n: usize,
|
||
ab: [(u32, u32); n],
|
||
}
|
||
let mut m = std::collections::BTreeMap::new();
|
||
for (a, b) in ab {
|
||
*m.entry(a).or_insert(0) += 1;
|
||
*m.entry(a + b).or_insert(0) -= 1;
|
||
}
|
||
// println!("{:?}", m);
|
||
let mut d = vec![0; n + 1]; //if n=5,[0, 0, 0, 0, 0, 0]
|
||
// println!("{:?}", &d);
|
||
let mut p = 0;
|
||
let mut k = 0;
|
||
for (i, j) in m {
|
||
d[k as usize] += i - p;
|
||
p = i;
|
||
k += j;
|
||
}
|
||
d.remove(0);
|
||
println!(
|
||
"{:?}",
|
||
d.iter_mut()
|
||
.map(|x| x.to_string())
|
||
.collect::<Vec<_>>()
|
||
.join(" ")
|
||
);
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-12-快速开平方根倒数算法"><a class="header" href="#kata-12-快速开平方根倒数算法">Kata 12 (快速开平方根倒数算法)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust">#[allow(unused_macros)]
|
||
macro_rules! input {
|
||
() => {{
|
||
let mut string = String::new();
|
||
std::io::stdin().read_line(&mut string).unwrap();
|
||
string = string.to_string().trim().to_owned();
|
||
string
|
||
}};
|
||
}
|
||
fn main() {
|
||
let data: f64 = input!().parse::<f64>().unwrap();
|
||
println!("{}", fast_sqrt64(data) * fast_sqrt64(data));
|
||
println!("{}", 1.0 / f64::sqrt(16.0 * 16.0));
|
||
}
|
||
use std::mem;
|
||
/**
|
||
* used to compute the 1/sqrt(x*x)
|
||
*/
|
||
fn fast_sqrt64(number: f64) -> f64 {
|
||
const MAGIC_U64: u64 = 0x5fe6ec85e7de30da;
|
||
const THREEHALFS: f64 = 1.5;
|
||
let x2: f64 = number * 0.5;
|
||
let i: u64 = MAGIC_U64 - (unsafe { mem::transmute::<f64, u64>(number) } >> 1); // convert f64 to u64
|
||
let y: f64 = unsafe { mem::transmute::<u64, f64>(i) }; // convert u64 to f64
|
||
y * (THREEHALFS - (x2 * y * y))
|
||
}</code></pre></pre>
|
||
<h2 id="kata-13-生成和判断素数prime-number"><a class="header" href="#kata-13-生成和判断素数prime-number">Kata 13 (生成和判断素数,prime number)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>/** 生成素数*/
|
||
pub fn find_primes(n: usize) -> Vec<usize> {
|
||
let mut result = Vec::new();
|
||
let mut is_prime = vec![true; n + 1];
|
||
for i in 2..=n {
|
||
if is_prime[i] {
|
||
result.push(i);
|
||
}
|
||
((i * 2)..=n).into_iter().step_by(i).for_each(|x| {
|
||
is_prime[x] = false;
|
||
});
|
||
}
|
||
result
|
||
}
|
||
/**判断是否素数 */
|
||
pub fn is_prime(n: u64) -> bool {
|
||
n == 2 || n % 2 > 0 && (3..=(n as f64).sqrt() as u64).step_by(2).all(|i| n % i > 0)
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-14-vec-add-each"><a class="header" href="#kata-14-vec-add-each">Kata 14 (vec add each)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust">/**
|
||
* Vec add each trait
|
||
*/
|
||
trait InIterator<Type:Copy>{
|
||
fn each<Function:Fn(Type) -> Type>(&mut self,f:Function);
|
||
}
|
||
/**
|
||
* each trait to Vec
|
||
*/
|
||
impl<Type:Copy> InIterator<Type> for Vec<Type>{
|
||
fn each<Function:Fn(Type) -> Type>(&mut self,f:Function){
|
||
let mut i = 0;
|
||
while i < self.len(){
|
||
self[i] = f(self[i]);
|
||
i+= 1;
|
||
}
|
||
}
|
||
}
|
||
fn main(){
|
||
let mut v:Vec<i128>= vec![1,50,65,100];
|
||
v.each(|x| x*9999999999999999999999999999999999);
|
||
eprintln!("{:?}",v);
|
||
}</code></pre></pre>
|
||
<h2 id="kata-15-生成菱形-图"><a class="header" href="#kata-15-生成菱形-图">Kata 15 (生成菱形 *图)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust">/**
|
||
* Examples
|
||
A size 3 diamond:
|
||
*
|
||
***
|
||
*
|
||
生成菱形 *图
|
||
*/
|
||
mod diamond {
|
||
pub fn print(n: i32) -> Option<String> {
|
||
if n < 0 || n % 2 == 0 {
|
||
return None;
|
||
}
|
||
let n = n as usize;
|
||
let diamond = (1..=n)
|
||
.chain((1..n).rev())
|
||
.step_by(2)
|
||
.map(|i| format!("{}{}\n", " ".repeat((n - i) / 2), "*".repeat(i)))
|
||
.collect();
|
||
Some(diamond)
|
||
}
|
||
}
|
||
fn main(){
|
||
eprintln!("{}",diamond::print(3).unwrap());
|
||
}</code></pre></pre>
|
||
<h2 id="kata-16-找出-m-到-n-之间的-prime-number-存到-vec"><a class="header" href="#kata-16-找出-m-到-n-之间的-prime-number-存到-vec">Kata 16 (找出 m 到 n 之间的 prime number 存到 vec)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>/**
|
||
输入g,m,n
|
||
找出m到n之间的prime number 存到vec
|
||
vec中找出 任意两个数的差 ==g
|
||
输出这两个数Some(a,b)
|
||
*/
|
||
mod steps_in_primes{
|
||
use std::convert::TryInto;
|
||
pub fn step(g: i32, m: u64, n: u64) -> Option<(u64, u64)> {
|
||
// your code
|
||
// let mut vec:Vec<> = find_primes(n as usize);
|
||
let mut vec:Vec<i128> = vec![];
|
||
for i in m..=n{
|
||
if is_prime(i as i128){
|
||
vec.push(i as i128);
|
||
}
|
||
}
|
||
// eprintln!("{:?}",vec);
|
||
let mut re:Vec<i128> = vec![];
|
||
for i in 0..vec.len()-1 {
|
||
for j in i+1..vec.len()-1 {
|
||
if vec[j] -vec[i] == g.try_into().unwrap(){
|
||
re.push(vec[i].try_into().unwrap());
|
||
re.push(vec[j].try_into().unwrap());
|
||
}
|
||
}
|
||
}
|
||
// eprintln!("{:?}",re);
|
||
if re.len()<1{
|
||
return None;
|
||
}
|
||
Some((re[0].try_into().unwrap(),re[1].try_into().unwrap()))
|
||
}
|
||
pub fn is_prime(n: i128) -> bool {
|
||
n == 2 || n % 2 > 0 && (3..=(n as f64).sqrt() as u64).step_by(2).all(|i| n % i as i128 > 0)
|
||
}
|
||
}
|
||
/**
|
||
输入g,m,n
|
||
找出m到n之间的prime number 存到vec
|
||
vec中找出 任意两个数的差 ==g
|
||
输出这两个数Some(a,b)
|
||
*/
|
||
mod steps_in_primes1{
|
||
pub fn is_prime(p: u64) -> bool {
|
||
p >= 2 &&
|
||
(2..)
|
||
.take_while(|q| q * q <= p)
|
||
.all(|q| p % q != 0)
|
||
}
|
||
pub fn step(g: i32, m: u64, n: u64) -> Option<(u64, u64)> {
|
||
(m..n)
|
||
.map(|p| (p, p + g as u64))
|
||
.filter(|&(p0, p1)| is_prime(p0) && is_prime(p1))
|
||
.nth(0)
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-17-分数相加-得到不可简化的分数"><a class="header" href="#kata-17-分数相加-得到不可简化的分数">Kata 17 (分数相加 ,得到不可简化的分数)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>/**
|
||
* 分数相加 ,得到不可简化的分数
|
||
* in:vec![(1, 2), (1, 3), (1, 4)]
|
||
* 1/2 + 1/3 +1/4 = 6/12+4/12+3/12
|
||
* out:Some((13, 12))
|
||
*
|
||
*/
|
||
mod irreducible_sum_of_rationals{
|
||
pub fn gcd(a: i64, b: i64) -> i64 {
|
||
if b == 0 {
|
||
a
|
||
} else {
|
||
gcd(b, a % b)
|
||
}
|
||
}
|
||
pub fn sum_fracts(l: Vec<(i64, i64)>) -> Option<(i64, i64)> {
|
||
if l.len() == 0 {
|
||
None
|
||
} else {
|
||
let res = l.iter().fold((0, 1), |acc, item| {
|
||
// dbg!(&acc,&item);
|
||
let n = acc.0 * item.1 + acc.1 * item.0;
|
||
// dbg!(n);
|
||
let d = acc.1 * item.1;
|
||
// dbg!(d);
|
||
let g = gcd(n, d);
|
||
// dbg!(g);
|
||
(n / g, d / g)
|
||
});
|
||
// eprintln!("{}/{}",res.0,res.1); //13/12
|
||
Some(res)
|
||
}
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-18-最大公约数"><a class="header" href="#kata-18-最大公约数">Kata 18 (最大公约数)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>//最大公约数
|
||
pub fn gcd(a: i64, b: i64) -> i64 {
|
||
if b == 0 {
|
||
a
|
||
} else {
|
||
gcd(b, a % b)
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-19-最小公倍数"><a class="header" href="#kata-19-最小公倍数">Kata 19 (最小公倍数)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>//公式法求最小公倍数
|
||
pub fn lcm(a: i32,b: i32) -> i32 {
|
||
a*b/gcd(a,b)
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-20前-n-个-prime-number-的乘积"><a class="header" href="#kata-20前-n-个-prime-number-的乘积">Kata 20(前 n 个 prime number 的乘积)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>/**
|
||
* in:n :usize
|
||
* out:前n个prime number的乘积
|
||
*/
|
||
mod primorial_of_a_number{
|
||
pub fn num_primorial(n: usize) -> u64 {
|
||
let mut vec = vec![];
|
||
for i in 2..100{
|
||
if is_prime(i as u64){
|
||
vec.push(i);
|
||
}
|
||
}
|
||
let mut count =0;
|
||
let mut mul =1;
|
||
for i in 0..vec.len(){
|
||
mul*=vec[i];
|
||
count += 1;
|
||
if count==n{
|
||
break;
|
||
}
|
||
}
|
||
mul
|
||
}
|
||
pub fn is_prime(p: u64) -> bool {
|
||
p >= 2 &&
|
||
(2..)
|
||
.take_while(|q| q * q <= p)
|
||
.all(|q| p % q != 0)
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-21-丢番图方程--diophantine-equation"><a class="header" href="#kata-21-丢番图方程--diophantine-equation">Kata 21 (丢番图方程 , Diophantine Equation)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust">/**
|
||
* 丢番图方程
|
||
* Diophantine Equation
|
||
* x2 - 4 * y2 = n
|
||
https://www.codewars.com/kata/554f76dca89983cc400000bb/train/rust
|
||
*/
|
||
mod diophantine_equation{
|
||
pub fn solequa(n: u64) -> Vec<(u64, u64)> {
|
||
let mut result = vec![];
|
||
if n % 4 == 2 { return result; } // early bailout
|
||
let rn = (n as f64).sqrt() as u64;
|
||
for a in 1u64..rn+1 {
|
||
let b = n/a;
|
||
if b*a != n || (b-a) % 4 != 0 { continue; }
|
||
let y = (b-a) / 4;
|
||
let x = a + 2*y;
|
||
result.push((x,y));
|
||
}
|
||
result
|
||
}
|
||
}
|
||
fn main(){
|
||
eprintln!("{:?}",diophantine_equation::solequa(5)); //[(3, 1)]
|
||
eprintln!("{:?}",diophantine_equation::solequa(20)); //[(6, 2)]
|
||
}</code></pre></pre>
|
||
<h2 id="kata-22-convet_char_vec_string_vec"><a class="header" href="#kata-22-convet_char_vec_string_vec">Kata 22 (convet_char_vec_string_vec)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>fn convet_char_vec_string_vec(vec:Vec<char>)->Vec<String> {
|
||
let mut v = vec![];
|
||
for i in vec.iter() {
|
||
if !i.is_ascii_whitespace(){
|
||
let mut s = "".to_string();
|
||
s.push(*i);
|
||
s.push_str(" ");
|
||
v.push(s);
|
||
}
|
||
}
|
||
v
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-23-assert-type-in-rust"><a class="header" href="#kata-23-assert-type-in-rust">Kata 23 (assert type in rust)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>pub mod rust_type_assert{
|
||
pub fn run() {
|
||
use std::any::Any;
|
||
pub fn is_string(s: &dyn Any)->&str {
|
||
if s.is::<String>() {
|
||
return "It's a string!";
|
||
} else {
|
||
return "Not a string...";
|
||
}
|
||
}
|
||
assert_eq!(is_string(&"aa"),"Not a string...");
|
||
assert_eq!(is_string(&"aa".to_string()),"It's a string!");
|
||
pub fn is_i64(s: &dyn Any)->&str {
|
||
if s.is::<i64>() {
|
||
return "It's a i64!";
|
||
} else {
|
||
return "Not a i64...";
|
||
}
|
||
}
|
||
assert_eq!(is_i64(&12),"Not a i64...");
|
||
assert_eq!(is_i64(&(12 as i64)),"It's a i64!");
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-24-casting-binary-float-to-integer-进制转换"><a class="header" href="#kata-24-casting-binary-float-to-integer-进制转换">Kata 24 (Casting binary float to integer 进制转换)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>/**
|
||
* 10.0 (f32) == 01000001001000000000000000000000 (binary)
|
||
* convert_to_i32(10.0) returns 1092616192 (i32)
|
||
*/
|
||
pub mod casting_binary_float_to_integer{
|
||
// return binary representation as i32
|
||
use std::cell::RefCell;
|
||
pub fn convert_to_i32(f: f32) -> i32 {
|
||
let ff:RefCell<f32> = RefCell::new(f);
|
||
// eprintln!("2进制:{:b}", 10);
|
||
// eprintln!("{:?}", ff.clone().borrow_mut().to_bits() as i32);
|
||
// println!("8进制:{:o}", 10);
|
||
// println!("16进制:{:x}", 10);
|
||
ff.clone().borrow_mut().to_bits() as i32
|
||
}
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
#[test]
|
||
fn provided_tests() {
|
||
assert_eq!(convert_to_i32(10.0), 1092616192);
|
||
assert_eq!(convert_to_i32(f32::INFINITY), 0x7f800000);
|
||
assert_eq!(convert_to_i32(1.40129846432e-44), 10);
|
||
}
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-25-cow-in-rust"><a class="header" href="#kata-25-cow-in-rust">Kata 25 (Cow in Rust)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>//Cow
|
||
pub mod cow_demo{
|
||
use std::borrow::Cow;
|
||
pub fn run(){
|
||
fn abs_all(input: &mut Cow<[i32]>) {
|
||
for i in 0..input.len() {
|
||
let v = input[i];
|
||
if v < 0 {
|
||
input.to_mut()[i] = -v;
|
||
}
|
||
}
|
||
}
|
||
let slice = [0, -31, 2];
|
||
let mut input = Cow::from(&slice[..]);
|
||
abs_all(&mut input);
|
||
input.to_mut().push(-120);
|
||
println!("to_mut {:?}", input);
|
||
//use from
|
||
let s = Cow::from("alen ");
|
||
println!("from {:?}", s.clone()+"andry");
|
||
println!("from {:?}", s.clone().to_string());
|
||
//use to_owned
|
||
use std::borrow::Borrow;
|
||
let b = Cow::from("ops b!");
|
||
let cow_borrow = Cow::to_owned(&b);
|
||
println!("cow_borrow: {:?}", cow_borrow.clone());
|
||
//use from_iter
|
||
use std::iter::FromIterator;
|
||
let iter = Vec::from_iter([0,5,15].iter());
|
||
let iter1 = Vec::from_iter((0..15).into_iter());
|
||
let iter_cow = Cow::from_iter(iter);
|
||
let iter_cow1 = Cow::from_iter(iter1.clone());
|
||
println!("from_iter {:?}", iter_cow);
|
||
println!("from_iter {:?}", iter_cow1);
|
||
let find_7 = iter1.iter().find(|&&x| x == 7).unwrap();
|
||
println!("iter1 include 7 : {:?}", *find_7==7);
|
||
}}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-26-cell-in-rust"><a class="header" href="#kata-26-cell-in-rust">Kata 26 (Cell in Rust)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>//Cell
|
||
pub mod cell_demo{
|
||
use std::cell::Cell;
|
||
use std::cell::RefCell;
|
||
struct Point{x:usize, y:usize,sum:Cell<Option<usize>>}
|
||
impl Point {
|
||
pub fn sum(&self) -> usize {
|
||
match self.sum.get() {
|
||
Some(sum) => {
|
||
println!("{}",sum);
|
||
sum
|
||
},
|
||
None => {
|
||
let new_sum = self.x+self.y;
|
||
self.sum.set(Some(new_sum));
|
||
println!("sum set: {:?}",new_sum);
|
||
new_sum
|
||
}
|
||
}
|
||
}
|
||
}
|
||
pub fn run() {
|
||
let p = Point{x:8,y:16,sum:Cell::new(None)};
|
||
println!("{}",p.sum());
|
||
println!("{}",p.sum());
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-27-refcell-in-rust"><a class="header" href="#kata-27-refcell-in-rust">Kata 27 (RefCell in Rust)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>//RefCell
|
||
pub mod refcell_demo{
|
||
use std::cell::RefCell;
|
||
struct Point{x:usize, y:usize,sum:RefCell<Option<usize>>}
|
||
impl Point {
|
||
pub fn sum(&self) -> usize {
|
||
match self.sum.take() {
|
||
Some(sum) => {
|
||
println!("{}",sum);
|
||
sum
|
||
},
|
||
None => {
|
||
let new_sum = self.x+self.y;
|
||
self.sum.replace(Some(new_sum));
|
||
println!("sum set: {:?}",new_sum);
|
||
new_sum
|
||
}
|
||
}
|
||
}
|
||
}
|
||
pub fn run() {
|
||
let p = Point{x:8,y:16,sum:RefCell::new(None)};
|
||
println!("{}",p.sum());
|
||
println!("{}",p.sum());
|
||
use std::cell::RefCell;
|
||
let c1 = RefCell::new(5);
|
||
let ptr = c1.as_ptr();
|
||
println!("{:?}",ptr);
|
||
let mut c2 = RefCell::new(5);
|
||
*c2.get_mut() += 1;
|
||
assert_eq!(c2, RefCell::new(6));
|
||
println!("{:?}",c2);
|
||
println!("before take:{:?}",c2.take());
|
||
println!("after take:{:?}",c2.take());
|
||
println!("after take:{:?}",c2.take());
|
||
println!("after take:{:?}",c2.take());
|
||
let mut cc = *c2.borrow_mut();
|
||
cc+=0;
|
||
println!("{:?}",cc);
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-28-impl-drop-trait-in-rust"><a class="header" href="#kata-28-impl-drop-trait-in-rust">Kata 28 (impl Drop trait in Rust)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>pub mod drop_demo{
|
||
struct Person{
|
||
name: String,
|
||
}
|
||
impl Drop for Person{
|
||
fn drop(&mut self) {
|
||
println!("drop:{}",self.name);
|
||
}
|
||
}
|
||
pub fn run(){
|
||
let _alen = Person{name: "Alen".into()};
|
||
let _andry = Person{name: "Andry".into()};
|
||
eprintln!("{},{}",_alen.name,_andry.name);
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-29-每-n-个位组合存到-hashset-中已存的值重复的话-return-false"><a class="header" href="#kata-29-每-n-个位组合存到-hashset-中已存的值重复的话-return-false">Kata 29 (每 n 个位组合存到 HashSet 中,已存的值重复的话 return false)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>/**
|
||
* https://www.codewars.com/kata/60aee6ae617c26004717d257/solutions
|
||
*/
|
||
#[allow(dead_code)]
|
||
#[allow(unused_variables)]
|
||
pub mod de_bruijn_sequences{
|
||
use std::collections::HashSet;
|
||
pub fn de_bruijn_sequence(sequence: &str, n: usize) -> bool {
|
||
let mut vec_sequence: Vec<u8> = sequence.bytes().collect();
|
||
vec_sequence.extend(vec_sequence[..n - 1].to_vec());
|
||
eprintln!("{:?}",vec_sequence);
|
||
let mut seen: HashSet<Vec<u8>> = HashSet::new();
|
||
for i in 0..sequence.len() {
|
||
if !seen.insert(vec_sequence[i..(i + n)].to_vec()) {
|
||
return false;
|
||
}
|
||
}
|
||
//每n个位组合存到HashSet中,已存的值重复的话return false
|
||
eprintln!("{:?}",seen);
|
||
true
|
||
}
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
#[test]
|
||
fn sample_tests() {
|
||
assert_eq!(de_bruijn_sequence("0011", 2), true);//01,00,11,10
|
||
assert_eq!(de_bruijn_sequence("abcd", 2), true);
|
||
assert_eq!(de_bruijn_sequence("0101", 2), false);
|
||
assert_eq!(de_bruijn_sequence("11231", 2), false);
|
||
assert_eq!(de_bruijn_sequence("aabca", 3), true);
|
||
assert_eq!(de_bruijn_sequence("00000111011010111110011000101001", 5), true);
|
||
assert_eq!(de_bruijn_sequence("11111000001110110011010001001010", 5), true);
|
||
assert_eq!(de_bruijn_sequence("0011123302031321", 2), false);
|
||
}
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-30-很大数的乘积和很大数的幂"><a class="header" href="#kata-30-很大数的乘积和很大数的幂">Kata 30 (很大数的乘积和很大数的幂)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>/**
|
||
* power function for large numbers,multiply large numbers
|
||
* 很大数的乘积和很大数的幂
|
||
*/
|
||
#[allow(dead_code)]
|
||
#[allow(unused_variables)]
|
||
#[allow(unused_mut)]
|
||
pub mod power_function_for_large_numbers{
|
||
pub fn power(a:String, b:String) -> String {
|
||
let mut s = a.clone();
|
||
for i in 0..b.parse::<i32>().unwrap()-1 {
|
||
// println!("{}",s);
|
||
s=mul(s.clone(),a.clone());
|
||
}
|
||
fn mul(a:String,aa:String)-> String {
|
||
multiply_large_numbers(a.clone(),aa.clone())
|
||
}
|
||
s
|
||
}
|
||
pub fn multiply_large_numbers(num1:String, num2:String)->String{
|
||
let len1 = num1.len();
|
||
let len2 = num2.len();
|
||
let num1_str:Vec<i32> = num1.split("")
|
||
.filter(|s| !s.is_empty())
|
||
.collect::<Vec<_>>().iter().map(|s| s.parse::<i32>().unwrap()).collect();
|
||
let num2_str:Vec<i32> = num2.split("")
|
||
.filter(|s| !s.is_empty())
|
||
.collect::<Vec<_>>().iter().map(|s| s.parse::<i32>().unwrap()).collect();
|
||
if len1 == 0 || len2 == 0 {
|
||
return "0".into();
|
||
}
|
||
let mut result:Vec<i32> = "0".repeat(len1+len2).split("")
|
||
.filter(|s| !s.is_empty())
|
||
.collect::<Vec<_>>().iter()
|
||
.map(|s| s.parse::<i32>().unwrap()).collect();
|
||
let mut i_n1 = 0;
|
||
let mut i_n2 = 0;
|
||
for i in 0..len1{
|
||
let ii = len1-i-1;
|
||
let mut carry = 0;
|
||
let mut n1 = num1_str[ii];
|
||
let mut i_n2 = 0;
|
||
for j in 0..len2{
|
||
let jj = len2-j-1;
|
||
let mut n2 = num2_str[jj];
|
||
let mut summ = n1 * n2 + result[i_n1 + i_n2] + carry;
|
||
let carry = summ;
|
||
let sum_i_n = i_n1+i_n2;
|
||
result[sum_i_n] = summ % 10;
|
||
i_n2 += 1;
|
||
}
|
||
if carry > 0{
|
||
result[i_n1 + i_n2] += carry
|
||
}
|
||
i_n1 += 1;
|
||
}
|
||
let mut i:i32 = result.len() as i32 - 1;
|
||
while i>=0 && result[i as usize] == 0{
|
||
i -= 1
|
||
}
|
||
if i == -1{
|
||
return "0".into()
|
||
}
|
||
let mut s:String = "".into();
|
||
while i >= 0{
|
||
s.push_str(&result[i as usize].to_string());
|
||
i -= 1;
|
||
}
|
||
return s
|
||
}
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
#[test]
|
||
fn test_power() {
|
||
assert_eq!(power(String::from("10"),String::from("7")),"10000000");
|
||
}
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-31-merge-two-vec-and-return-median-number"><a class="header" href="#kata-31-merge-two-vec-and-return-median-number">Kata 31 (Merge Two Vec and Return median number)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>pub mod mearge_two_vec_return_median{
|
||
use std::convert::TryInto;
|
||
pub fn mearge_vec<T:Clone+Ord>(a:Vec<T>,b:Vec<T>) -> T
|
||
where
|
||
T: std::ops::Add<Output = T>+Ord+Clone+Copy+std::ops::Div<Output = T>+std::convert::Into<T>+From<i32>,
|
||
{
|
||
let mut a = a.clone();
|
||
for item in b.iter() {
|
||
a.push(*item);
|
||
}
|
||
a.sort();
|
||
let l = a.len();
|
||
if l%2 !=0 {
|
||
let mid = a.len()/2;
|
||
let mid_num = a[mid];
|
||
return mid_num;
|
||
}else{
|
||
let mid = a.len()/2;
|
||
let mid_num = a[mid]+a[mid-1];
|
||
return mid_num.into() /2.into();
|
||
}
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-32-string-add-split_to_vec-tarit"><a class="header" href="#kata-32-string-add-split_to_vec-tarit">Kata 32 (String add split_to_vec tarit)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>pub mod string_add_trait{
|
||
trait SplitToVec{
|
||
fn split_to_vec(self,word:String)->Vec<String>;
|
||
}
|
||
impl SplitToVec for String{
|
||
fn split_to_vec(self,word:String)->Vec<String>{
|
||
let v = self.split(&word).filter(|s|!s.is_empty()).collect::<Vec<&str>>();
|
||
v.iter().map(|s| s.to_string()).collect::<Vec<_>>()
|
||
}
|
||
}
|
||
pub fn run_string(){
|
||
let s = String::from("name: alen andry");
|
||
let v = s.split_to_vec(" ".into()); //["name:", "alen", "andry"]
|
||
println!("{:?}", v);
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-33-字符串中字符的出现次数统计"><a class="header" href="#kata-33-字符串中字符的出现次数统计">Kata 33 (字符串中字符的出现次数统计)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>// code war problems url :https://www.codewars.com/kata/57a6633153ba33189e000074/train/rust
|
||
// Example:
|
||
// ordered_count("abracadabra") == vec![('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)]
|
||
#[allow(dead_code)]
|
||
#[allow(unused_variables)]
|
||
#[allow(unused_mut)]
|
||
use std::collections::BTreeMap;
|
||
fn ordered_count(sip: &str) -> Vec<(char, i32)> {
|
||
let sip = sip.to_owned();
|
||
let set_sip = sip.clone();
|
||
let mut arr_sip: Vec<char> = set_sip.chars().collect();
|
||
arr_sip.sort();
|
||
arr_sip.reverse();
|
||
// println!("{:?}", arr_sip);
|
||
let mut bmap = BTreeMap::new();
|
||
for x in arr_sip {
|
||
bmap.insert(x, count_x_in_sip(&sip, x));
|
||
}
|
||
// println!("{:?}", bmap);
|
||
fn count_x_in_sip(sip: &str, target: char) -> i32 {
|
||
let mut c: i32 = 0;
|
||
for x in sip.chars() {
|
||
if target == x {
|
||
c += 1;
|
||
}
|
||
}
|
||
return c;
|
||
}
|
||
// bmap to tuple vec
|
||
fn convert_bmap_to_vec(bmap: BTreeMap<char, i32>) -> Vec<(char, i32)> {
|
||
let mut vec = vec![];
|
||
for (v, k) in &bmap {
|
||
vec.push((v.to_owned(), k.to_owned()));
|
||
}
|
||
return vec;
|
||
}
|
||
return convert_bmap_to_vec(bmap);
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-34-find-most-common-element-找出出现次数最多的元素"><a class="header" href="#kata-34-find-most-common-element-找出出现次数最多的元素">Kata 34 (find most common element 找出出现次数最多的元素)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust">fn main() {
|
||
/*{"a": 2, "b": 3, "m": 1, "s": 3}
|
||
common item val :"b"
|
||
common item index :1
|
||
common item val :"s"
|
||
common item index :3
|
||
*/
|
||
let str = "aabbbssms";
|
||
fn find_most_common(str: &str) -> [(&str, i32); 1] {
|
||
let mut bmap = BTreeMap::new();
|
||
let str_vec = str.split("").filter(|s| !s.is_empty()).collect::<Vec<_>>();
|
||
for i in 0..str_vec.len() {
|
||
if !bmap.contains_key(str_vec[i]) {
|
||
bmap.insert(str_vec[i], 1);
|
||
} else {
|
||
let mut count = bmap
|
||
.get(str_vec[i])
|
||
.unwrap()
|
||
.to_string()
|
||
.parse::<i32>()
|
||
.unwrap();
|
||
count += 1;
|
||
bmap.insert(str_vec[i], count);
|
||
}
|
||
}
|
||
fn find_max<I>(iter: I) -> Option<I::Item>
|
||
where
|
||
I: Iterator,
|
||
I::Item: Ord,
|
||
{
|
||
iter.reduce(|a, b| if a >= b { a } else { b })
|
||
}
|
||
println!("{:?}", bmap);
|
||
// println!("{:?}", bmap.keys());
|
||
// println!("{:?}", bmap.values());
|
||
for (index, item) in bmap.values().enumerate() {
|
||
if item == find_max(bmap.values()).unwrap() {
|
||
let vec: Vec<&str> = bmap.keys().cloned().collect();
|
||
println!("common item val :{:?}", vec[index]);
|
||
println!("common item index :{:?}", index);
|
||
}
|
||
}
|
||
// println!("{:?}", find_max(bmap.values()).unwrap());
|
||
return [("", find_max(bmap.values()).unwrap().to_owned())];
|
||
}
|
||
find_most_common(str);
|
||
}</code></pre></pre>
|
||
<h2 id="kata-35-sort-float-vec-从小到大-排序"><a class="header" href="#kata-35-sort-float-vec-从小到大-排序">Kata 35 (Sort float Vec 从小到大 排序)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust">fn main() {
|
||
//sort 从小到大 排序
|
||
let mut vec = vec![100.1, 1.15, 5.5, 1.123, 2.0];
|
||
vec.sort_by(|a, b| a.partial_cmp(b).unwrap());
|
||
println!("{:?}", vec);
|
||
assert_eq!(vec, vec![1.123, 1.15, 2.0, 5.5, 100.1]);
|
||
}</code></pre></pre>
|
||
<h2 id="kata-36-slice-string-use-input-read-string"><a class="header" href="#kata-36-slice-string-use-input-read-string">Kata 36 (slice String, use input!() read string)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>#[allow(unused_variables)]
|
||
fn slice_string(in_string: String, start: i32, end: i32) -> String {
|
||
let mut s = Vec::new();
|
||
let in_string_vec = in_string
|
||
.split("")
|
||
.filter(|s| !s.is_empty())
|
||
.collect::<Vec<_>>();
|
||
if start < 0 && end > in_string_vec.len() as i32 {
|
||
return "out of range".to_owned();
|
||
} else {
|
||
for i in start..end {
|
||
s.push(in_string_vec[i as usize]);
|
||
}
|
||
}
|
||
return s.join("").to_string();
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="自己定义的-input-快速-io-输入值"><a class="header" href="#自己定义的-input-快速-io-输入值">自己定义的 input!() (快速 IO 输入值)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust">#[allow(unused_macros)]
|
||
macro_rules! input {
|
||
() => {{
|
||
let mut string = String::new();
|
||
std::io::stdin().read_line(&mut string).unwrap();
|
||
string
|
||
}};
|
||
}
|
||
fn main() {
|
||
let s = input!();
|
||
println!("{:?}", s); //"alen andry\n"
|
||
assert_eq!("alen andry\n".to_string(), s);
|
||
}</code></pre></pre>
|
||
<h2 id="kata-37-输出-string-的全排序"><a class="header" href="#kata-37-输出-string-的全排序">Kata 37 (输出 String 的全排序)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust">// input '123' 输出string的全排序
|
||
// ["1", "12", "123", "2", "23", "3"]
|
||
pub mod c {
|
||
pub fn run() {
|
||
use proconio::{input, marker::*};
|
||
input! {
|
||
mut s: Chars,
|
||
}
|
||
let s = s.iter_mut().map(|x| x.to_string()).collect::<Vec<_>>();
|
||
// println!("{:?}", s);
|
||
#[allow(unused_variables)]
|
||
fn slice_string(in_string: String, start: i32, end: i32) -> String {
|
||
let mut s = Vec::new();
|
||
let in_string_vec = in_string
|
||
.split("")
|
||
.filter(|s| !s.is_empty())
|
||
.collect::<Vec<_>>();
|
||
if start < 0 && end > in_string_vec.len() as i32 {
|
||
return "out of range".to_owned();
|
||
} else {
|
||
for i in start..end {
|
||
s.push(in_string_vec[i as usize]);
|
||
}
|
||
}
|
||
return s.join("").to_string();
|
||
}
|
||
// let some_string = slice_string(s_string, 0, 3);
|
||
// println!("{:?}", some_string);
|
||
let s_string = s.join("").to_string();
|
||
let mut out_vec = Vec::new();
|
||
for i in 0..s.len() + 1 {
|
||
for j in i + 1..s.len() + 1 {
|
||
out_vec.push(slice_string(s_string.clone(), i as i32, j as i32));
|
||
}
|
||
}
|
||
println!("{:?}", out_vec);
|
||
// input '123' 输出string的全排序
|
||
// ["1", "12", "123", "2", "23", "3"]
|
||
}
|
||
}
|
||
fn main() {
|
||
c::run();
|
||
}</code></pre></pre>
|
||
<h2 id="kata-38-各位相加到小于-9-时输出合"><a class="header" href="#kata-38-各位相加到小于-9-时输出合">Kata 38 (各位相加到小于 9 时输出合)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust">/*
|
||
各位相加到小于9 时输出
|
||
imput 15 ->6
|
||
imput 19 ->1
|
||
imput 238 ->4
|
||
*/
|
||
pub mod c {
|
||
pub fn run() {
|
||
use proconio::{input, marker::*};
|
||
input! {
|
||
mut s: Chars,
|
||
}
|
||
let s = s
|
||
.iter_mut()
|
||
.map(|x| x.to_string().parse::<i32>().unwrap())
|
||
.collect::<Vec<_>>();
|
||
// println!("{:?}", s);
|
||
fn count(arr: Vec<i32>) -> i32 {
|
||
let mut sum = 0;
|
||
for i in 0..arr.len() {
|
||
sum += arr[i];
|
||
}
|
||
if sum <= 9 {
|
||
println!("{:?}", sum);
|
||
} else {
|
||
let arr = sum
|
||
.to_string()
|
||
.chars()
|
||
.map(|x| x.to_string().parse::<i32>().unwrap())
|
||
.collect::<Vec<_>>();
|
||
// println!("{:?}", arr);
|
||
count(arr);
|
||
}
|
||
return 0;
|
||
}
|
||
count(s);
|
||
}
|
||
}
|
||
fn main() {
|
||
c::run();
|
||
}</code></pre></pre>
|
||
<h2 id="kata-39-选择排序-slection_sort"><a class="header" href="#kata-39-选择排序-slection_sort">Kata 39 (选择排序 slection_sort)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>#[allow(dead_code)]
|
||
// code war problems url :https://www.codewars.com/kata/5861d28f124b35723e00005e/train/rust
|
||
pub fn slection_sort(arr: &Vec<i32>) -> Vec<i32> {
|
||
// write code here
|
||
let length = arr.len();
|
||
let mut arr = arr.to_owned();
|
||
let mut minindex;
|
||
let mut temp;
|
||
for i in 0..length - 1 {
|
||
minindex = i;
|
||
for j in i + 1..length {
|
||
if arr[j] < arr[minindex] {
|
||
minindex = j;
|
||
}
|
||
}
|
||
temp = arr[i];
|
||
arr[i] = arr[minindex];
|
||
arr[minindex] = temp;
|
||
}
|
||
return arr;
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-40-vec-中删除重复的部分"><a class="header" href="#kata-40-vec-中删除重复的部分">Kata 40 (vec 中删除重复的部分)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>#[allow(dead_code)]
|
||
#[allow(unused_variables)]
|
||
#[allow(unused_mut)]
|
||
pub fn run() {
|
||
fn unique_in_order<T>(sequence: T) -> Vec<T::Item>
|
||
where
|
||
T: std::iter::IntoIterator,
|
||
T::Item: std::cmp::PartialEq + std::fmt::Debug,
|
||
{
|
||
let mut v: Vec<_> = sequence.into_iter().collect();
|
||
v.dedup();
|
||
v
|
||
}
|
||
let data = vec!["A", "A", "B", "b", "b", "b"];
|
||
let data2 = "AAAABBBCCDAABBB".chars();
|
||
println!("{:?}", unique_in_order(data)); //["A", "B", "b"]
|
||
println!("{:?}", unique_in_order(data2)); //['A', 'B', 'C', 'D', 'A', 'B']
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-41-rust-implement-fib-function-"><a class="header" href="#kata-41-rust-implement-fib-function-">Kata 41 (Rust implement fib function )</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>pub fn run() {
|
||
//produce fib
|
||
fn product_fib(prod: u64) {
|
||
// your code
|
||
let mut p: i64 = prod as i64;
|
||
fn fib(n: u64) -> u64 {
|
||
match n {
|
||
0 => 1,
|
||
1 => 1,
|
||
_ => fib(n - 1) + fib(n - 2),
|
||
}
|
||
}
|
||
let mut list: Vec<u64> = Vec::new();
|
||
while p > -1 {
|
||
list.push(fib(p as u64));
|
||
p -= 1;
|
||
}
|
||
println!("{:?}", list);
|
||
}
|
||
product_fib(8); //produce 8 number
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-42-lettcode-two_sum-problem-solution-in-rust"><a class="header" href="#kata-42-lettcode-two_sum-problem-solution-in-rust">Kata 42 (Lettcode two_sum problem solution in rust)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>use std::collections::HashMap;
|
||
pub fn run(){
|
||
fn two_sum(nums: Vec<i32>,taget:i32)-> Vec<i32>{
|
||
let mut h_map = HashMap::new();
|
||
for i in 0..nums.len(){
|
||
if let Some(&j) = h_map.get(&(taget-nums[i])){
|
||
return vec![j as i32,i as i32];
|
||
}
|
||
else{
|
||
h_map.insert(nums[i],i);
|
||
}
|
||
}
|
||
vec![]
|
||
}
|
||
let result = two_sum(vec![1,2,0,2],2);
|
||
println!("{:?}",result);
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-43-use-mutex-多线程共享一个值"><a class="header" href="#kata-43-use-mutex-多线程共享一个值">Kata 43 (Use mutex 多线程共享一个值)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>pub mod mutex {
|
||
pub fn run() {
|
||
use std::sync::Mutex;
|
||
let l: &'static _ = Box::leak(Box::new(Mutex::new(0.0)));
|
||
let handlers = (0..999)
|
||
.map(|_| {
|
||
std::thread::spawn(move || {
|
||
for _ in 0..9999 {
|
||
*l.lock().unwrap() += 0.0001;
|
||
}
|
||
})
|
||
})
|
||
.collect::<Vec<_>>();
|
||
for handler in handlers {
|
||
handler.join().unwrap();
|
||
}
|
||
assert_eq!(*l.lock().unwrap(), 999.0 * 9999.0);
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-44-implment-default-for-type"><a class="header" href="#kata-44-implment-default-for-type">Kata 44 (implment default for type)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>pub mod implment_default {
|
||
struct Grounded;
|
||
impl Default for Grounded {
|
||
fn default() -> Self {Grounded}
|
||
}
|
||
struct Launched;
|
||
// and so on
|
||
struct Rocket<Stage = Grounded> {
|
||
stage: std::marker::PhantomData<Stage>,
|
||
}
|
||
impl Default for Rocket<Grounded>
|
||
where
|
||
Grounded:Default,
|
||
{
|
||
fn default() -> Self {
|
||
Rocket{stage:std::marker::PhantomData}
|
||
}
|
||
}
|
||
impl Rocket<Grounded> {
|
||
pub fn launch(self) -> Rocket<Launched> {
|
||
Rocket{stage:std::marker::PhantomData}
|
||
}
|
||
}
|
||
impl Rocket<Launched> {
|
||
pub fn accelerate(&mut self) {}
|
||
pub fn decelerate(&mut self) {}
|
||
}
|
||
struct Color;
|
||
struct Kilograms;
|
||
impl<Stage> Rocket<Stage> {
|
||
pub fn color(&self) -> Color {Color}
|
||
pub fn weight(&self) -> Kilograms {Kilograms}
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-45-use-cow"><a class="header" href="#kata-45-use-cow">Kata 45 (Use Cow)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>#[allow(unused)]
|
||
pub mod use_cow {
|
||
use std::borrow::Cow;
|
||
use std::sync::Arc;
|
||
fn test(ref a: String) {
|
||
eprintln!("{:?}", a);
|
||
}
|
||
fn test1(v: &mut Vec<&str>) {
|
||
v.push("z");
|
||
v.push("x");
|
||
v.push("y");
|
||
for item in v.splitn(3, |s| *s == "x") {
|
||
println!("split: {:?}", item);
|
||
}
|
||
v.reverse();
|
||
eprintln!("{:?}", v);
|
||
}
|
||
pub fn run() {
|
||
let s = String::from("ok");
|
||
test(Cow::from(&s).clone().to_string());
|
||
eprintln!("{:?}", s);
|
||
let mut v = vec!["a", "b"];
|
||
test1(&mut Cow::from(&v).clone().to_vec());
|
||
v.sort();
|
||
eprintln!("{:?}", v.join(&" "));
|
||
eprintln!("{:?}", v);
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-46-二维vec-sort_by_row"><a class="header" href="#kata-46-二维vec-sort_by_row">Kata 46 (二维Vec sort_by_row)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>pub fn sort_by_row(arr: Vec<Vec<f64>>,row:usize) -> Vec<Vec<f64>> {
|
||
// write code here
|
||
let length = arr[row].len();
|
||
let mut arr = arr.to_owned();
|
||
let mut minindex;
|
||
for i in 0..length - 1 {
|
||
minindex = i;
|
||
for j in i + 1..length {
|
||
if arr[row][j] > arr[row][minindex] {
|
||
minindex = j;
|
||
}
|
||
}
|
||
for k in 0..row+1{
|
||
arr[k].swap(minindex,i);
|
||
}
|
||
}
|
||
return arr;
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-47-implement-clonal-selection-algorithm"><a class="header" href="#kata-47-implement-clonal-selection-algorithm">Kata 47 (<em>Implement clonal selection algorithm</em>)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>pub mod clonal_selection_algorithm {
|
||
use rand::{thread_rng, Rng};
|
||
pub fn y(a: f64, b: f64) -> f64 {
|
||
let aa = -30.0 * f64::powf(b, 4.0);
|
||
let bb = 64.0 * f64::powf(b, 3.0);
|
||
let cc = 43.8 * f64::powf(b, 2.0);
|
||
let dd = 10.8 * f64::powf(b, 1.0);
|
||
let ee = (aa + bb + cc + dd) * 1000.0 * f64::sin(5.0 * std::f64::consts::PI * a);
|
||
let ff = 1.0 + 0.1 * f64::powf(a, 2.0);
|
||
f64::abs(ee / ff)
|
||
}
|
||
pub fn cloning_number(beta: f64, population_number: f64, i: f64) -> f64 {
|
||
f64::floor((beta * population_number) / i)
|
||
}
|
||
pub fn generate_three_random(population_number: i32) -> Vec<Vec<f64>> {
|
||
fn generate() -> f64 {
|
||
let mut rng = thread_rng();
|
||
let m: f64 = rng.gen_range(0.0..1.0);
|
||
m
|
||
}
|
||
let mut temp: Vec<f64> = Vec::new();
|
||
let mut temp2: Vec<f64> = Vec::new();
|
||
let mut temp_fitness: Vec<f64> = Vec::new();
|
||
for i in 0..population_number as usize {
|
||
temp.push(generate());
|
||
temp2.push(generate());
|
||
temp_fitness.push(y(temp[i], temp2[i]));
|
||
}
|
||
vec![temp, temp2, temp_fitness]
|
||
}
|
||
pub fn sort_by_row(arr: Vec<Vec<f64>>,row:usize) -> Vec<Vec<f64>> {
|
||
// write code here
|
||
let length = arr[row].len();
|
||
let mut arr = arr.to_owned();
|
||
let mut minindex;
|
||
for i in 0..length - 1 {
|
||
minindex = i;
|
||
for j in i + 1..length {
|
||
if arr[row][j] > arr[row][minindex] {
|
||
minindex = j;
|
||
}
|
||
}
|
||
for k in 0..row+1{
|
||
arr[k].swap(minindex,i);
|
||
}
|
||
}
|
||
return arr;
|
||
}
|
||
pub fn mutaition(clon: Vec<&Vec<f64>>, theta: f64) -> Vec<Vec<f64>> {
|
||
fn generate() -> f64 {
|
||
let mut rng = thread_rng();
|
||
let m: f64 = rng.gen_range(0.0..1.0);
|
||
m
|
||
}
|
||
let mut mutation = vec![];
|
||
let clon = clon;
|
||
let mut clon1: Vec<Vec<f64>> = vec![];
|
||
let len_clon = clon.len();
|
||
for _ in 0..len_clon {
|
||
let mut vec = vec![];
|
||
for _ in 0..clon[0].len() {
|
||
vec.push(generate());
|
||
}
|
||
mutation.push(vec.clone());
|
||
clon1.push(vec.clone());
|
||
}
|
||
for i in 0..mutation.len() {
|
||
for j in 0..mutation[0].len() {
|
||
clon1[i][j] = clon[i][j];
|
||
}
|
||
}
|
||
for i in 0..mutation.len() {
|
||
for j in 0..mutation[0].len() {
|
||
if mutation[i][j] < theta {
|
||
clon1[i][j] = generate();
|
||
}
|
||
}
|
||
}
|
||
let mut yy = vec![];
|
||
for j in 0..clon1[0].len() {
|
||
yy.push(y(clon1.clone()[0][j],clon1.clone()[1][j]));
|
||
}
|
||
clon1.push(yy);
|
||
clon1
|
||
}
|
||
#[allow(unused)]
|
||
pub fn run() {
|
||
let mut iteration_number: i32 = 2;
|
||
let mut population_number: i32 = 4;
|
||
let mut n: usize = 10;
|
||
let mut beta: f64 = 5.0;
|
||
let mut theta: f64 = 0.2;
|
||
let population = generate_three_random(population_number);
|
||
let mut selected_population: Vec<f64> = vec![];
|
||
let new_population = sort_by_row(population.clone(),2);
|
||
let selected_population = vec![&new_population[0], &new_population[1]];
|
||
// println!("population {:#?}", population.clone());
|
||
// println!("new_population {:#?}", new_population.clone());
|
||
// println!("selected_population {:#?}", selected_population.clone());
|
||
let clone: Vec<&Vec<f64>> = selected_population.clone();
|
||
let new_clone = new_population.clone();
|
||
let last_population = new_clone.clone();
|
||
// println!("clone:{:#?}", &clone);
|
||
// println!("new_clone:{:#?}", &new_clone);
|
||
// println!("new_clone:{:#?}", &last_population);
|
||
let mutationed = mutaition(clone.clone(), theta);
|
||
println!("mutationed:{:#?}", &mutationed);
|
||
let mut sorted_mutation = sort_by_row(mutationed.clone(),2).to_owned();
|
||
println!("sorted_mutation:{:#?}", &sorted_mutation);
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-48-implement-coin_change-problem-还钱问题"><a class="header" href="#kata-48-implement-coin_change-problem-还钱问题">Kata 48 (<em>Implement coin_change problem</em> 还钱问题)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>pub mod coin_change{
|
||
pub fn solution(coins:Vec<i32>,amount:i32)->i32{
|
||
let mut max = amount+1;
|
||
let mut dp = (0..max).map(|_|{amount+1}).collect::<Vec<_>>();
|
||
dp[0]=0;
|
||
for i in 1..=amount as usize{
|
||
for j in 0..coins.len(){
|
||
if coins[j] as usize <= i{
|
||
dp[i]=std::cmp::min(dp[i], dp[i-coins[j] as usize]+1);
|
||
}
|
||
}
|
||
}
|
||
let mut re:i32;
|
||
if dp[amount as usize]>amount{
|
||
re = -1;
|
||
}else{
|
||
re = dp[amount as usize];
|
||
}
|
||
println!("{:?}", &dp);
|
||
println!("{:?}", &re);
|
||
re
|
||
}
|
||
pub fn run(){
|
||
solution(vec![2], 3);//-1
|
||
solution(vec![1,2,5], 11); //3
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-49-use-atomic-implement-mutex"><a class="header" href="#kata-49-use-atomic-implement-mutex">Kata 49 (use Atomic implement mutex)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>pub mod implement_mutex {
|
||
#[allow(dead_code)]
|
||
#[allow(unused)]
|
||
use std::cell::UnsafeCell;
|
||
use std::sync::atomic::{AtomicBool, Ordering};
|
||
const LOCKED: bool = true;
|
||
const UNLOCKED: bool = false;
|
||
pub struct Mutex<T> {
|
||
locked: AtomicBool,
|
||
v: UnsafeCell<T>,
|
||
}
|
||
impl<T> Mutex<T> {
|
||
fn new(t: T) -> Self {
|
||
Self {
|
||
locked: AtomicBool::new(UNLOCKED),
|
||
v: UnsafeCell::new(t),
|
||
}
|
||
}
|
||
fn with_lock<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
|
||
while self
|
||
.locked
|
||
.compare_exchange(UNLOCKED, LOCKED, Ordering::Acquire, Ordering::Acquire)
|
||
.is_err()
|
||
{
|
||
while self.locked.load(Ordering::Relaxed) == LOCKED {
|
||
std::thread::yield_now();
|
||
}
|
||
std::thread::yield_now();
|
||
}
|
||
// self.locked.store(LOCKED,Ordering::Relaxed);
|
||
let ret = f(unsafe { &mut *self.v.get() });
|
||
self.locked.store(UNLOCKED, Ordering::Release);
|
||
ret
|
||
}
|
||
}
|
||
unsafe impl<T> Sync for Mutex<T> where T: Send {}
|
||
unsafe impl<T> Send for Mutex<T> where T: Send {}
|
||
pub fn thread_handlers() {
|
||
let l: &'static _ = Box::leak(Box::new(Mutex::new(0)));
|
||
let handlers = (0..999)
|
||
.map(|_| {
|
||
std::thread::spawn(move || {
|
||
for _ in 0..999 {
|
||
l.with_lock(|v| {
|
||
*v += 1;
|
||
});
|
||
}
|
||
})
|
||
})
|
||
.collect::<Vec<_>>();
|
||
for handler in handlers {
|
||
handler.join().unwrap();
|
||
}
|
||
assert_eq!(l.with_lock(|v| *v), 999 * 999);
|
||
}
|
||
pub fn atomic_demo() {
|
||
use std::sync::atomic::AtomicUsize;
|
||
let x: &'static _ = Box::leak(Box::new(AtomicBool::new(false)));
|
||
let y: &'static _ = Box::leak(Box::new(AtomicBool::new(false)));
|
||
let z: &'static _ = Box::leak(Box::new(AtomicUsize::new(0)));
|
||
let _tx = std::thread::spawn(move || {
|
||
x.store(true, Ordering::SeqCst);
|
||
});
|
||
let _ty = std::thread::spawn(move || {
|
||
y.store(true, Ordering::SeqCst);
|
||
});
|
||
let t1 = std::thread::spawn(move || {
|
||
while !x.load(Ordering::Acquire) {
|
||
if y.load(Ordering::Acquire) {
|
||
z.fetch_add(1, Ordering::Release);
|
||
}
|
||
}
|
||
});
|
||
let t2 = std::thread::spawn(move || {
|
||
while !y.load(Ordering::Acquire) {
|
||
if x.load(Ordering::Acquire) {
|
||
z.fetch_add(1, Ordering::Release);
|
||
}
|
||
}
|
||
});
|
||
t1.join().unwrap();
|
||
t2.join().unwrap();
|
||
let z = z.load(Ordering::SeqCst);
|
||
eprintln!("{:?}", z);
|
||
}
|
||
pub fn run() {
|
||
// thread_handlers();
|
||
atomic_demo();
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-50-cmd_download_files"><a class="header" href="#kata-50-cmd_download_files">Kata 50 (cmd_download_files)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>#[allow(dead_code)]
|
||
#[allow(unused)]
|
||
#[allow(non_snake_case)]
|
||
pub mod cmd_download_files {
|
||
use std::io::{self, Write};
|
||
use std::process::Command;
|
||
use std::sync::Mutex;
|
||
pub fn download_all() {
|
||
let pdfs: Vec<Vec<&str>> = vec![vec![
|
||
"https://projecteuclid.org/download/pdf_1/euclid.ss/1028905930",
|
||
"https://otr.cypherpunks.ca/otr-wpes.pdf", "https://fahrplan.events.ccc.de/congress/2009/Fahrplan/attachments/1435_JTAG.pdf",
|
||
"https://philpapers.org/archive/RAATOR-2.pdf",
|
||
"https://www.usenix.org/system/files/sec20-sugawara.pdf",
|
||
]
|
||
];
|
||
use std::thread::JoinHandle;
|
||
fn download<'a>(url: &'static str) {
|
||
std::fs::create_dir_all("./pdfs");
|
||
if url.contains(".pdf") {
|
||
Command::new("duma")
|
||
.current_dir("./pdfs")
|
||
.arg("-c")
|
||
.arg("-n")
|
||
.arg("1000")
|
||
.arg("-T")
|
||
.arg("10")
|
||
.arg(url)
|
||
.spawn()
|
||
.expect("command failed to start");
|
||
}
|
||
}
|
||
let l: &'static _ = Box::leak(Box::new(Mutex::new(pdfs.clone())));
|
||
for item in pdfs.iter() {
|
||
for item1 in item.iter() {
|
||
download(item1);
|
||
}
|
||
}
|
||
println!("{}", "download started");
|
||
}
|
||
pub fn make_zip() {
|
||
fn zip(zip_name: &str, name: &str) {
|
||
Command::new("zip")
|
||
.current_dir("./")
|
||
.arg("-r")
|
||
.arg(zip_name)
|
||
.arg(name)
|
||
.spawn()
|
||
.expect("sh command failed to start");
|
||
println!("ok");
|
||
}
|
||
zip("pdfs.zip", "./pdfs");
|
||
// std::process::exit(1);
|
||
}
|
||
pub fn run() {
|
||
download_all();
|
||
make_zip();
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-51-rgb-to-hex-conversion"><a class="header" href="#kata-51-rgb-to-hex-conversion">Kata 51 (RGB To Hex Conversion)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>#[allow(dead_code)]
|
||
#[allow(unused)]
|
||
#[allow(non_snake_case)]
|
||
pub mod rgb_to_hex {
|
||
pub fn rgb(r: i32, g: i32, b: i32) -> String {
|
||
fn to_x(i: i32) -> String {
|
||
let mut result = String::new();
|
||
if i < 0 {
|
||
result = String::from("00")
|
||
} else if i > 255 {
|
||
result = String::from("FF")
|
||
} else {
|
||
if format!("{:x}", i).len() <= 1 {
|
||
let mut re = String::from("0");
|
||
re.push_str(&format!("{:x}", i).to_uppercase());
|
||
result = re;
|
||
} else {
|
||
result = format!("{:x}", i).to_uppercase();
|
||
}
|
||
}
|
||
result
|
||
}
|
||
format!("{}{}{}", to_x(r), to_x(g), to_x(b))
|
||
}
|
||
//another solution
|
||
fn rgb_1(r: i32, g: i32, b: i32) -> String {
|
||
format!(
|
||
"{:02X}{:02X}{:02X}",
|
||
r.clamp(0, 255),
|
||
g.clamp(0, 255),
|
||
b.clamp(0, 255)
|
||
)
|
||
}
|
||
pub fn run() {
|
||
assert_eq!(rgb(255, 255, 255), "FFFFFF".to_string());
|
||
assert_eq!(rgb(0, 0, 0), "000000".to_string());
|
||
assert_eq!(rgb(-20, 275, 125), "00FF7D".to_string());
|
||
assert_eq!(300.clamp(0, 255), 255);
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-52-the-look-and-say-sequence"><a class="header" href="#kata-52-the-look-and-say-sequence">Kata 52 (The Look and Say sequence)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>/***
|
||
* The Look and Say sequence
|
||
* https://www.codewars.com/kata/5263c5d011f4233c9d000561/train/rust
|
||
*/
|
||
#[allow(dead_code)]
|
||
#[allow(unused)]
|
||
#[allow(non_snake_case)]
|
||
pub mod look_and_say_sequence {
|
||
use itertools::{iterate, Itertools};
|
||
fn get_lines(n: usize) -> String {
|
||
iterate("1".to_owned(), |s| {
|
||
format!(
|
||
"{}",
|
||
s.chars()
|
||
.dedup_with_count()
|
||
.format_with("", |(k, x), f| f(&format_args!("{}{}", k, x)))
|
||
)
|
||
})
|
||
.take(n)
|
||
.join(",")
|
||
}
|
||
fn dedup_with_counts() {
|
||
//根基前后相同的元素进行count
|
||
use itertools::Itertools;
|
||
let data = vec!['a', 'a', 'b', 'c', 'c', 'b', 'b'];
|
||
itertools::assert_equal(
|
||
data.into_iter().dedup_with_count(),
|
||
vec![(2, 'a'), (1, 'b'), (2, 'c'), (2, 'b')],
|
||
);
|
||
}
|
||
pub fn run() {
|
||
println!("{:?}", get_lines(5));
|
||
println!("{:?}", get_lines(8));
|
||
}
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
#[test]
|
||
fn basic() {
|
||
assert_eq!(get_lines(2), "1,11");
|
||
assert_eq!(get_lines(3), "1,11,21");
|
||
assert_eq!(get_lines(5), "1,11,21,1211,111221");
|
||
}
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-53-molecule-to-atoms-已知化学式-返回每个化学元素的数量"><a class="header" href="#kata-53-molecule-to-atoms-已知化学式-返回每个化学元素的数量">Kata 53 (Molecule to atoms 已知化学式 返回每个化学元素的数量)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>/**
|
||
* Molecule to atoms 已知化学式 返回每个化学元素的数量
|
||
* https://www.codewars.com/kata/52f831fa9d332c6591000511/train/rust
|
||
* For example:
|
||
parse_molecule("H2O"); // water
|
||
// Ok([("H", 2), ("O", 1)])
|
||
parse_molecule("Mg(OH)2"); // magnesium hydroxide
|
||
// Ok([("Mg", 1), ("O", 2), ("H", 2)]
|
||
parse_molecule("K4[ON(SO3)2]2"); // Fremy's salt
|
||
// Ok([("K", 4), ("O", 14),("N", 2),("S", 4)])
|
||
parse_molecule("pie")
|
||
// Err(ParseError)
|
||
*/
|
||
#[allow(dead_code)]
|
||
#[allow(unused)]
|
||
#[allow(non_snake_case)]
|
||
pub mod molecule_to_atoms {
|
||
use std::collections::HashMap;
|
||
use thiserror::Error;
|
||
pub type Atom = (String, usize);
|
||
pub type Molecule = Vec<Atom>;
|
||
#[derive(Error, Debug)]
|
||
pub enum ParseError {
|
||
#[error("Not a valid molecule")]
|
||
InvalidName,
|
||
#[error("Mismatched parenthesis")]
|
||
ParensMismatch,
|
||
}
|
||
fn atom(s: &mut &[u8]) -> Atom {
|
||
let mut i = 1;
|
||
// dbg!(s.clone()[i] as char);
|
||
while i < s.len() && s[i].is_ascii_lowercase() {
|
||
//if second letter is lowercase i+=1
|
||
i += 1;
|
||
}
|
||
//from 0..i if the atom name
|
||
let name = std::str::from_utf8(&s[..i]).unwrap().to_string();
|
||
// dbg!(&name);
|
||
let end = i;
|
||
while i < s.len() && s[i].is_ascii_digit() {
|
||
i += 1;
|
||
}
|
||
let count = if i - end > 0 {
|
||
let count = std::str::from_utf8(&s[end..i]).unwrap().parse().unwrap();
|
||
count
|
||
} else {
|
||
1
|
||
};
|
||
*s = &s[i..];
|
||
(name, count)
|
||
}
|
||
fn parse_subsequence(s: &mut &[u8], output: &mut Molecule) -> Result<(), ParseError> {
|
||
let opening = s[0];
|
||
*s = &s[1..];
|
||
let seq_begin = output.len();
|
||
parse_sequence(s, output)?;
|
||
let seq_end = output.len();
|
||
let mut i = 1;
|
||
while i < s.len() && s[i].is_ascii_digit() {
|
||
i += 1;
|
||
}
|
||
let count = if i > 1 {
|
||
let count = std::str::from_utf8(&s[1..i]).unwrap().parse().unwrap();
|
||
// dbg!(&count);
|
||
count
|
||
} else {
|
||
1
|
||
};
|
||
if i > s.len() {
|
||
return Err(ParseError::ParensMismatch);
|
||
}
|
||
if opening == b'(' && s[0] != b')' {
|
||
return Err(ParseError::ParensMismatch);
|
||
}
|
||
if opening == b'[' && s[0] != b']' {
|
||
return Err(ParseError::ParensMismatch);
|
||
}
|
||
if opening == b'{' && s[0] != b'}' {
|
||
return Err(ParseError::ParensMismatch);
|
||
}
|
||
*s = &s[i..];
|
||
for i in seq_begin..seq_end {
|
||
output[i].1 *= count;
|
||
}
|
||
Ok(())
|
||
}
|
||
fn parse_sequence(s: &mut &[u8], output: &mut Molecule) -> Result<(), ParseError> {
|
||
loop {
|
||
if s.is_empty() {
|
||
break;
|
||
}
|
||
let peek = s[0];
|
||
dbg!(peek.clone() as char);
|
||
if peek.is_ascii_uppercase() {
|
||
let atom = atom(s);
|
||
output.push(atom)
|
||
} else if peek.is_ascii_lowercase() {
|
||
return Err(ParseError::InvalidName);
|
||
} else if matches!(peek, b'(' | b'[' | b'{') {
|
||
parse_subsequence(s, output)?
|
||
} else {
|
||
break;
|
||
}
|
||
}
|
||
Ok(())
|
||
}
|
||
pub fn parse_molecule(s: &str) -> Result<Molecule, ParseError> {
|
||
let mut s = s.as_bytes();
|
||
// dbg!(&s);
|
||
let mut molecules = vec![];
|
||
parse_sequence(&mut s, &mut molecules)?;
|
||
let mut molecule_map = HashMap::new();
|
||
for (name, count) in molecules {
|
||
*molecule_map.entry(name).or_insert(0) += count;
|
||
}
|
||
dbg!(&molecule_map);
|
||
Ok(molecule_map.into_iter().collect())
|
||
}
|
||
pub fn run() {
|
||
parse_molecule("H2O");
|
||
parse_molecule("Ca(OH)2");
|
||
parse_molecule("CaO");
|
||
}
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::{parse_molecule, Molecule};
|
||
macro_rules! assert_parse {
|
||
($formula:expr, $expected:expr, $name:ident) => {
|
||
#[test]
|
||
fn $name() {
|
||
super::assert_parse($formula, &$expected, "");
|
||
}
|
||
};
|
||
}
|
||
mod molecules {
|
||
assert_parse!("H", [("H", 1)], hydrogen);
|
||
assert_parse!("O2", [("O", 2)], oxygen);
|
||
assert_parse!("H2O", [("H", 2), ("O", 1)], water);
|
||
assert_parse!(
|
||
"Mg(OH)2",
|
||
[("Mg", 1), ("O", 2), ("H", 2)],
|
||
magnesium_hydroxide
|
||
);
|
||
assert_parse!(
|
||
"K4[ON(SO3)2]2",
|
||
[("K", 4), ("O", 14), ("N", 2), ("S", 4)],
|
||
fremys_salt
|
||
);
|
||
}
|
||
#[test]
|
||
fn errors() {
|
||
assert_fail("pie", "Not a valid molecule");
|
||
assert_fail("Mg(OH", "Mismatched parenthesis");
|
||
assert_fail("Mg(OH}2", "Mismatched parenthesis");
|
||
}
|
||
fn assert_fail(formula: &str, msg: &str) {
|
||
let result = parse_molecule(formula);
|
||
assert!(
|
||
result.is_err(),
|
||
"expected {} {:?} to fail, got {:?}",
|
||
msg,
|
||
formula,
|
||
result.unwrap()
|
||
);
|
||
}
|
||
fn assert_parse(formula: &str, expected: &[(&str, usize)], _mst: &str) {
|
||
let mut expected = expected
|
||
.into_iter()
|
||
.map(|&(name, usize)| (name.to_owned(), usize))
|
||
.collect::<Molecule>();
|
||
let result = parse_molecule(formula);
|
||
assert!(
|
||
result.is_ok(),
|
||
"expected {:?} to pass, got {:?}",
|
||
formula,
|
||
result
|
||
);
|
||
let mut actual = result.unwrap();
|
||
actual.sort();
|
||
expected.sort();
|
||
assert_eq!(actual, expected);
|
||
}
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-54-encode-and-decode-base64"><a class="header" href="#kata-54-encode-and-decode-base64">Kata 54 (encode and decode base64)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>/**
|
||
* encode and decode base64
|
||
*/
|
||
#[allow(dead_code)]
|
||
#[allow(unused)]
|
||
#[allow(non_snake_case)]
|
||
pub mod base64 {
|
||
use std::os::unix::prelude::OsStrExt;
|
||
use openssl::base64;
|
||
pub fn encode(src: &str) -> String {
|
||
base64::encode_block(src.as_bytes())
|
||
}
|
||
pub fn decode(s: &str) -> String {
|
||
let decode_result = base64::decode_block(s);
|
||
String::from_utf8(decode_result.unwrap()).clone().unwrap()
|
||
}
|
||
pub fn run() {
|
||
let encode_result = encode("base64");
|
||
println!("{:?}", encode_result); //"YmFzZTY0"
|
||
let decode_result = decode(&encode_result);
|
||
println!("{:?}", decode_result); //"base64"
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-55-count-of-positives--sum-of-negatives"><a class="header" href="#kata-55-count-of-positives--sum-of-negatives">Kata 55 (Count of positives / sum of negatives)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>/**
|
||
*Count of positives / sum of negatives
|
||
*https://www.codewars.com/kata/576bb71bbbcf0951d5000044/train/rust?collection=shi-yong-de-you-yi-si-de-ti
|
||
*/
|
||
#[allow(dead_code)]
|
||
#[allow(unused)]
|
||
#[allow(non_snake_case)]
|
||
pub mod count_positives_sum_negative {
|
||
pub fn count_positives_sum_negatives(input: Vec<i32>) -> Vec<i32> {
|
||
let mut count = 0;
|
||
let mut sum = 0;
|
||
for item in input.iter() {
|
||
if item > &0 {
|
||
count += 1;
|
||
} else {
|
||
sum += item;
|
||
}
|
||
}
|
||
if count > 0 {
|
||
vec![count, sum]
|
||
} else {
|
||
vec![]
|
||
}
|
||
}
|
||
#[test]
|
||
fn returns_expected() {
|
||
let test_data1 = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15];
|
||
let expected1 = vec![10, -65];
|
||
assert_eq!(count_positives_sum_negatives(test_data1), expected1);
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-56-encode-and-decode-to-aes-加密解密"><a class="header" href="#kata-56-encode-and-decode-to-aes-加密解密">Kata 56 (encode and decode to AES 加密解密)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>#[allow(dead_code)]
|
||
#[allow(unused)]
|
||
#[allow(non_snake_case)]
|
||
pub mod to_aes {
|
||
pub fn run() {
|
||
use libaes::Cipher;
|
||
let arguments: Vec<String> = std::env::args().collect();
|
||
// println!("{:?}", arguments);
|
||
if arguments[1] == "--text_encode" || arguments[1] == "-TE" {
|
||
let my_key = b"dnropsdnropsdnro"; // key is 16 bytes, i.e. 128-bit
|
||
let plaintext = arguments[2].as_bytes();
|
||
let iv = b"dnropsdnropsdnro";
|
||
// Create a new 128-bit cipher
|
||
let cipher = Cipher::new_128(my_key);
|
||
// Encryption
|
||
let encrypted = cipher.cbc_encrypt(iv, plaintext);
|
||
fn vec_to_string(v: Vec<u8>) -> String {
|
||
let mut re = String::new();
|
||
for item in v.iter() {
|
||
re.push(*item as char);
|
||
}
|
||
re
|
||
}
|
||
println!("{:?}", vec_to_string(encrypted.to_vec()));
|
||
// Decryption
|
||
let decrypted = cipher.cbc_decrypt(iv, &encrypted[..]);
|
||
} else if arguments[1] == "--text_decode" || arguments[1] == "-TD" {
|
||
let my_key = b"dnropsdnropsdnro"; // key is 16 bytes, i.e. 128-bit
|
||
let plaintext = arguments[2].as_bytes();
|
||
let iv = b"dnropsdnropsdnro";
|
||
// Create a new 128-bit cipher
|
||
let cipher = Cipher::new_128(my_key);
|
||
// Encryption
|
||
let encrypted = cipher.cbc_encrypt(iv, plaintext);
|
||
fn vec_to_string(v: Vec<u8>) -> String {
|
||
let mut re = String::new();
|
||
for item in v.iter() {
|
||
re.push(*item as char);
|
||
}
|
||
re
|
||
}
|
||
// Decryption
|
||
let decrypted = cipher.cbc_decrypt(iv, &arguments[2].as_bytes()[..]);
|
||
println!("{:?}", String::from_utf8(decrypted.to_vec())); //Ok("Alen_Andry")
|
||
} else if arguments[1] == "--binary_encode" || arguments[1] == "-BE" {
|
||
use std::fs::File;
|
||
use std::io::prelude::*;
|
||
use std::io::BufReader;
|
||
let my_key = b"dnropsdnropsdnro"; // key is 16 bytes, i.e. 128-bit
|
||
let mut file = File::open(&arguments[2]).unwrap();
|
||
// let mut buf_reader = BufReader::new(file);
|
||
let mut file_copy = file.try_clone().unwrap();
|
||
let mut contents = vec![];
|
||
file_copy.read_to_end(&mut contents);
|
||
// let plaintext = arguments[2].as_bytes();
|
||
let plaintext = contents.clone();
|
||
let iv = b"dnropsdnropsdnro";
|
||
// Create a new 128-bit cipher
|
||
let cipher = Cipher::new_128(my_key);
|
||
// Encryptions
|
||
let encrypted = cipher.cbc_encrypt(iv, &plaintext);
|
||
fn vec_to_string(v: Vec<u8>) -> String {
|
||
let mut re = String::new();
|
||
for item in v.iter() {
|
||
re.push(*item as char);
|
||
}
|
||
re
|
||
}
|
||
let mut f = File::create(&arguments[3]).unwrap();
|
||
f.write_all(&encrypted);
|
||
// Decryption
|
||
let decrypted = cipher.cbc_decrypt(iv, &encrypted[..]);
|
||
} else if arguments[1] == "--binary_decode" || arguments[1] == "-BD" {
|
||
use std::fs::File;
|
||
use std::io::prelude::*;
|
||
use std::io::BufReader;
|
||
let my_key = b"dnropsdnropsdnro"; // key is 16 bytes, i.e. 128-bit
|
||
let mut file = File::open(&arguments[2]).unwrap();
|
||
// let mut buf_reader = BufReader::new(file);
|
||
let mut file_copy = file.try_clone().unwrap();
|
||
let mut contents = vec![];
|
||
file_copy.read_to_end(&mut contents);
|
||
// let plaintext = arguments[2].as_bytes();
|
||
let plaintext = contents.clone();
|
||
let iv = b"dnropsdnropsdnro";
|
||
// Create a new 128-bit cipher
|
||
let cipher = Cipher::new_128(my_key);
|
||
// Encryptions
|
||
let encrypted = cipher.cbc_encrypt(iv, &plaintext);
|
||
fn vec_to_string(v: Vec<u8>) -> String {
|
||
let mut re = String::new();
|
||
for item in v.iter() {
|
||
re.push(*item as char);
|
||
}
|
||
re
|
||
}
|
||
// Decryption
|
||
let decrypted = cipher.cbc_decrypt(iv, &encrypted[..]);
|
||
let mut f1 = File::create(&arguments[3]).unwrap();
|
||
f1.write_all(&decrypted);
|
||
}
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-57-输出vec的所有不同顺序的子集"><a class="header" href="#kata-57-输出vec的所有不同顺序的子集">Kata 57 (输出vec的所有不同顺序的子集)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>#[allow(dead_code)]
|
||
#[allow(unused)]
|
||
#[allow(non_snake_case)]
|
||
pub mod premutaitions {
|
||
pub fn run() {
|
||
use itertools::Itertools;
|
||
use std::borrow::Borrow;
|
||
use std::cell::{RefCell, RefMut};
|
||
//输出vec的所有不同顺序的子集
|
||
let mut vec = Box::new(RefCell::new(vec![1, 2, 3]));
|
||
let vec_len = vec.as_mut().get_mut().len();
|
||
let mut re = vec![];
|
||
for i in 1..vec_len + 1 {
|
||
let vec_mut: &mut Vec<i64> = vec.as_mut().get_mut();
|
||
let mut new_vec = vec_mut.to_owned();
|
||
let all_permumations = new_vec.into_iter().permutations(i).collect::<Vec<_>>();
|
||
re.push(all_permumations);
|
||
}
|
||
println!("{:?}", re);
|
||
//[[[1], [2], [3]], [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]], [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]]
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-58-itertools-常用的function"><a class="header" href="#kata-58-itertools-常用的function">Kata 58 (itertools 常用的function)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>#[allow(dead_code)]
|
||
#[allow(unused)]
|
||
#[allow(non_snake_case)]
|
||
pub mod use_itertools {
|
||
use itertools::*;
|
||
use std::cell::{RefCell, RefMut};
|
||
use std::collections::HashMap;
|
||
pub fn run() {
|
||
{
|
||
//chain_vec 连接vec
|
||
let chain_vec = chain(&[1, 2, 3], &[4, 6]).map(|x| *x).collect::<Vec<i32>>();
|
||
eprintln!("{:?}", chain_vec);
|
||
//enumerate
|
||
for (index, item) in enumerate(&chain_vec) {
|
||
eprintln!("index:{}item:{}", index, item);
|
||
}
|
||
}
|
||
{
|
||
// find max min
|
||
let max_f32 = fold(&[1., 2., 3.], 0., |a, &b| f32::max(a, b));
|
||
let min_f32 = fold(&[1., 2., 3.], 0., |a, &b| f32::min(a, b));
|
||
eprintln!("{:?}", max_f32);
|
||
eprintln!("{:?}", min_f32);
|
||
}
|
||
{
|
||
//每一个位置后插入 另一个vec的元素
|
||
let it1 = vec![1, 2, 3]
|
||
.into_iter()
|
||
.interleave(vec![10, 20, 30])
|
||
.map(|x| x)
|
||
.collect::<Vec<i32>>();
|
||
eprintln!("{:?}", it1); //[1, 10, 2, 20, 3, 30]
|
||
}
|
||
{
|
||
//每两个一起 存到vec![(1, 2), (1, 3), (1, 4)]
|
||
let pit = vec![1, 2, 3, 4, 5, 6]
|
||
.into_iter()
|
||
.batching(|it| match it.next() {
|
||
None => None,
|
||
Some(x) => match it.next() {
|
||
None => None,
|
||
Some(y) => Some((x, y)),
|
||
},
|
||
})
|
||
.map(|x| x)
|
||
.collect::<Vec<(i32, i32)>>();
|
||
eprintln!("{:?}", pit); //[(0, 1), (2, 3), (4, 5), (6, 7)]
|
||
}
|
||
{
|
||
//根据条件 分类vec
|
||
let data1 = vec![1, 3, -2, -2, 1, 0, 1, 2];
|
||
let mut data_grouped = Vec::new();
|
||
for (key, group) in &data1.into_iter().group_by(|elt| *elt >= 0) {
|
||
data_grouped.push((key, group.collect::<Vec<_>>()));
|
||
}
|
||
eprintln!("{:?}", data_grouped); //[(true, [1, 3]), (false, [-2, -2]), (true, [1, 0, 1, 2])]
|
||
}
|
||
{
|
||
//每2个一起 存到vec 分别sum
|
||
let data2 = vec![2, 3, 5, 6, -2, 0];
|
||
let mut chunk_data = vec![];
|
||
for chunk in &data2.into_iter().chunks(2) {
|
||
let mut ch = Box::new(RefCell::new(chunk));
|
||
chunk_data.push((
|
||
ch.as_mut().get_mut().map(|x| x).collect::<Vec<_>>(),
|
||
ch.as_mut().get_mut().sum::<i32>(),
|
||
));
|
||
}
|
||
eprintln!("{:?}", chunk_data); //[([2, 3], 0), ([5, 6], 0), ([-2, 0], 0)]
|
||
}
|
||
{
|
||
//每3个一起 存到tuple_vec
|
||
let it1 = vec![1, 2, 3, 4].into_iter().tuple_windows::<(_, _, _)>();
|
||
itertools::assert_equal(it1, vec![(1, 2, 3), (2, 3, 4)]);
|
||
let it2 = (1..7).tuples::<(_, _, _)>();
|
||
itertools::assert_equal(it2, vec![(1, 2, 3), (4, 5, 6)]);
|
||
}
|
||
{
|
||
// 输出从小到大 第五个元素
|
||
let numbers = vec![1, 5, 3, 0, 1, 2];
|
||
let five_smallest = numbers.into_iter().k_smallest(5);
|
||
eprintln!("{:?}", five_smallest);
|
||
}
|
||
{
|
||
//Vec<(i32, i32)> to HashMap<i32, Vec<i32>>
|
||
let data1 = vec![(0, 10), (2, 12), (3, 13), (0, 20), (3, 33), (2, 42)];
|
||
let lookup1 = data1.into_iter().into_group_map();
|
||
eprintln!("{:?}", lookup1);
|
||
}
|
||
{
|
||
// Vec<(i32, i32)> to HashMap<i32, Vec<i32>> 根据第一个元素分类
|
||
let data2 = vec![(0, 10), (2, 12), (3, 13), (0, 20), (3, 33), (2, 42)];
|
||
let lookup2: HashMap<u32, Vec<(u32, u32)>> =
|
||
data2.clone().into_iter().into_group_map_by(|a| a.0);
|
||
eprintln!("{:?}", lookup2);
|
||
}
|
||
{
|
||
//return 最大元素的位置
|
||
let a = [-3_i32, 0, 1, 5, -10];
|
||
assert_eq!(a.iter().position_max_by(|x, y| x.cmp(y)), Some(3));
|
||
}
|
||
{
|
||
//return 最小元素位置
|
||
let a = [-3, 0, 1, 5, -10];
|
||
assert_eq!(a.iter().position_min(), Some(4));
|
||
}
|
||
{
|
||
//输出vec的所有子集
|
||
let sets = vec![1, 2].into_iter().powerset().collect::<Vec<_>>();
|
||
eprintln!("{:?}", sets); //[[], [1], [2], [1, 2]]
|
||
}
|
||
{
|
||
//找元素为位置
|
||
let data = vec![1, 2, 3, 3, 4, 6, 7, 9];
|
||
let positions = data
|
||
.iter()
|
||
.positions(|v| v % 2 == 0)
|
||
.map(|x| x)
|
||
.collect::<Vec<_>>();
|
||
eprintln!("{:?}", positions);
|
||
}
|
||
{
|
||
//drop some item 前后删除
|
||
let init_front = vec![0, 3, 6, 9]
|
||
.into_iter()
|
||
.dropping(1)
|
||
.map(|x| x)
|
||
.collect::<Vec<_>>();
|
||
eprintln!("{:?}", init_front); //[3, 6, 9]
|
||
let init_back = vec![0, 3, 6, 9]
|
||
.into_iter()
|
||
.dropping_back(1)
|
||
.map(|x| x)
|
||
.collect::<Vec<_>>();
|
||
eprintln!("{:?}", init_back); //[0, 3, 6]
|
||
}
|
||
{
|
||
//求和 0-10
|
||
let sum1 = (0..11).fold(0, |acc, y| acc + y);
|
||
let sum2 = vec![1, 15, 10].into_iter().fold(0, |acc, y| acc + y);
|
||
eprintln!("{:?},{:?}", sum1, sum2);
|
||
}
|
||
{
|
||
//更新vec内部元素
|
||
let input = vec![vec![1], vec![3, 2, 1]];
|
||
let it = input
|
||
.into_iter()
|
||
.update(|mut v| v.push(0))
|
||
.map(|x| x)
|
||
.collect::<Vec<_>>();
|
||
eprintln!("{:?}", it); // vec![vec![1, 0], vec![3, 2, 1, 0]]
|
||
let vec = vec![1, 5, 6, 8];
|
||
let new_vec = vec
|
||
.into_iter()
|
||
.update(|mut v| {
|
||
let mut vv = *v;
|
||
vv = vv * 10;
|
||
*v = vv;
|
||
})
|
||
.map(|x| x)
|
||
.collect::<Vec<_>>();
|
||
eprintln!("{:?}", new_vec); //[10, 50, 60, 80]
|
||
}
|
||
{
|
||
//删除重复元素
|
||
let data1 = vec![10, 20, 30, 20, 40, 10, 50];
|
||
assert_equal(data1.into_iter().unique(), vec![10, 20, 30, 40, 50]);
|
||
let data2 = vec!["a", "bb", "aa", "c", "ccc"];
|
||
assert_equal(
|
||
data2.into_iter().unique_by(|s| s.len()),
|
||
vec!["a", "bb", "ccc"],
|
||
);
|
||
}
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-59-snail-sort-矩阵蛇形遍历-iter-reverse"><a class="header" href="#kata-59-snail-sort-矩阵蛇形遍历-iter-reverse">Kata 59 (snail sort 矩阵蛇形遍历 .iter() reverse)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>/**
|
||
* snail sort 矩阵蛇形遍历 .iter() reverse
|
||
* https://www.codewars.com/kata/521c2db8ddc89b9b7a0000c1/train/rust
|
||
*/
|
||
#[allow(dead_code)]
|
||
#[allow(unused)]
|
||
#[allow(non_snake_case)]
|
||
pub mod snail_sort {
|
||
pub fn get_matrix_edge(matrix: &[Vec<i32>]) -> Vec<i32> {
|
||
// enjoy
|
||
let mut re: Vec<i32> = vec![];
|
||
let mut left = vec![];
|
||
for (row_index, item_vec) in matrix.iter().enumerate() {
|
||
if row_index == 0 {
|
||
for (culmn_index, item_num) in item_vec.iter().enumerate() {
|
||
re.push(*item_num);
|
||
}
|
||
}
|
||
if row_index != 0 {
|
||
for (culmn_index, item_num) in item_vec.iter().enumerate() {
|
||
if culmn_index == item_vec.len() - 1 {
|
||
re.push(*item_num);
|
||
}
|
||
}
|
||
}
|
||
if row_index == matrix.len() - 1 {
|
||
let mut bottom = vec![];
|
||
for (culmn_index, item_num) in item_vec.iter().enumerate() {
|
||
if culmn_index != item_vec.len() - 1 {
|
||
bottom.push(*item_num);
|
||
}
|
||
}
|
||
bottom.reverse();
|
||
for bb in &bottom {
|
||
re.push(*bb);
|
||
}
|
||
}
|
||
for (culmn_index, item_num) in item_vec.iter().enumerate() {
|
||
if culmn_index == 0 {
|
||
left.push(*item_num);
|
||
}
|
||
}
|
||
}
|
||
left.reverse();
|
||
if left.len() > 2 {
|
||
left.remove(0);
|
||
let len = left.len();
|
||
left.remove(len - 1);
|
||
for ll in &left {
|
||
re.push(*ll);
|
||
}
|
||
}
|
||
re
|
||
}
|
||
pub fn split_matrix(matrix: &[Vec<i32>], start_index: (usize, usize)) -> Vec<Vec<i32>> {
|
||
let mut re = Vec::new();
|
||
let mut end_index: (usize, usize) = (0, 0);
|
||
if matrix.len() > 2 {
|
||
end_index = (matrix.len() - 2, matrix.len() - 2);
|
||
for (row_index, item_vec) in matrix.iter().enumerate() {
|
||
let mut new_row = vec![];
|
||
for (culmn_index, item_num) in item_vec.iter().enumerate() {
|
||
if culmn_index >= start_index.1
|
||
&& culmn_index <= end_index.1
|
||
&& row_index >= start_index.0
|
||
&& row_index <= end_index.0
|
||
{
|
||
new_row.push(*item_num);
|
||
}
|
||
}
|
||
if new_row.len() > 0 {
|
||
re.push(new_row);
|
||
}
|
||
}
|
||
}
|
||
re
|
||
}
|
||
pub fn snail(matrix: &[Vec<i32>]) -> Vec<i32> {
|
||
let mut re = Vec::new();
|
||
re = get_matrix_edge(matrix);
|
||
let mut new_matrix = split_matrix(matrix, (1, 1));
|
||
let re1 = get_matrix_edge(&new_matrix);
|
||
for item in re1.iter() {
|
||
re.push(*item);
|
||
}
|
||
while new_matrix.len() >= 1 {
|
||
new_matrix = split_matrix(&new_matrix, (1, 1));
|
||
let re1 = get_matrix_edge(&new_matrix);
|
||
for item in re1.iter() {
|
||
re.push(*item);
|
||
}
|
||
}
|
||
re
|
||
}
|
||
//other solution
|
||
fn snail1(matrix: &[Vec<i32>]) -> Vec<i32> {
|
||
let mut ret = Vec::new();
|
||
if matrix.len() == 0 {
|
||
return ret;
|
||
}
|
||
let mut width = matrix[0].len();
|
||
let mut height = matrix.len();
|
||
let mut cycle = 0;
|
||
while width > 0 && height > 0 {
|
||
for x in cycle..width {
|
||
ret.push(matrix[cycle][x]);
|
||
}
|
||
for y in cycle + 1..height {
|
||
ret.push(matrix[y][width - 1]);
|
||
}
|
||
for x in (cycle..width - 1).rev() {
|
||
ret.push(matrix[height - 1][x]);
|
||
}
|
||
for y in (cycle + 1..height - 1).rev() {
|
||
ret.push(matrix[y][cycle]);
|
||
}
|
||
cycle += 1;
|
||
width -= 1;
|
||
height -= 1;
|
||
}
|
||
ret
|
||
}
|
||
pub fn run() {
|
||
let square1 = &[vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];
|
||
let square2 = &[
|
||
vec![1, 2, 3, 4],
|
||
vec![5, 6, 7, 8],
|
||
vec![9, 10, 11, 12],
|
||
vec![13, 14, 15, 16],
|
||
];
|
||
let square3 = &[
|
||
vec![543, 4, 207, 610, 748, 71, 813],
|
||
vec![100, 61, 987, 541, 429, 798, 277],
|
||
vec![63, 766, 838, 430, 271, 884, 274],
|
||
vec![640, 765, 403, 676, 56, 233, 522],
|
||
vec![335, 516, 590, 908, 150, 588, 221],
|
||
vec![401, 522, 813, 89, 696, 173, 887],
|
||
vec![844, 266, 636, 500, 493, 531, 334],
|
||
];
|
||
println!("{:?}", snail1(square1));
|
||
println!("{:?}", snail(square2));
|
||
println!("{:?}", snail(square3));
|
||
}
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
#[test]
|
||
fn sample_test1() {
|
||
let square = &[vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];
|
||
let expected = vec![1, 2, 3, 6, 9, 8, 7, 4, 5];
|
||
assert_eq!(snail(square), expected);
|
||
}
|
||
#[test]
|
||
fn sample_test2() {
|
||
let square = &[vec![1, 2, 3], vec![8, 9, 4], vec![7, 6, 5]];
|
||
let expected = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
|
||
assert_eq!(snail(square), expected);
|
||
}
|
||
#[test]
|
||
fn sample_test3() {
|
||
let square: &[Vec<i32>; 1] = &[Vec::new()];
|
||
let expected = Vec::new();
|
||
assert_eq!(snail(square), expected, "Failed with empty input");
|
||
}
|
||
#[test]
|
||
fn sample_test4() {
|
||
let square = &[vec![1]];
|
||
let expected = vec![1];
|
||
assert_eq!(snail(square), expected);
|
||
}
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-60-use-scrcpy-connect-phone"><a class="header" href="#kata-60-use-scrcpy-connect-phone">Kata 60 (Use scrcpy connect phone)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>#[allow(dead_code)]
|
||
#[allow(unused)]
|
||
#[allow(non_snake_case)]
|
||
pub mod connect_phone {
|
||
use std::process::Command;
|
||
pub fn detect_phone() -> Vec<String> {
|
||
let result = Command::new("adb")
|
||
.arg("devices")
|
||
.output()
|
||
.expect("command failed to start");
|
||
let str_result_to_vec = std::str::from_utf8(&result.stdout)
|
||
.unwrap()
|
||
.split("\n")
|
||
.filter(|s| !s.is_empty())
|
||
.collect::<Vec<_>>()
|
||
.iter()
|
||
.map(|s| s.to_string())
|
||
.collect();
|
||
str_result_to_vec
|
||
}
|
||
pub fn get_phone_ip() -> String {
|
||
let result = Command::new("adb")
|
||
.arg("shell")
|
||
.arg("ip")
|
||
.arg("a")
|
||
.output()
|
||
.expect("command failed to start");
|
||
let str_result_to_vec: Vec<String> = std::str::from_utf8(&result.stdout)
|
||
.unwrap()
|
||
.split("\n")
|
||
.filter(|s| !s.is_empty())
|
||
.collect::<Vec<_>>()
|
||
.iter()
|
||
.map(|s| s.to_string())
|
||
.collect();
|
||
let mut re = String::from("phone is not connected or more than one device ");
|
||
for item in str_result_to_vec {
|
||
if item.contains("192.") {
|
||
re = item.trim().to_string().split("/").collect::<Vec<_>>()[0]
|
||
.to_string()
|
||
.split(" ")
|
||
.collect::<Vec<_>>()[1]
|
||
.to_string();
|
||
}
|
||
}
|
||
re.to_string()
|
||
}
|
||
pub fn start_tcpip(port: &str) -> String {
|
||
let result = Command::new("adb")
|
||
.arg("tcpip")
|
||
.arg("5555")
|
||
.output()
|
||
.expect("command failed to start");
|
||
let str_result_to_vec: Vec<String> = std::str::from_utf8(&result.stdout)
|
||
.unwrap()
|
||
.split("\n")
|
||
.filter(|s| !s.is_empty())
|
||
.collect::<Vec<_>>()
|
||
.iter()
|
||
.map(|s| s.to_string())
|
||
.collect();
|
||
let mut re = format!("can't start tcpip at {}", &port);
|
||
for item in str_result_to_vec {
|
||
if item.contains(&port) {
|
||
re = item;
|
||
}
|
||
}
|
||
re
|
||
}
|
||
pub fn connect_phone(ip_address: &str, port: &str) -> String {
|
||
let address = format!("{}:{}", ip_address, port);
|
||
let result = Command::new("adb")
|
||
.arg("connect")
|
||
.arg(&address)
|
||
.output()
|
||
.expect("command failed to start");
|
||
let str_result_to_vec: Vec<String> = std::str::from_utf8(&result.stdout)
|
||
.unwrap()
|
||
.split("\n")
|
||
.filter(|s| !s.is_empty())
|
||
.collect::<Vec<_>>()
|
||
.iter()
|
||
.map(|s| s.to_string())
|
||
.collect();
|
||
let mut re = format!("can't connect to :: {}", &address);
|
||
for item in str_result_to_vec {
|
||
if item.contains("connected") && !item.contains("failed") && !item.contains("can't") {
|
||
re = item;
|
||
re.push_str(" :: ready to run scrcpy");
|
||
}
|
||
}
|
||
re
|
||
}
|
||
pub fn run_srcpy() -> String {
|
||
use std::thread;
|
||
use std::time::{Duration, Instant};
|
||
thread::sleep(Duration::from_secs(3));
|
||
let result = Command::new("scrcpy")
|
||
.spawn()
|
||
.expect("can't connect open scrcpy");
|
||
let mut re = format!("opening scrcpy");
|
||
re
|
||
}
|
||
pub fn run() {
|
||
let port = "5555";
|
||
let ip_address = get_phone_ip();
|
||
println!("{:?}", detect_phone());
|
||
println!("{:?}", get_phone_ip());
|
||
println!("{:?}", start_tcpip(&port));
|
||
println!("{:?}", connect_phone(&ip_address, &port));
|
||
println!("{:?}", run_srcpy());
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-61-closest-and-smallest"><a class="header" href="#kata-61-closest-and-smallest">Kata 61 (Closest and Smallest)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>/**
|
||
* Closest and Smallest
|
||
* https://www.codewars.com/kata/5868b2de442e3fb2bb000119/train/rust
|
||
*/
|
||
#[allow(dead_code)]
|
||
#[allow(unused)]
|
||
#[allow(non_snake_case)]
|
||
pub mod closest_and_smallest {
|
||
pub fn closest(s: &str) -> String {
|
||
let mut s_vec: Vec<i32> = s
|
||
.split(" ")
|
||
.filter(|s| !s.is_empty())
|
||
.collect::<Vec<_>>()
|
||
.iter()
|
||
.map(|s| s.parse::<i32>().unwrap())
|
||
.collect();
|
||
let mut s_weights: Vec<i32> = s
|
||
.split(" ")
|
||
.filter(|s| !s.is_empty())
|
||
.collect::<Vec<_>>()
|
||
.iter()
|
||
.map(|s| {
|
||
s.split("")
|
||
.filter(|s| !s.is_empty())
|
||
.collect::<Vec<_>>()
|
||
.iter()
|
||
.map(|s| s.parse::<i32>().unwrap())
|
||
.collect::<Vec<i32>>()
|
||
.iter()
|
||
.sum()
|
||
})
|
||
.collect();
|
||
let mut collect_weights = Vec::new();
|
||
for i in 0..s_weights.len() {
|
||
collect_weights.push((s_weights[i], s_vec[i]));
|
||
}
|
||
let mut new_collect_weights = collect_weights.clone();
|
||
new_collect_weights.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
|
||
fn find_closest(vec: &mut Vec<(i32, i32)>) -> (usize, usize, i32) {
|
||
let mut adjacen_weights: Vec<(usize, usize, i32)> = vec![];
|
||
for i in 0..vec.len() - 1 {
|
||
adjacen_weights.push((i, i + 1, vec[i + 1].0 - vec[i].0));
|
||
}
|
||
adjacen_weights.sort_by(|a, b| a.2.partial_cmp(&b.2).unwrap());
|
||
adjacen_weights[0]
|
||
}
|
||
let closest_index = find_closest(&mut new_collect_weights);
|
||
let mut re = Vec::new();
|
||
re.push(new_collect_weights[closest_index.0]);
|
||
re.push(new_collect_weights[closest_index.1]);
|
||
fn find_index(collect_weights: &mut Vec<(i32, i32)>, target: i32) -> usize {
|
||
let mut re = 0;
|
||
for i in 0..collect_weights.len() {
|
||
if collect_weights[i].1 == target {
|
||
re = i;
|
||
break;
|
||
}
|
||
}
|
||
re
|
||
}
|
||
let mut indexs = vec![];
|
||
indexs.push(find_index(&mut collect_weights, re[0].1));
|
||
collect_weights.reverse();
|
||
indexs.push(collect_weights.len() - 1 - find_index(&mut collect_weights, re[1].1));
|
||
let mut vec = vec![];
|
||
vec.push(vec![re[0].0, indexs[0] as i32, re[0].1]);
|
||
vec.push(vec![re[1].0, indexs[1] as i32, re[1].1]);
|
||
let mut result = String::from("[");
|
||
for item in vec.iter() {
|
||
result.push_str("(");
|
||
for item1 in item.iter() {
|
||
result.push_str(&format!("{:?},", item1));
|
||
}
|
||
result.push_str(")");
|
||
}
|
||
result.push_str(&format!("]"));
|
||
let re = result.replace(",)", ")");
|
||
return re;
|
||
}
|
||
//other solution
|
||
fn closest1(s: &str) -> String {
|
||
use itertools::Itertools;
|
||
fn weight(s: &str) -> u32 {
|
||
s.chars().map(|c| c.to_digit(10).unwrap()).sum()
|
||
}
|
||
let (_, a, b) = s
|
||
.trim()
|
||
.split_whitespace()
|
||
.enumerate()
|
||
.map(|(i, x)| (weight(x) as i64, i, x))
|
||
.sorted()
|
||
.tuple_windows()
|
||
.map(|(a, b)| ((a.0 - b.0).abs(), a, b))
|
||
.min()
|
||
.unwrap();
|
||
format!("[({},{},{})({},{},{})]", a.0, a.1, a.2, b.0, b.1, b.2)
|
||
}
|
||
pub fn run() {
|
||
let s = "643181 268 211507 849 144916 396 568036 222 79436 641 506082 948 385502 626 631751 560 488490 210 538675 520 271288 641 137916 265 723201";
|
||
let re = closest(s);
|
||
println!("{:?}", re);
|
||
let r = "[(0,6,0)(0,7,0)]";
|
||
assert_eq!(re, r.to_string());
|
||
}
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
fn testing(s: &str, exp: String) -> () {
|
||
let ans = closest(s);
|
||
assert_eq!(ans, exp, "Testing: {}", s);
|
||
}
|
||
#[test]
|
||
fn basic_tests() {
|
||
let mut s = "456899 50 11992 176 272293 163 389128 96 290193 85 52"; // [(13, 9, "85"), (14, 3, "176")]
|
||
testing(s, "[(13,9,85)(14,3,176)]".to_string());
|
||
s = "239382 162 254765 182 485944 134 468751 62 49780 108 54"; // "[[8, 5, 134], [8, 7, 62]]";
|
||
testing(s, "[(8,5,134)(8,7,62)]".to_string());
|
||
s = "241259 154 155206 194 180502 147 300751 200 406683 37 57";
|
||
let r = "[(10,1,154)(10,9,37)]";
|
||
testing(s, r.to_string());
|
||
}
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-62-解数独-nn的矩阵中每一行和列不能有重复的数字"><a class="header" href="#kata-62-解数独-nn的矩阵中每一行和列不能有重复的数字">Kata 62 (解数独 n*n的矩阵中每一行和列不能有重复的数字)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>#[allow(dead_code)]
|
||
#[allow(unused)]
|
||
#[allow(non_snake_case)]
|
||
pub mod sudoku_solver {
|
||
struct Solution;
|
||
impl Solution {
|
||
pub fn solve_sudoku(board: &mut Vec<Vec<char>>) {
|
||
let mut empty_position = vec![];
|
||
for i in 0..9 {
|
||
for j in 0..9 {
|
||
if board[i][j] == '.' {
|
||
empty_position.push((i, j));
|
||
board[i][j] = '0';
|
||
}
|
||
}
|
||
}
|
||
let position_len = empty_position.len();
|
||
let mut loop_index = 0;
|
||
while loop_index < position_len {
|
||
let (x, y) = empty_position[loop_index];
|
||
if board[x][y] < '9' {
|
||
board[x][y] = std::char::from_u32((board[x][y] as u32) + 1).unwrap();
|
||
} else {
|
||
board[x][y] = '0';
|
||
loop_index -= 1;
|
||
continue;
|
||
}
|
||
if Solution::invalid(board, x, y) {
|
||
continue;
|
||
}
|
||
loop_index += 1;
|
||
}
|
||
}
|
||
pub fn invalid(board: &Vec<Vec<char>>, x: usize, y: usize) -> bool {
|
||
use std::collections::HashSet;
|
||
let mut contain_table = HashSet::new();
|
||
// validate line
|
||
for i in 0..9 {
|
||
let x1 = board[x][i];
|
||
if x1 != '0' {
|
||
if contain_table.contains(&x1) {
|
||
return true;
|
||
}
|
||
contain_table.insert(x1);
|
||
}
|
||
}
|
||
contain_table.clear();
|
||
// validate column
|
||
for i in 0..9 {
|
||
let x2 = board[i][y];
|
||
if x2 != '0' {
|
||
if contain_table.contains(&x2) {
|
||
return true;
|
||
}
|
||
contain_table.insert(x2);
|
||
}
|
||
}
|
||
contain_table.clear();
|
||
// validate box
|
||
let i1 = x / 3;
|
||
let i2 = y / 3;
|
||
for i in 0..3 {
|
||
for j in 0..3 {
|
||
let x3 = board[i1 * 3 + i][i2 * 3 + j];
|
||
if x3 != '0' {
|
||
if contain_table.contains(&x3) {
|
||
return true;
|
||
}
|
||
contain_table.insert(x3);
|
||
}
|
||
}
|
||
}
|
||
contain_table.clear();
|
||
false
|
||
}
|
||
}
|
||
#[cfg(test)]
|
||
mod test {
|
||
use super::*;
|
||
#[test]
|
||
fn test() {
|
||
let mut sudoku = vec![
|
||
vec!['5', '3', '.', '.', '7', '.', '.', '.', '.'],
|
||
vec!['6', '.', '.', '1', '9', '5', '.', '.', '.'],
|
||
vec!['.', '9', '8', '.', '.', '.', '.', '6', '.'],
|
||
vec!['8', '.', '.', '.', '6', '.', '.', '.', '3'],
|
||
vec!['4', '.', '.', '8', '.', '3', '.', '.', '1'],
|
||
vec!['7', '.', '.', '.', '2', '.', '.', '.', '6'],
|
||
vec!['.', '6', '.', '.', '.', '.', '2', '8', '.'],
|
||
vec!['.', '.', '.', '4', '1', '9', '.', '.', '5'],
|
||
vec!['.', '.', '.', '.', '8', '.', '.', '7', '9'],
|
||
];
|
||
Solution::solve_sudoku(&mut sudoku);
|
||
let mut expected_solution = vec![
|
||
vec!['5', '3', '4', '6', '7', '8', '9', '1', '2'],
|
||
vec!['6', '7', '2', '1', '9', '5', '3', '4', '8'],
|
||
vec!['1', '9', '8', '3', '4', '2', '5', '6', '7'],
|
||
vec!['8', '5', '9', '7', '6', '1', '4', '2', '3'],
|
||
vec!['4', '2', '6', '8', '5', '3', '7', '9', '1'],
|
||
vec!['7', '1', '3', '9', '2', '4', '8', '5', '6'],
|
||
vec!['9', '6', '1', '5', '3', '7', '2', '8', '4'],
|
||
vec!['2', '8', '7', '4', '1', '9', '6', '3', '5'],
|
||
vec!['3', '4', '5', '2', '8', '6', '1', '7', '9'],
|
||
];
|
||
assert_eq!(expected_solution, sudoku);
|
||
}
|
||
#[test]
|
||
fn test_invalid_method() {
|
||
let mut expected_solution = vec![
|
||
vec!['5', '3', '4', '6', '7', '8', '9', '1', '2'],
|
||
vec!['6', '7', '2', '1', '9', '5', '3', '4', '8'],
|
||
vec!['1', '9', '8', '3', '4', '2', '5', '6', '7'],
|
||
vec!['8', '5', '9', '7', '6', '1', '4', '2', '3'],
|
||
vec!['4', '2', '6', '8', '5', '3', '7', '9', '1'],
|
||
vec!['7', '1', '3', '9', '2', '4', '8', '5', '6'],
|
||
vec!['9', '6', '1', '5', '3', '7', '2', '8', '4'],
|
||
vec!['2', '8', '7', '4', '1', '9', '6', '3', '5'],
|
||
vec!['3', '4', '5', '2', '8', '6', '1', '7', '9'],
|
||
];
|
||
for i in 0..9 {
|
||
for j in 0..9 {
|
||
assert_eq!(false, Solution::invalid(&expected_solution, i, j));
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-63-read-from-terminal-macroinput"><a class="header" href="#kata-63-read-from-terminal-macroinput">Kata 63 (Read from terminal macro,input!())</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>#[allow(unused_macros)]
|
||
macro_rules! input {
|
||
() => {{
|
||
let mut string = String::new();
|
||
std::io::stdin().read_line(&mut string).unwrap();
|
||
string = string.to_string().trim().to_owned();
|
||
string
|
||
}};
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-64parse-string-进制转换"><a class="header" href="#kata-64parse-string-进制转换">Kata 64(parse string 进制转换)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>/**
|
||
* pase string or decimal conversion
|
||
*/
|
||
#[allow(dead_code)]
|
||
#[allow(unused_variables)]
|
||
#[allow(unused)]
|
||
#[allow(non_snake_case)]
|
||
pub mod pase_string_decimal_conversion {
|
||
pub fn run() {
|
||
//Vec<String> to i64
|
||
let mut vec = vec![];
|
||
for i in 0..5 {
|
||
vec.push(format!("{}", i));
|
||
}
|
||
let vec_to_i64: i64 = vec.into_iter().collect::<String>().parse().unwrap();
|
||
assert_eq!(vec_to_i64, 1234);
|
||
// String to i64
|
||
let s = format!("444");
|
||
let s_i64 = s.parse::<i64>().unwrap();
|
||
assert_eq!(s_i64, 444);
|
||
//split_i64 to Vec<i64>
|
||
let split_i64 = format!("{}", 1234)
|
||
.chars()
|
||
.map(|x| i64::from(x.to_digit(10).unwrap()))
|
||
.rev()
|
||
.collect::<Vec<i64>>();
|
||
assert_eq!(split_i64, vec![4, 3, 2, 1]);
|
||
//char to i64
|
||
let c: char = '5';
|
||
let c_to_i64 = i64::from(c.to_digit(10).unwrap());
|
||
assert_eq!(c_to_i64, 5);
|
||
//&str to Vec<i64>
|
||
let s1: &str = "564";
|
||
let c_to_i64 = s1
|
||
.chars()
|
||
.map(|x| i64::from(x.to_digit(10).unwrap()))
|
||
.collect::<Vec<i64>>();
|
||
assert_eq!(c_to_i64, vec![5, 6, 4]);
|
||
//decimal conversion
|
||
/**- ``, which uses the `Display` trait
|
||
- `?`, which uses the `Debug` trait
|
||
- `e`, which uses the `LowerExp` trait
|
||
- `E`, which uses the `UpperExp` trait
|
||
- `o`, which uses the `Octal` trait
|
||
- `p`, which uses the `Pointer` trait
|
||
- `b`, which uses the `Binary` trait
|
||
- `x`, which uses the `LowerHex` trait
|
||
- `X`, which uses the `UpperHex` trait
|
||
*/
|
||
//十进制转化为其他进制
|
||
//十进制to二进制
|
||
let num = 454;
|
||
let biynary_num = format!("{:b}", num);
|
||
assert_eq!(biynary_num, format!("111000110"));
|
||
//十进制to八进制
|
||
let octonary_num = format!("{:o}", num);
|
||
assert_eq!(octonary_num, format!("706"));
|
||
//十进制to十六进制
|
||
let hexadecimal_num = format!("{:x}", num);
|
||
assert_eq!(hexadecimal_num, format!("1c6"));
|
||
//二进制转化为其他进制
|
||
//二进制to十进制
|
||
let num1 = "100";
|
||
fn binary_to_decimal(num: &str) -> String {
|
||
let mut sum = 0;
|
||
let mut vec = num
|
||
.chars()
|
||
.map(|x| i64::from(x.to_digit(10).unwrap()))
|
||
.collect::<Vec<i64>>();
|
||
for (index, item) in vec.iter().rev().enumerate() {
|
||
sum += i64::pow(2, index as u32) * item;
|
||
}
|
||
format!("{}", sum)
|
||
}
|
||
//二进制转十进制结果
|
||
let num_to_decimal = binary_to_decimal(num1);
|
||
assert_eq!(num_to_decimal, format!("4"));
|
||
//二进制to八进制,先把二进制转十进制再转八进制
|
||
let octonary_num = format!("{:o}", binary_to_decimal("1111").parse::<i64>().unwrap());
|
||
assert_eq!(octonary_num, format!("17"));
|
||
//二进制to十六进制,先把二进制转十进制再转十六进制
|
||
let hexadecimal_num = format!("{:x}", binary_to_decimal("1111").parse::<i64>().unwrap());
|
||
assert_eq!(hexadecimal_num, format!("f"));
|
||
//八进制转化为其他进制
|
||
//八进制to十进制
|
||
fn octonary_to_decimal(num: &str) -> String {
|
||
let mut sum = 0;
|
||
let mut vec = num
|
||
.chars()
|
||
.map(|x| i64::from(x.to_digit(10).unwrap()))
|
||
.collect::<Vec<i64>>();
|
||
for (index, item) in vec.iter().rev().enumerate() {
|
||
sum += i64::pow(8, index as u32) * item;
|
||
}
|
||
format!("{}", sum)
|
||
}
|
||
//八进制转十进制结果
|
||
let num_to_decimal = octonary_to_decimal("1111");
|
||
assert_eq!(num_to_decimal, format!("585"));
|
||
//八进制to二进制,先把八进制转十进制再转八进制
|
||
let octonary_num = format!("{:b}", octonary_to_decimal("1111").parse::<i64>().unwrap());
|
||
assert_eq!(octonary_num, format!("1001001001"));
|
||
//八进制to十六进制,先把八进制转十进制再转十六进制
|
||
let hexadecimal_num = format!("{:x}", octonary_to_decimal("1111").parse::<i64>().unwrap());
|
||
assert_eq!(hexadecimal_num, format!("249"));
|
||
//十六进制转化为其他进制
|
||
//十六进制to十进制
|
||
fn hexadecimal_to_decimal(num: &str) -> String {
|
||
let mut sum = 0;
|
||
let mut vec = num
|
||
.chars()
|
||
.map(|x| i64::from(x.to_digit(10).unwrap()))
|
||
.collect::<Vec<i64>>();
|
||
for (index, item) in vec.iter().rev().enumerate() {
|
||
sum += i64::pow(16, index as u32) * item;
|
||
}
|
||
format!("{}", sum)
|
||
}
|
||
//十六进制转十进制结果
|
||
let num_to_decimal = hexadecimal_to_decimal("1111");
|
||
assert_eq!(num_to_decimal, format!("4369"));
|
||
//十六进制to二进制,先把十六进制转十进制再转八进制
|
||
let octonary_num = format!(
|
||
"{:b}",
|
||
hexadecimal_to_decimal("1111").parse::<i64>().unwrap()
|
||
);
|
||
assert_eq!(octonary_num, format!("1000100010001"));
|
||
//十六进制to八进制,先把十六进制转十进制再转十六进制
|
||
let hexadecimal_num = format!(
|
||
"{:o}",
|
||
hexadecimal_to_decimal("1111").parse::<i64>().unwrap()
|
||
);
|
||
assert_eq!(hexadecimal_num, format!("10421"));
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-65-rust-闭包"><a class="header" href="#kata-65-rust-闭包">Kata 65 (rust 闭包)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust">fn main() {
|
||
//两个闭包共同分享一个值
|
||
use std::sync::Mutex;
|
||
let l = Box::leak(Box::new(Mutex::new(0.0)));
|
||
let add = || {
|
||
*l.lock().unwrap() += 1.0;
|
||
};
|
||
let min = || {
|
||
*l.lock().unwrap() -= 1.0;
|
||
};
|
||
for _ in 0..10 {
|
||
add();
|
||
min();
|
||
}
|
||
println!("{:?}", *l.lock().unwrap()); //0.0
|
||
}</code></pre></pre>
|
||
<h2 id="kata-66-rust-append-data-to-file"><a class="header" href="#kata-66-rust-append-data-to-file">Kata 66 (Rust append data to file)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>//fsio = "0.3.0" add to Cargo.toml
|
||
use fsio::{directory, file, path};
|
||
use std::fs::File;
|
||
use std::io::Write;
|
||
use std::path::Path;
|
||
use std::str;
|
||
pub fn append(file_path: &str, data: &str) {
|
||
let result = file::ensure_exists(file_path);
|
||
if result.is_ok() {
|
||
file::append_text_file(file_path, data);
|
||
} else {
|
||
File::create(file_path);
|
||
file::append_text_file(file_path, data);
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-67-trait-object-dyn-vecvec-contains-diffrent-type"><a class="header" href="#kata-67-trait-object-dyn-vecvec-contains-diffrent-type">Kata 67 (Trait object dyn vec,(vec contains diffrent type))</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>/**
|
||
* trait_object
|
||
*/
|
||
pub mod trait_object {
|
||
use std::fmt;
|
||
use std::fmt::Write;
|
||
pub fn run() {
|
||
fn dyn_obj_vec() {
|
||
//trait slug
|
||
use dyn_clone::DynClone;
|
||
pub trait Dyn_Vec: fmt::Display + fmt::Debug + DynClone {
|
||
fn slugify(&self) -> String;
|
||
fn tostring(&self) -> String;
|
||
fn prinln(&self);
|
||
}
|
||
impl Dyn_Vec for String {
|
||
fn slugify(&self) -> String {
|
||
format!("{}", self.replace(" ", "_"))
|
||
}
|
||
fn tostring(&self) -> String {
|
||
format!("{}", self)
|
||
}
|
||
fn prinln(&self) {
|
||
println!("{}", self);
|
||
}
|
||
}
|
||
impl Dyn_Vec for &str {
|
||
fn slugify(&self) -> String {
|
||
format!("{}", self.to_string().replace(" ", "_"))
|
||
}
|
||
fn tostring(&self) -> String {
|
||
format!("{}", self)
|
||
}
|
||
fn prinln(&self) {
|
||
println!("{}", self);
|
||
}
|
||
}
|
||
//int
|
||
impl Dyn_Vec for i8 {
|
||
fn slugify(&self) -> String {
|
||
format!("{}", self.to_string().replace(" ", "_"))
|
||
}
|
||
fn tostring(&self) -> String {
|
||
format!("{}", self)
|
||
}
|
||
fn prinln(&self) {
|
||
println!("{}", self);
|
||
}
|
||
}
|
||
impl Dyn_Vec for i16 {
|
||
fn slugify(&self) -> String {
|
||
format!("{}", self.to_string().replace(" ", "_"))
|
||
}
|
||
fn tostring(&self) -> String {
|
||
format!("{}", self)
|
||
}
|
||
fn prinln(&self) {
|
||
println!("{}", self);
|
||
}
|
||
}
|
||
impl Dyn_Vec for i32 {
|
||
fn slugify(&self) -> String {
|
||
format!("{}", self.to_string().replace(" ", "_"))
|
||
}
|
||
fn tostring(&self) -> String {
|
||
format!("{}", self)
|
||
}
|
||
fn prinln(&self) {
|
||
println!("{}", self);
|
||
}
|
||
}
|
||
impl Dyn_Vec for i64 {
|
||
fn slugify(&self) -> String {
|
||
format!("{}", self.to_string().replace(" ", "_"))
|
||
}
|
||
fn tostring(&self) -> String {
|
||
format!("{}", self)
|
||
}
|
||
fn prinln(&self) {
|
||
println!("{}", self);
|
||
}
|
||
}
|
||
impl Dyn_Vec for i128 {
|
||
fn slugify(&self) -> String {
|
||
format!("{}", self.to_string().replace(" ", "_"))
|
||
}
|
||
fn tostring(&self) -> String {
|
||
format!("{}", self)
|
||
}
|
||
fn prinln(&self) {
|
||
println!("{}", self);
|
||
}
|
||
}
|
||
//float
|
||
impl Dyn_Vec for f32 {
|
||
fn slugify(&self) -> String {
|
||
format!("{}", self.to_string().replace(" ", "_"))
|
||
}
|
||
fn tostring(&self) -> String {
|
||
format!("{}", self)
|
||
}
|
||
fn prinln(&self) {
|
||
println!("{}", self);
|
||
}
|
||
}
|
||
impl Dyn_Vec for f64 {
|
||
fn slugify(&self) -> String {
|
||
format!("{}", self.to_string().replace(" ", "_"))
|
||
}
|
||
fn tostring(&self) -> String {
|
||
format!("{}", self)
|
||
}
|
||
fn prinln(&self) {
|
||
println!("{}", self);
|
||
}
|
||
}
|
||
//the same type of vec slice impl trait
|
||
//slice item is a thing has implmented trait slug
|
||
fn same(h: &[impl Dyn_Vec]) {
|
||
//is short cut of same1()
|
||
for s in h {
|
||
println!("{}", s.tostring());
|
||
}
|
||
}
|
||
//slice item is a thing has implmented trait slug and need to be the same type
|
||
fn same1<H: Dyn_Vec>(h: &[H]) {
|
||
for s in h {
|
||
s.prinln();
|
||
}
|
||
}
|
||
same(&["a", "b", "c"]);
|
||
same1(&[format!("s0"), format!("s1"), format!("s2")]);
|
||
//diffrent type of vec slice impl trait
|
||
//slice item is a thing has implmented trait slug canbe diffrent type
|
||
//vec contain diffrent type
|
||
pub fn new_Dyn_Vec() -> Vec<Box<dyn Dyn_Vec>> {
|
||
vec![Box::new("default") as Box<dyn Dyn_Vec>]
|
||
}
|
||
let mut Dyn_Vec: Vec<Box<dyn Dyn_Vec>> = new_Dyn_Vec();
|
||
Dyn_Vec.push(Box::new("151515"));
|
||
Dyn_Vec.push(Box::new(15));
|
||
Dyn_Vec.push(Box::new(String::from("string")));
|
||
Dyn_Vec.push(Box::new(1.02));
|
||
//println dyn obj
|
||
fn println_Dyn_Vec(h: &[Box<dyn Dyn_Vec>]) {
|
||
for s in h {
|
||
println!("{}", s.tostring());
|
||
}
|
||
}
|
||
println_Dyn_Vec(&Dyn_Vec);
|
||
println!("{:?}", Dyn_Vec);
|
||
//impl Clone for trait object
|
||
dyn_clone::clone_trait_object!(Dyn_Vec);
|
||
#[derive(Clone)]
|
||
struct Each_Dyn_Vec(Box<dyn Dyn_Vec>);
|
||
let first = Dyn_Vec[0].clone();
|
||
println!("{}", first);
|
||
// fast way to implment object trait
|
||
use thin_trait_object::*;
|
||
#[thin_trait_object]
|
||
trait Addable {
|
||
fn add(&self, other: &str) -> String;
|
||
}
|
||
impl Addable for String {
|
||
fn add(&self, other: &str) -> String {
|
||
format!("{}{}", self, other)
|
||
}
|
||
}
|
||
impl Addable for &str {
|
||
fn add(&self, other: &str) -> String {
|
||
format!("{}{}", self, other)
|
||
}
|
||
}
|
||
impl Addable for Vec<i32> {
|
||
fn add(&self, other: &str) -> String {
|
||
let mut v = self.clone();
|
||
let re = match other.parse::<i32>() {
|
||
Ok(r) => {
|
||
v.push(r);
|
||
v
|
||
}
|
||
Err(r) => v,
|
||
};
|
||
format!("{:?}", re)
|
||
}
|
||
}
|
||
impl Addable for Vec<String> {
|
||
fn add(&self, other: &str) -> String {
|
||
let mut v = self.clone();
|
||
v.push(other.to_string());
|
||
format!("{:?}", v)
|
||
}
|
||
}
|
||
//move occurs because value has type `String`, which does not implement the `Copy` trait
|
||
//when this error ust yhe trait
|
||
#[thin_trait_object]
|
||
trait Cloneable {
|
||
fn clone_by_index(&self, index: usize) -> String;
|
||
}
|
||
impl Cloneable for Vec<String> {
|
||
fn clone_by_index(&self, index: usize) -> String {
|
||
let s = self.to_owned();
|
||
format!("{}", &s[index])
|
||
}
|
||
}
|
||
let s1 = BoxedAddable::new("String".to_string()).add("add");
|
||
let s2 = BoxedAddable::new("&str").add("add");
|
||
let s3 = "ok".add("add");
|
||
let s4 = vec![15, 2].add("15151"); //[15, 2, 15151]
|
||
let s5 = vec![format!("ok")].add("add str"); //[15, 2, 15151]
|
||
let s6 = vec![format!("ok")].clone_by_index(0);
|
||
println!("{}", s1);
|
||
println!("{}", s2);
|
||
println!("{}", s3);
|
||
println!("{}", s4);
|
||
println!("{}", s5);
|
||
println!("{}", s6);
|
||
}
|
||
dyn_obj_vec();
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-68-conversion_between_str_string"><a class="header" href="#kata-68-conversion_between_str_string">Kata 68 (conversion_between_str_string)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>pub mod conversion_between_str_string {
|
||
pub fn run() {
|
||
pub fn to_str(s: impl AsRef<str>) -> impl AsRef<str> {
|
||
s
|
||
}
|
||
pub fn tostring1(s: impl AsRef<str> + std::fmt::Debug + std::fmt::Display) -> String {
|
||
format!("{}", s)
|
||
}
|
||
trait Tostring: ToString + std::fmt::Debug + std::fmt::Display {
|
||
fn to_string(&self) -> String;
|
||
}
|
||
pub fn tostring(s: &dyn Tostring) -> String {
|
||
format!("{}", s)
|
||
}
|
||
impl<T: std::fmt::Display + ?Sized + std::fmt::Debug> Tostring for T {
|
||
fn to_string(&self) -> String {
|
||
let mut buf = String::new();
|
||
//for use std::fmt::Formatter::new need to add #![feature(fmt_internals)] to top of main.rs
|
||
let mut formatter = unsafe { std::fmt::Formatter::new(&mut buf) };
|
||
// Bypass format_args!() to avoid write_str with zero-length strs
|
||
std::fmt::Display::fmt(self, &mut formatter)
|
||
.expect("a Display implementation returned an error unexpectedly");
|
||
buf
|
||
}
|
||
}
|
||
assert_eq!(to_str("&str").as_ref(), "&str");
|
||
assert_eq!(to_str(format!("String")).as_ref(), "String");
|
||
assert_eq!(tostring(&format!("String")).as_ref(), format!("String"));
|
||
assert_eq!(tostring(&"&str").as_ref(), format!("&str"));
|
||
assert_eq!(tostring(&15).as_ref(), format!("15"));
|
||
assert_eq!(tostring(&15.5).as_ref(), format!("15.5"));
|
||
assert_eq!(tostring(&15.56_f64).as_ref(), format!("15.56"));
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-kata-69-vec-clone-get-item"><a class="header" href="#kata-kata-69-vec-clone-get-item">Kata Kata 69 (Vec<String> clone get item)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>trait Cloneable {
|
||
fn clone_by_index(&self, index: usize) -> String;
|
||
}
|
||
impl Cloneable for Vec<String> {
|
||
fn clone_by_index(&self, index: usize) -> String {
|
||
let s = self.to_owned();
|
||
format!("{}", &s[index])
|
||
}
|
||
}
|
||
let s: Vec<String> = vec![format!("1"), format!("2"), format!("3")];
|
||
let f0 = s.clone_by_index(0);
|
||
let f1 = s.clone_by_index(0);
|
||
println!("{}", f0);
|
||
println!("{}", f1);
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata-70-cross-compile-cros-compile-cfg-compile"><a class="header" href="#kata-70-cross-compile-cros-compile-cfg-compile">Kata 70 (Cross compile cros compile cfg compile)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust">fn main() {
|
||
#[cfg(not(target_os = "linux"))]
|
||
println!("not linux");
|
||
#[cfg(target_os = "linux")]
|
||
println!("linux");
|
||
#[cfg(target_os = "windows")]
|
||
println!("windows");
|
||
#[cfg(target_os = "macos")]
|
||
println!("macos");
|
||
#[cfg(target_os = "ios")]
|
||
println!("ios");
|
||
#[cfg(target_os = "android")]
|
||
println!("android");
|
||
#[cfg(target_os = "fuchsia")]
|
||
println!("fuchsia");
|
||
#[cfg(target_os = "freebsd")]
|
||
println!("freebsd");
|
||
}</code></pre></pre>
|
||
<h2 id="kata-71-gnome_sort"><a class="header" href="#kata-71-gnome_sort">Kata 71 (gnome_sort)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>fn gnome_sort<T: Ord>(v: &mut Vec<T>) {
|
||
let mut i = 0;
|
||
while i < v.len() {
|
||
if i == 0 || v[i - 1].le(&v[i]) {
|
||
i += 1;
|
||
} else {
|
||
v.swap(i - 1, i);
|
||
i -= 1;
|
||
}
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
<h2 id="kata72-where-my-anagrams-at"><a class="header" href="#kata72-where-my-anagrams-at">Kata72 (where my anagrams at)</a></h2>
|
||
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>/**
|
||
* Where my anagrams at?
|
||
* https://www.codewars.com/kata/523a86aa4230ebb5420001e1/train/rust
|
||
* What is an anagram? Well, two words are anagrams of each other if they both contain the same letters. For example:
|
||
'abba' & 'baab' == true
|
||
'abba' & 'bbaa' == true
|
||
'abba' & 'abbba' == false
|
||
'abba' & 'abca' == false
|
||
元素种类相同,出现次数相同=>true
|
||
元素种类不相同,出现次数不相同=>false
|
||
Write a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words. You should return an array of all the anagrams or an empty array if there are none. For example:
|
||
anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa']
|
||
anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) => ['carer', 'racer']
|
||
anagrams('laser', ['lazing', 'lazy', 'lacer']) => []
|
||
Note for Go
|
||
For Go: Empty string slice is expected when there are no anagrams found.
|
||
*/
|
||
#[allow(dead_code)]
|
||
#[allow(unused_variables)]
|
||
#[allow(unused)]
|
||
#[allow(non_snake_case)]
|
||
pub mod where_my_anagrams_at {
|
||
fn anagrams(word: &str, words: &[String]) -> Vec<String> {
|
||
// your code here
|
||
fn is_same(word1: &str, word2: &str) -> bool {
|
||
fn ordered_count(sip: &str) -> Vec<(char, i32)> {
|
||
use std::collections::BTreeMap;
|
||
let sip = sip.to_owned();
|
||
let set_sip = sip.clone();
|
||
let mut arr_sip: Vec<char> = set_sip.chars().collect();
|
||
arr_sip.sort();
|
||
arr_sip.reverse();
|
||
let mut bmap = BTreeMap::new();
|
||
for x in arr_sip {
|
||
bmap.insert(x, count_x_in_str(&sip, x));
|
||
}
|
||
fn count_x_in_str(sip: &str, target: char) -> i32 {
|
||
let mut c: i32 = 0;
|
||
for x in sip.chars() {
|
||
if target == x {
|
||
c += 1;
|
||
}
|
||
}
|
||
return c;
|
||
}
|
||
// bmap to tuple vec
|
||
fn convert_bmap_to_vec(bmap: BTreeMap<char, i32>) -> Vec<(char, i32)> {
|
||
let mut vec = vec![];
|
||
for (v, k) in &bmap {
|
||
vec.push((v.to_owned(), k.to_owned()));
|
||
}
|
||
return vec;
|
||
}
|
||
return convert_bmap_to_vec(bmap);
|
||
}
|
||
if ordered_count(word1).eq(&ordered_count(word2)) {
|
||
return true;
|
||
} else {
|
||
return false;
|
||
}
|
||
}
|
||
let mut re: Vec<String> = vec![];
|
||
for item in words.iter() {
|
||
if is_same(word, item) {
|
||
re.push(item.to_owned());
|
||
}
|
||
}
|
||
re
|
||
}
|
||
//other solution
|
||
fn anagrams1(word: &str, words: &[String]) -> Vec<String> {
|
||
use itertools::Itertools;
|
||
let cs = word.chars().sorted().collect_vec();
|
||
words
|
||
.iter()
|
||
.filter(|s| s.chars().sorted().collect_vec() == cs)
|
||
.cloned()
|
||
// .map(|s|s.to_owned()) //the same to cloned()
|
||
.collect()
|
||
}
|
||
pub fn run() {}
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
#[test]
|
||
fn sample_tests() {
|
||
do_test("abba", &["aabb", "abcd", "bbaa", "dada"], &["aabb", "bbaa"]);
|
||
do_test(
|
||
"racer",
|
||
&["crazer", "carer", "racar", "caers", "racer"],
|
||
&["carer", "racer"],
|
||
);
|
||
}
|
||
fn do_test(word: &str, words: &[&str], exp: &[&str]) {
|
||
let words: Vec<String> = words.iter().map(|w| w.to_string()).collect();
|
||
let expected: Vec<String> = exp.iter().map(|w| w.to_string()).collect();
|
||
let got = anagrams(word, &words);
|
||
assert_eq!(
|
||
got, expected,
|
||
"Failed with word: \"{}\"\nwords: {:#?}",
|
||
word, words
|
||
);
|
||
}
|
||
}
|
||
}
|
||
<span class="boring">}</span></code></pre></pre>
|
||
|
||
</main>
|
||
|
||
<nav class="nav-wrapper" aria-label="Page navigation">
|
||
<!-- Mobile navigation buttons -->
|
||
<a rel="prev" href="../../posts/leetcode/rust_leetcode.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
||
<i class="fa fa-angle-left"></i>
|
||
</a>
|
||
|
||
<a rel="next prefetch" href="../../posts/leetcode/swift_codewar.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
||
<i class="fa fa-angle-right"></i>
|
||
</a>
|
||
|
||
<div style="clear: both"></div>
|
||
</nav>
|
||
</div>
|
||
</div>
|
||
|
||
<nav class="nav-wide-wrapper" aria-label="Page navigation">
|
||
<a rel="prev" href="../../posts/leetcode/rust_leetcode.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
||
<i class="fa fa-angle-left"></i>
|
||
</a>
|
||
|
||
<a rel="next prefetch" href="../../posts/leetcode/swift_codewar.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
||
<i class="fa fa-angle-right"></i>
|
||
</a>
|
||
</nav>
|
||
|
||
</div>
|
||
|
||
|
||
|
||
<script>
|
||
window.playground_line_numbers = true;
|
||
</script>
|
||
|
||
<script>
|
||
window.playground_copyable = true;
|
||
</script>
|
||
|
||
<script src="../../ace.js"></script>
|
||
<script src="../../editor.js"></script>
|
||
<script src="../../mode-rust.js"></script>
|
||
<script src="../../theme-dawn.js"></script>
|
||
<script src="../../theme-tomorrow_night.js"></script>
|
||
|
||
<script src="../../elasticlunr.min.js"></script>
|
||
<script src="../../mark.min.js"></script>
|
||
<script src="../../searcher.js"></script>
|
||
|
||
<script src="../../clipboard.min.js"></script>
|
||
<script src="../../highlight.js"></script>
|
||
<script src="../../book.js"></script>
|
||
|
||
<!-- Custom JS scripts -->
|
||
<script src="../../src/js/custom.js"></script>
|
||
|
||
|
||
</div>
|
||
</body>
|
||
</html>
|