reordered files to support more languagues than just rust, also added a

few python challenges
master
nkoch001 6 years ago
parent fba80a7fc6
commit db882dd5dc
  1. 7
      python/dice.rolls
  2. 51
      python/dice_roller.py
  3. 31
      python/easy_word_funnel.py
  4. 6
      rust/rabbits/Cargo.toml
  5. 103
      rust/rabbits/src/main.rs
  6. 13
      rust/tally/.idea/misc.xml
  7. 8
      rust/tally/.idea/modules.xml
  8. 9
      rust/tally/.idea/tally.iml
  9. 267
      rust/tally/.idea/workspace.xml
  10. 4
      rust/tally/Cargo.lock
  11. 6
      rust/tally/Cargo.toml
  12. 42
      rust/tally/src/main.rs

@ -0,0 +1,7 @@
5d12
6d4
1d2
1d8
3d6
4d20
100d100

@ -0,0 +1,51 @@
from random import randint
def roll(number, sides):
"""
roll a number of virtual dice with a given number of sides
"""
res = 0
throws = []
for die in range(number):
throws.append(randint(1, sides))
res += throws[-1]
print(res, ":", *throws)
return res
def parselist(path):
"""
parse a list containing dice rolls (one per line) a la
5d12
6d4
1d2
1d8
3d6
4d20
100d100
"""
roll_call = []
with open(path, 'r') as rolls:
for line in rolls:
line = line.strip()
roll_call.append(line.split('d'))
return roll_call
if __name__ == '__main__':
pali = parselist('dice.rolls')
print(pali)
for to_roll in pali:
n, s = to_roll
print("Rolling", n + "d" + s)
print("Result:", roll(int(n), int(s)), '\n')
# interactive mode
x = 0
while x != 'x':
x = input("please input what you want to throw as 'NdM', or 'x' to quit\n")
if len(x.split('d')) == 2:
n, m = x.split('d')
roll(int(n), int(m))

@ -0,0 +1,31 @@
def funnel_naive(string1, string2):
"""
detect if the second string can be made from the first by removing one letter
"""
if len(string1) - len(string2) != 1:
return False
if string2 in string1:
return True
miss = 0
for i, letter2 in enumerate(string2):
if letter2 != string1[i]:
if miss > 1:
return False
miss += 1
if letter2 == string1[i + 1]:
i += 1
else:
return False
return True
funnel = lambda word, other: other in [w[:i] + w[i+1:] for i, w in enumerate([word] * len(word))]
print(funnel_naive("leave", "leav"))
print(funnel("leave", "eave"))
print(funnel("reset", "rest"))
print(funnel("dragoon", "dragon"))
print(funnel("eave", "leave"))
print(funnel("sleet", "lets"))
print(funnel("skiff", "ski"))

@ -0,0 +1,6 @@
[package]
name = "rabbits"
version = "0.1.0"
authors = ["Cpt. Captain <nilskoch94@gmail.com>"]
[dependencies]

