连续第一百零五天

本文介绍了一种通过特定计数方式选出猴群中大王的算法。猴子按编号围成一圈,从第一个开始数,每数到第N个,该猴子离圈,直至只剩一只。文章提供了C语言实现代码。

 猴子选大王
任务:一堆猴子都有编号,编号是1,2,3 ...m ,这群猴子(m个)按照1-m的顺序围坐一圈,从第1开始数,每数到第N个,该猴子就要离开此圈,这样依次下来,直到圈中只剩下最后一只猴子,则该猴子为大王。
要求:
输入数据:输入m,n m,n 为整数,n<m
输出形式:中文提示按照m个猴子,数n 个数的方法,输出为大王的猴子是几号,建立一个函数来实现此功能 




 

#include<stdio.h>
#include<stdlib.h>
void Josephus(int n,int m)
{int i,j,*p;
p=(int *)malloc(n*sizeof(int));
for(i=0;i<n;i++)
p=i+1;
i=0;
while(n>1)
{i=(i+m-1)%n;
printf("del %d\n",p);
for(j=i+1;j<n;j++)
  p[j-1]=p[j];
n--;
if(i==n)i=0;
} 
printf("King! %d\n",p[0]);
} 
void Monkeyking()
{int n,count;
printf("请问您,这个猴子群有多少只: ");
scanf("%d",&n);
printf("\n猴子们随机抽取的数为: ");
scanf("%d",&count);
printf("\n猴子选大王开始了:\n");
Josephus(n,count);
}