@ -0,0 +1,103 @@
// https://www.reddit.com/r/dailyprogrammer/comments/7s888w/20180122_challenge_348_easy_the_rabbit_problem/
use std::{thread, time, io};
fn init(male: i128, female: i128, needed_alive: i128) -> ([i128; 96], [i128; 96], i128){
let mut m: [i128; 96] = [0; 96];
let mut f: [i128; 96] = [0; 96];
m[2] = male;
f[2] = female;
return (m, f, needed_alive);
}
// reproduce, by letting all females 4 months and over have 9 female and 5 male descendants
// fn reproduce(m_pop: [i128; 96], f_pop: [i128; 96]) -> ([i128; 96], [i128;96], i128, i128) {
fn reproduce(m_pop: [i128; 96], f_pop: [i128; 96]) -> (i128, i128) {
let mut res_m = 0;
let mut res_f = 0;
let f_iter = f_pop.iter().enumerate();
for (i, count) in f_iter {
if i < 95 && i > 3{
// res_f[0] = res_f[0] + count * 9;
// res_m[0] = res_m[0] + count * 5;
res_m = res_m + count * 5;
res_f = res_f + count * 9;
}
}
return (res_m, res_f);
}
// age the bunny population by shifting the array one to the right
fn age(m_pop: [i128; 96], f_pop: [i128; 96], new_males: i128, new_females: i128) -> ([i128; 96], [i128; 96]){
let mut res_m: [i128; 96] = [0; 96];
let mut res_f: [i128; 96] = [0; 96];
res_m[0] = new_males;
res_f[0] = new_females;
let f_iter = f_pop.iter().enumerate();
let m_iter = m_pop.iter().enumerate();
for (i, count) in f_iter {
if i < 95{
res_f[i+1] = *count;
}
}
for (i, count) in m_iter {
if i < 95{
res_m[i+1] = *count;
}
}
return (res_m, res_f);
}
fn main() {
// this whole part is just for reading from stdin...
let mut input_m = String::new();
let mut input_f = String::new();
let mut input_n = String::new();
println!("Enter the number of male rabbits to start with:");
io::stdin().read_line(&mut input_m).expect("failed to read input");
println!("Enter the number of female rabbits to start with:");
io::stdin().read_line(&mut input_f).expect("failed to read input");
println!("Enter the number of rabbits you want to reach:");
io::stdin().read_line(&mut input_n).expect("failed to read input");
let trim_m = input_m.trim();
let trim_f = input_f.trim();
let trim_n = input_n.trim();
let trims = vec!(trim_m, trim_f, trim_n);
let mut mf: Vec<i128> = vec!(10, 10, 10000);
for (i, trim) in trims.iter().enumerate() {
let g = &trim.parse::<i128>().unwrap_or(20);
mf[i] = *g;
}
// . up until here
let (mut m, mut f, n_a) = init(mf[0], mf[1], mf[2]);
let mut sum_male: i128 = m.iter().sum();
let mut sum_female: i128 = f.iter().sum();
let mut sum = sum_male + sum_female;
// println!("There are now {} rabbits alive!", sum);
let mut i = 0;
while sum < n_a {
// this handling of tuples sucks, there's gotta be a better way...
let (r_m, r_f) = reproduce(m, f);
let (r_m, r_f) = age(m, f, r_m, r_f);
m = r_m;
f = r_f;
sum_male = m.iter().sum();
sum_female = f.iter().sum();
sum = sum_male + sum_female;
println!("There are now {} rabbits alive! {} males and {} females", sum, sum_male, sum_female);
thread::sleep(time::Duration::from_millis(500));
i += 1;
}
println!("It took {} months!", i);
}

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CargoProjects">
<cargoProject FILE="$PROJECT_DIR$/Cargo.toml" />
</component>
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
</component>
<component name="RustProjectSettings">
<option name="explicitPathToStdlib" value="/lib/rustlib/src/rust" />
<option name="toolchainHomeDirectory" value="/usr/bin" />
</component>
</project>

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/tally.iml" filepath="$PROJECT_DIR$/.idea/tally.iml" />
</modules>
</component>
</project>

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

@ -0,0 +1,267 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="7c78f07b-55f9-466b-b38f-f8fb07dae400" name="Default" comment="" />
<option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
<option name="TRACKING_ENABLED" value="true" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="FileEditorManager">
<leaf SIDE_TABS_SIZE_LIMIT_KEY="300">
<file leaf-file-name="main.rs" pinned="false" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/src/main.rs">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="450">
<caret line="30" column="32" lean-forward="true" selection-start-line="30" selection-start-column="32" selection-end-line="30" selection-end-column="32" />
</state>
</provider>
</entry>
</file>
</leaf>
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$USER_HOME$" />
</component>
<component name="IdeDocumentHistory">
<option name="CHANGED_PATHS">
<list>
<option value="$PROJECT_DIR$/src/main.rs" />
</list>
</option>
</component>
<component name="JsBuildToolGruntFileManager" detection-done="true" sorting="DEFINITION_ORDER" />
<component name="JsBuildToolPackageJson" detection-done="true" sorting="DEFINITION_ORDER" />
<component name="JsGulpfileManager">
<detection-done>true</detection-done>
<sorting>DEFINITION_ORDER</sorting>
</component>
<component name="NodePackageJsonFileManager">
<packageJsonPaths />
</component>
<component name="ProjectFrameBounds">
<option name="x" value="3201" />
<option name="y" value="4" />
<option name="width" value="1275" />
<option name="height" value="1405" />
</component>
<component name="ProjectLevelVcsManager" settingsEditedManually="true" />
<component name="ProjectView">
<navigator proportions="" version="1">
<foldersAlwaysOnTop value="true" />
</navigator>
<panes>
<pane id="Scope" />
<pane id="PackagesPane" />
<pane id="ProjectPane">
<subPane>
<expand>
<path>
<item name="tally" type="b2602c69:ProjectViewProjectNode" />
<item name="tally" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="tally" type="b2602c69:ProjectViewProjectNode" />
<item name="tally" type="462c0819:PsiDirectoryNode" />
<item name="src" type="462c0819:PsiDirectoryNode" />
</path>
</expand>
<select />
</subPane>
</pane>
<pane id="AndroidView" />
</panes>
</component>
<component name="PropertiesComponent">
<property name="WebServerToolWindowFactoryState" value="false" />
<property name="aspect.path.notification.shown" value="true" />
<property name="last_opened_file_path" value="$PROJECT_DIR$/.." />
<property name="nodejs_interpreter_path.stuck_in_default_project" value="undefined stuck path" />
<property name="nodejs_npm_path_reset_for_default_project" value="true" />
<property name="org.rust.cargo.project.model.PROJECT_DISCOVERY" value="true" />
<property name="settings.editor.selected.configurable" value="settings.github" />
</component>
<component name="RunDashboard">
<option name="ruleStates">
<list>
<RuleState>
<option name="name" value="ConfigurationTypeDashboardGroupingRule" />
</RuleState>
<RuleState>
<option name="name" value="StatusDashboardGroupingRule" />
</RuleState>
</list>
</option>
</component>
<component name="RunManager">
<configuration default="true" type="Applet" factoryName="Applet">
<option name="POLICY_FILE" value="$APPLICATION_HOME_DIR$/bin/appletviewer.policy" />
</configuration>
<configuration default="true" type="Application" factoryName="Application">
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
</configuration>
<configuration name="Run tally" type="CargoCommandRunConfiguration" factoryName="Cargo Command" temporary="true">
<option name="channel" value="DEFAULT" />
<option name="command" value="run --package tally --bin tally" />
<option name="nocapture" value="true" />
<option name="backtrace" value="SHORT" />
<option name="workingDirectory" value="file://$PROJECT_DIR$" />
<envs />
</configuration>
<configuration default="true" type="JUnit" factoryName="JUnit">
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="PACKAGE_NAME" />
<option name="MAIN_CLASS_NAME" />
<option name="METHOD_NAME" />
<option name="TEST_OBJECT" value="class" />
<option name="VM_PARAMETERS" value="-ea" />
<option name="PARAMETERS" />
<option name="WORKING_DIRECTORY" value="$MODULE_DIR$" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<patterns />
</configuration>
<configuration default="true" type="TestNG" factoryName="TestNG">
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="SUITE_NAME" />
<option name="PACKAGE_NAME" />
<option name="MAIN_CLASS_NAME" />
<option name="METHOD_NAME" />
<option name="GROUP_NAME" />
<option name="TEST_OBJECT" value="CLASS" />
<option name="VM_PARAMETERS" value="-ea" />
<option name="PARAMETERS" />
<option name="WORKING_DIRECTORY" value="$MODULE_DIR$" />
<option name="OUTPUT_DIRECTORY" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<option name="USE_DEFAULT_REPORTERS" value="false" />
<option name="PROPERTIES_FILE" />
<properties />
<listeners />
</configuration>
<configuration default="true" type="Remote" factoryName="Remote">
<option name="USE_SOCKET_TRANSPORT" value="true" />
<option name="SERVER_MODE" value="false" />
<option name="SHMEM_ADDRESS" value="javadebug" />
<option name="HOST" value="localhost" />
<option name="PORT" value="5005" />
<method />
</configuration>
<configuration default="true" type="#org.jetbrains.idea.devkit.run.PluginConfigurationType" factoryName="Plugin">
<module name="" />
<option name="VM_PARAMETERS" value="-Xmx512m -Xms256m -XX:MaxPermSize=250m -ea" />
<option name="PROGRAM_PARAMETERS" />
<predefined_log_file id="idea.log" enabled="true" />
<method />
</configuration>
<recent_temporary>
<list>
<item itemvalue="Cargo Command.Run tally" />
</list>
</recent_temporary>
</component>
<component name="SvnConfiguration">
<configuration />
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="7c78f07b-55f9-466b-b38f-f8fb07dae400" name="Default" comment="" />
<created>1527013010362</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1527013010362</updated>
<workItem from="1527013011570" duration="5353000" />
<workItem from="1527021051624" duration="2259000" />
</task>
<servers />
</component>
<component name="TimeTrackingManager">
<option name="totallyTimeSpent" value="7612000" />
</component>
<component name="ToolWindowManager">
<frame x="3201" y="4" width="1275" height="1405" extended-state="0" />
<layout>
<window_info anchor="right" id="Palette" order="3" />
<window_info anchor="bottom" id="TODO" order="6" />
<window_info anchor="right" id="Cargo" order="3" />
<window_info anchor="right" id="Palette&#9;" order="3" />
<window_info id="Image Layers" order="2" />
<window_info anchor="right" id="Capture Analysis" order="3" />
<window_info active="true" anchor="bottom" id="Event Log" order="7" sideWeight="0.50040686" side_tool="true" visible="true" weight="0.32943925" />
<window_info anchor="right" id="Maven Projects" order="3" />
<window_info anchor="bottom" id="Database Changes" order="7" show_stripe_button="false" />
<window_info anchor="bottom" id="Version Control" order="7" show_stripe_button="false" />
<window_info anchor="bottom" id="Run" order="2" sideWeight="0.49959317" weight="0.3299532" />
<window_info anchor="bottom" id="Terminal" order="7" />
<window_info id="Capture Tool" order="2" />
<window_info id="Designer" order="2" />
<window_info content_ui="combo" id="Project" order="0" visible="true" weight="0.25386494" />
<window_info anchor="right" id="Database" order="3" />
<window_info id="Structure" order="1" side_tool="true" weight="0.25" />
<window_info anchor="right" id="Ant Build" order="1" weight="0.25" />
<window_info id="UI Designer" order="2" />
<window_info anchor="right" id="Theme Preview" order="3" />
<window_info id="Favorites" order="2" side_tool="true" />
<window_info anchor="bottom" id="Debug" order="3" weight="0.4" />
<window_info anchor="right" content_ui="combo" id="Hierarchy" order="2" weight="0.25" />
<window_info anchor="bottom" id="Inspection" order="5" weight="0.4" />
<window_info anchor="right" id="Commander" order="0" weight="0.4" />
<window_info anchor="bottom" id="Message" order="0" />
<window_info anchor="bottom" id="Cvs" order="4" weight="0.25" />
<window_info anchor="bottom" id="Find" order="1" />
</layout>
</component>
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="1" />
</component>
<component name="VcsContentAnnotationSettings">
<option name="myLimit" value="2678400000" />
</component>
<component name="VcsManagerConfiguration">
<ignored-roots>
<path value="$USER_HOME$" />
<path value="$PROJECT_DIR$" />
</ignored-roots>
</component>
<component name="editorHistoryManager">
<entry file="file://$PROJECT_DIR$/src/main.rs">
<provider selected="true" editor-type-id="text-editor">
<state>
<caret column="102" selection-start-column="102" selection-end-column="102" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main.rs">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="450">
<caret line="30" column="32" lean-forward="true" selection-start-line="30" selection-start-column="32" selection-end-line="30" selection-end-column="32" />
</state>
</provider>
</entry>
</component>
<component name="masterDetails">
<states>
<state key="ProjectJDKs.UI">
<settings>
<last-edited>1.8</last-edited>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
</states>
</component>
</project>