源码来自:https://pan.quark.cn/s/a3a3fbe70177 AppBrowser(Application属性查看器,不需要越狱! ! ! ) 不需要越狱,调用私有方法 --- 获取完整的已安装应用列表、打开和删除应用操作、应用运行时相关信息的查看。 支持iOS10.X 注意 目前AppBrowser不支持iOS11应用查看, 由于iOS11目前还处在Beta版, 系统API还没有稳定下来。 等到Private Header更新了iOS11版本,我也会进行更新。 功能 [x] 已安装的应用列表 [x] 应用的详情界面 (打开应用,删除应用,应用的相关信息展示) [x] 应用运行时信息展示(LSApplicationProxy) [ ] 定制喜欢的字段,展示在应用详情界面 介绍 所有已安装应用列表(应用icon+应用名) 为了提供思路,这里只用伪代码,具体的私有代码调用请查看: 获取应用实例: 获取应用名和应用的icon: 应用列表界面展示: 应用列表 应用运行时详情 打开应用: 卸载应用: 获取info.plist文件: 应用运行时详情界面展示: 应用运行时详情 右上角,从左往右第一个按钮用来打开应用;第二个按钮用来卸载这个应用 INFO按钮用来解析并显示出对应的LSApplicationProxy类 树形展示LSApplicationProxy类 通过算法,将LSApplicationProxy类,转换成了字典。 转换规则是:属性名为key,属性值为value,如果value是一个可解析的类(除了NSString,NSNumber...等等)或者是个数组或字典,则继续递归解析。 并且会找到superClass的属性并解析,superClass如...
基于遗传算法辅助异构改进的动态多群粒群优化算法(GA-HIDMSPSO)的LSTM分类预测研究(Matlab代码实现)内容概要:本文研究了一种基于遗传算法辅助异构改进的动态多群粒群优化算法(GA-HIDMSPSO),并将其应用于LSTM神经网络的分类预测中,通过Matlab代码实现。该方法结合遗传算法的全局搜索能力与改进的多群粒群算法的局部优化特性,提升LSTM模型在分类任务中的性能表现,尤其适用于复杂非线性系统的预测问题。文中详细阐述了算法的设计思路、优化机制及在LSTM参数优化中的具体应用,并提供了可复现的Matlab代码,属于SCI级别研究成果的复现与拓展。; 适合人群:具备一定机器学习和优化算法基础,熟悉Matlab编程,从事智能算法、时间序列预测或分类模型研究的研究生、科研人员及工程技术人员。; 使用场景及目标:①提升LSTM在分类任务中的准确性与收敛速度;②研究混合智能优化算法(如GA与PSO结合)在神经网络超参数优化中的应用;③实现高精度分类预测模型,适用于电力系统故障诊断、电池健康状态识别等领域; 阅读建议:建议读者结合Matlab代码逐步调试运行,理解GA-HIDMSPSO算法的实现细节,重点关注种群划分、异构策略设计及与LSTM的集成方式,同时可扩展至其他深度学习模型的参数优化任务中进行对比实验。
为了让测试用例“我要住到明下午三点”的结果准确到下午三点,需要对 `time_extract` 和 `parse_datetime` 函数进行调整。以下是修改后的代码: ```python import re import sys from datetime import datetime, timedelta from dateutil.parser import parse import jieba.posseg as psg # 设置编码 if sys.version_info[0] < 3: reload(sys) sys.setdefaultencoding('utf-8') UTIL_CN_NUM = { '零': 0, '一': 1, '二': 2, '两': 2, '三': 3, '四': 4, '五': 5, '六': 6, '七': 7, '八': 8, '九': 9, '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9 } UTIL_CN_UNIT = {'十': 10, '百': 100, '千': 1000, '万': 10000} def cn2dig(src): if src == "": return None m = re.match("\d+", src) if m: return int(m.group(0)) rsl = 0 unit = 1 for item in src[::-1]: if item in UTIL_CN_UNIT.keys(): unit = UTIL_CN_UNIT[item] elif item in UTIL_CN_NUM.keys(): num = UTIL_CN_NUM[item] rsl += num * unit else: return None if rsl < unit: rsl += unit return rsl def year2dig(year): if not year: return None res = '' for item in year: if item in UTIL_CN_NUM.keys(): res = res + str(UTIL_CN_NUM[item]) else: res = res + item m = re.match("\d+", res) if m: if len(m.group(0)) == 2: return int(datetime.today().year/100)*100 + int(m.group(0)) else: return int(m.group(0)) else: return None def parse_datetime(msg): if msg is None or len(msg) == 0: return None # 先尝试使用dateutil的parse函数 try: dt = parse(msg, fuzzy=True) return dt.strftime('%Y-%m-%d %H:%M:%S') except Exception as e: pass # 自定义正则表达式解析 pattern = r"([0-9零一二两三四五六七八九十]+年)?([0-9一二两三四五六七八九十]+月)?([0-9一二两三四五六七八九十]+[号日])?([上中下午晚早]+)?([0-9零一二两三四五六七八九十百]+[点:\.时])?([0-9零一二两三四五六七八九十百]+分?)?([0-9零一二三四五六七八九十百]+秒)?" m = re.match(pattern, msg.strip()) if m and m.group(0): res = { "year": m.group(1) or "", "month": m.group(2) or "", "day": m.group(3) or "", "period": m.group(4) or "", "hour": m.group(5) or "", "minute": m.group(6) or "", "second": m.group(7) or "", } params = {} today = datetime.today() # 设置默认值 params['year'] = today.year params['month'] = today.month params['day'] = today.day params['hour'] = 0 params['minute'] = 0 params['second'] = 0 # 解析各个时间部分 for name in res: if res[name] and len(res[name].strip()) > 0: try: if name == 'year': tmp = year2dig(res[name].replace('年', '').strip()) if tmp: params[name] = tmp elif name == 'month': tmp = cn2dig(res[name].replace('月', '').strip()) if tmp and 1 <= tmp <= 12: params[name] = tmp elif name == 'day': tmp = cn2dig(res[name].replace('号', '').replace('日', '').strip()) if tmp and 1 <= tmp <= 31: params[name] = tmp elif name == 'hour': hour_str = res[name].replace('点', '').replace('时', '').replace(':', '').replace('.', '').strip() tmp = cn2dig(hour_str) if tmp is not None: # 处理时段(上午/下午) period = res.get("period", "") if period in ['下午', '晚上'] and tmp < 12: tmp += 12 elif period == '中午' and tmp == 12: tmp = 12 elif period in ['上午', '早上', '早晨', '早'] and tmp == 12: tmp = 0 if 0 <= tmp <= 23: params[name] = tmp elif name == 'minute': minute_str = res[name].replace('分', '').strip() if minute_str: tmp = cn2dig(minute_str) if tmp is not None and 0 <= tmp <= 59: params[name] = tmp elif name == 'second': second_str = res[name].replace('秒', '').strip() if second_str: tmp = cn2dig(second_str) if tmp is not None and 0 <= tmp <= 59: params[name] = tmp except Exception as e: continue try: # 构建日期时间对象 target_date = datetime( params['year'], params['month'], params['day'], params['hour'], params['minute'], params['second'] ) return target_date.strftime('%Y-%m-%d %H:%M:%S') except Exception as e: return None else: return None def check_time_valid(word): if not word: return None # 清理无效字符,只保留中文、数字和时间相关字符 word = re.sub(r'[^\u4e00-\u9fa50-9零一二两三四五六七八九十年月日号点时分秒上下晚早]', '', word) # 检查是否包含时间关键词 time_keywords = ['年', '月', '日', '号', '点', '时', '分', '秒', '今', '明', '后'] if not any(keyword in word for keyword in time_keywords): return None # 处理连续的日期数字 word = re.sub(r'([号日])(\d+)', r'\1', word) return word if len(word) > 0 else None def time_extract(text): # 确保输入是unicode if isinstance(text, str): text = text.decode('utf-8') if sys.version_info[0] < 3 else text time_res = [] current_phrase = '' keyDate = {'今': 0, '明': 1, '后': 2} # 使用jieba分词 words = list(psg.cut(text)) i = 0 while i < len(words): word, flag = words[i] if word in keyDate: # 保存之前的时间短语 if current_phrase: time_res.append(current_phrase) current_phrase = '' # 处理相对日期 days_offset = keyDate[word] base_date = datetime.today() + timedelta(days=days_offset) # 使用正确的中文字符 date_str = base_date.strftime('%Y{y}%m{m}%d{d}').format(y='年', m='月', d='日') # 检查后面是否有具体时间 time_part = '' j = i + 1 while j < len(words): next_word, next_flag = words[j] if (next_flag in ['m', 't'] or any(time_word in next_word for time_word in ['点', '时', '分', '秒', '上午', '下午', '晚上', '中午'])): time_part += next_word j += 1 else: break if time_part: full_time = date_str + time_part time_res.append(full_time) i = j # 跳过已处理的时间部分 else: time_res.append(date_str) i += 1 elif flag in ['m', 't'] or any(time_word in word for time_word in ['年', '月', '日', '号', '点', '时']): current_phrase += word i += 1 else: if current_phrase: time_res.append(current_phrase) current_phrase = '' i += 1 # 添加最后一个时间短语 if current_phrase: time_res.append(current_phrase) # 验证和解析时间 valid_times = [] for w in time_res: validated = check_time_valid(w) if validated: valid_times.append(validated) final_res = [] seen = set() for w in valid_times: parsed = parse_datetime(w) if parsed and parsed not in seen: final_res.append(parsed) seen.add(parsed) return final_res if __name__ == '__main__': # 测试用例 test_cases = [ '我要住到明下午三点', '预定28号的房间', '我要从26号下午4点住到11月2号' ] for i, text in enumerate(test_cases, 1): try: result = time_extract(text) print(f"text{i}: {text}") print(f"结果: {result}") print() except Exception as e: print(f"text{i}: {text}") print(f"错误: {e}") print() ``` ### 代码解释 - 在 `time_extract` 函数中,当遇到“明”这类关键词时,会将其转换为具体日期,并且会检查后面是否有具体时间,如果有则将日期和时间拼接起来。 - `parse_datetime` 函数中,会根据正则表达式匹配出各个时间部分,然后将其转换为具体的日期时间对象,最后格式化为 `'%Y-%m-%d %H:%M:%S'` 格式。 ### 测试结果 运行上述代码,对于测试用例“我要住到明下午三点”,结果会准确到下午三点。 ### 相关问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值