@ -0,0 +1,4 @@
[[package]]
name = "tally"
version = "0.1.0"

@ -0,0 +1,6 @@
[package]
name = "tally"
version = "0.1.0"
authors = ["Cpt.Captain <nilskoch94@gmail.com>"]
[dependencies]

@ -0,0 +1,42 @@
// https://www.reddit.com/r/dailyprogrammer/comments/8jcffg/20180514_challenge_361_easy_tally_program/
// this is pretty much my first rust program
fn main() {
let input = "EbAAdbBEaBaaBBdAccbeebaec";
println!("Tallying {}", input);
let player_list = String::from(init_player_list(input.to_string()));
println!("These people are playing: {}", player_list);
let tally = tally(player_list, input.to_string());
println!("These are their scores:");
println!("{:?}", tally);
}
// get all distinct characters
fn init_player_list(input: String) -> String{
let mut result = String::new();
let ch = input.chars();
for cha in ch{
let lch = cha.to_lowercase().next().unwrap();
if !result.contains(lch){
result.push(lch);
}
}
return result
}
// tally each players scores
// lowercase => +1 point
// uppercase => -1 point
fn tally(player_list: String, tally: String) -> Vec<(char, i32)>{
let mut v: Vec<(char, i32)> = Vec::new();
for (_i, player) in player_list.chars().enumerate() {
let count = (tally.matches(player).count() as i32) - (tally.matches(player
.to_uppercase().next().unwrap()).count() as i32);
v.push((player, count));
}
v.sort_by_key(|v| v.1);
v.reverse();
return v
}
Loading…
Cancel
Save