perfect shuffle 完美洗牌算法

详解欧拉计划第622题:完美洗牌 欧拉计划第622题:完美洗牌有这样一种洗牌:将牌张平分为两份,左手拿上半部分牌张,右手拿下半部分牌张,然后,将右手的牌严格地交叉到左手的牌张中,也就是右手的第1张牌处于左手的第1张牌后面,右手的第2张牌处于左手的第2张牌后面,依次类推。...... 阅读详情

完美洗牌问题:给定一个数组a1,a2,a3,...an,b1,b2,b3..bn,把它最终设置为b1,a1,b2,a2,...bn,an这样的。

  perfect shuffle实质是一个置换。置换为: ­

                  i -> 2*i mod (2*n+1) ­

置换可以分解为一系列不相交的轮换之积。故如果能找出所有轮换的一个代表元则可很容易解决问题。 ­我们的关键问题是从每个圈里选择任意一个位置作代表,每个圈从这个位置位置走一圈。

结论:对于2 * n = (3^k - 1),这种长度的数组,恰好只有k个圈,并且每个圈的头部是1,3,9,...3^(k - 1)。

对于一般的n,把它拆成两部分,前一部分是满足结论,后一部分再单独算。为了把数组分成适当的两部分,我们同样需要交换一些元素。假设满足结论的需要的长度是2 * m = (3^k - 1), 我们需要把n分解成m和n - m两部分,按下标来说,是这样:

原先的数组(1..m) (m + 1.. n) (n + 1..n + m)(n + m + 1..2 * n),我们要达到的数组 (1..m)(n + 1.. n + m)(m + 1..n)(n + m + 1..2  * n)。可见,中间那两段长度为(n - m)和m的段需要交换位置,这个相当于把(m + 1..n + m)的段循环右移m次。


算法步骤:

输入数组 a[1..2 * n]

step 1 找到 2 * m = 3^k - 1 使得 3^k <= 2 * n < 3^(k +1)

step 2 把a[m + 1..n + m]那部分循环移m位

step 3 对每个i = 0,1,2..k - 1,3^i是个圈的头部,做cycle_leader算法,数组长度为m,所以对2 * m + 1取模。

step 4 对数组的后面部分a[2 * m + 1.. 2 * n]继续使用本算法,这相当于n减小了m。


USRP N210与MATLAB连接实战:从驱动安装到信号接收 本文详细介绍了USRP N210与MATLAB连接的完整流程,涵盖驱动安装、网络配置、支持包安装及信号接收实战。重点解决了安装过程中的常见错误和硬件连接问题,并通过MATLAB代码示例展示了如何配置接收器、处理信号数据,帮助用户快速实现从设备对接到信号分析的全过程。 阅读详情

相关推荐

【NLP】文献翻译4——CH-SIMS:中文多模态情感分析数据集与细粒度的模态注释

CH-SIMS: A Chinese Multimodal Sentiment Analysis Dataset with Fine-grained Annotations of Modality摘要1. 介绍2. 相关工作2.1 多模态数据集2.2 多模态情感分析2.3 多任务学习3. CH-SIMS 数据集3.1 数据获取3.2 标注3.3 特征提取4. 多模式多任务学习框架4.1 单模态子网4.2 特征融合网络4.3 优化目标5. 实验5.1 基准5.2 实验的细节5.3 结果和讨论5.3.1 与

YoungSeng's Blog 1万+

完美洗牌算法

输入 , 如何在O(n)的时间,用O(1)的空间,将这个序列顺序改为 。 输入:1234567dbcdefg 则输出1a2b3c4d5e6f7g 公式:y = 2x mod (2n -1), 顾而 x = (y + k * (2n - 1))/2 这里k可以化成y相关,因为i 范围为0--2n-1所以y+k(2n-1) 必须在0 --(2n-1)*2 所以y 与k*(2n-

zzmc的专栏 3881

从网口变压器到TVS管:手把手设计通过4KV浪涌的以太网电路

本文详细解析工业级以太网接口4KV浪涌防护设计,从网口变压器选型到TVS管布局,提供通过IEC61000-4-5标准测试的完整方案。重点介绍Bob Smith电路优化和PCB设计技巧,帮助工程师有效应对雷电感应和设备开关瞬态干扰,确保工业设备稳定运行。

study的专栏 299

完美洗牌的秘密(一)——(反)完美洗牌定理

早点关注我,精彩不错过!在我们MatheMagician刚创刊的时候,曾经写过的第一个长篇系列:《关于洗牌的研究(七)——从数学到魔术之鸽尾洗牌》。在那一期文章里其中一部分就是介绍完美洗牌的诸多性质,并且给出了当时我仅了解的两个完美洗牌的魔术《洗牌巴格拉斯》和《完美三明治》。这些作品充分体现了在完美洗牌下,每一个索引处的扑克牌的位置变化的规律,不妨复习一下:关于洗牌的研究(六)——从数学到魔术之完...

magic2728的博客 2243

SAP录入总账凭证报错 公司代码未被分配给国家或用于计算程序的国家消息号 FF703

SAP系统报错FF703的解决方案:当公司代码未分配国家或未配置计税程序时,会导致增值税计算失败。处理方法:1)通过OX02检查公司代码国家字段;2)使用OBBG为国家分配计税程序(如TAXCN)。配置步骤:1)SPRO分配公司代码到国家;2)OBBG设置国家对应的计税程序。注意事项:历史数据需清理才能修改国家字段,不同账簿可配置不同计税程序。完成配置后即可正常处理含税凭证。

金牌架构师 562

多智能体记忆架构设计:从分层模型到一致性实践

多智能体记忆架构本质上是一个有状态、分布式、支持遗忘的知识系统。从分层模型入手,结合RBAC隔离、版本向量一致性以及混合存储,可以构建出既灵活又健壮的生产级方案。可微分记忆:让记忆的读写操作嵌入端到端训练。基于大模型的记忆压缩:用LLM自动生成情景摘要,取代规则式遗忘。联邦记忆:不同组织之间的多智能体系统在不共享原始数据的情况下协同记忆。希望本文能为你的多智能体项目提供一块坚实的基石。欢迎在评论区分享你在实践中遇到的记忆架构难题。

Ven%的博客 174

洗牌算法3-完美洗牌算法

#### 2.3、Perfect shuffle algorithm perfect_shuffle3 ##### 2.3.1、cycle_leader algorithm Either perfect_shuffle1, or perfect_shuffle2, these two algorithms do not reach the time complexity of O (N) an

lmdyyh5722756的专栏 1073

【回眸】Tessy集成测试软件使用指南(一)新手使用篇

这个专栏的文章前4篇都在记录如何使用Tessy进行单元测试,集成测试需要有一定单元测试基础,且做集成测试之前,需要做好单元测试,否则将会大幅增加软件单元代码纠错的代价。集成测试所花费的时间通常远远超过单元测试。如果直接从单元测试到系统测试,结果往往是不理想的。集成测试可以检测由于单元相互交互而导致的错误,通常由一组专业的测试人员执行。

啤酒鸭的物联网开发记录博客 5310

[转]完美洗牌(Perfect Shuffle)问题

[转]原博文地址:https://github.com/julycoding/The-Art-Of-Programming-By-July/blob/master/ebook/zh/02.09.md 完美洗牌算法 题目详情 有个长度为2n的数组{a1,a2,a3,...,an,b1,b2,b3,...,bn},希望排序后{a1,b1,a2,b2,....,an,bn},请考虑有无时间复杂度o...

weixin_30487201的博客 731

真随机数与伪随机数

前面我们学习了LFSR,这个玩意落地到具体的应用是什么呢?没错是寄存器,这里在网络找到了几个回答,这里做个记录,下面一起来学习一下吧。

叫好与叫座虽然不是对立面,但想在同一个作品中达到双重效果很难。 1065

【2024/3/12 更新】Windows Server 2019 服务配置与管理汇总

本栏目一共介绍了17种Windows Server 2019 的服务配置与管理,为了方便大家阅读理解,特意总结了17种服务的一些内容。具体说明如下所示

VMware, Windows, Linux, Cisco, Container, Kubernetes, Kali 2万+

perfect shuffle 算法的一个线性复杂度实现

今天又发现一个关于完美洗牌的算法。这个比较简单一些,由 microsoft的Peiyush Jain提出。 ­ ­ 原论文:      A Simple In-Place Algorithm for In-Shuffle. ­                  Peiyush Jain, Microsoft Corporation. ­

540

康耐视visionpro-CogCreateSegmentAvgSegsTool操作工具详细说明

康耐视visionpro-CogCreateSegmentAvgSegsTool操作工具详细说明

视觉人机器视觉的博客 1492

perfect_shuffle的C++实现

今天花了点时间实现了C++版的perfect_shuffle算法,具体代码如下:

lmdyyh5722756的专栏 1110

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

完美洗牌算法(2013年UC校招笔试、2016阿里实习生笔试)

完美洗牌算法 2013年UC校招笔试、2016阿里实习生笔试

那年聪聪 3979

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

算法:完美洗牌问题

有个的数组{a1,a2,a3,…,an,b1,b2,b3,…,bn},希望排序后{a1,b1,a2,b2,….,an,bn},请考虑有无时间复杂度o(n),空间复杂度0(1)的解法。

OceanStar的博客 631

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

数组元素交叉排列的算法题(a1 a2 a3 .. an b1 b2 b3 .. bn -->a 1 b1, a2 b2, a3 b3, .. an bn ) 概论思想(perfect shuffle 算法)

perfect shuffle 算法 <br />今天又发现一个关于完美洗牌的算法。这个比较简单一些,由 microsoft的Peiyush Jain提出。 ­<br />­<br />原论文:      A Simple In-Place Algorithm for In-Shuffle. ­<br />                 Peiyush Jain, Microsoft Corporation. ­<br />                            July 2004<br

yuan8080的专栏 7443

[CareerCup] 18.2 Shuffle Cards 洗牌

18.2 Write a method to shuffle a deck of cards. It must be a perfect shuffle—in other words, each of the 52! permutations of the deck has to be equally likely. Assume that you a...

weixin_33897722的博客 100

随机洗牌

Write a method to shuffle a deck of cards. It must be a perfect shuffle - in other words, each 52! permutations of the deck has to be equally likely. Assume that you are given a random number genera

jiyanfeng1的专栏 641

遗传算法实战:100皇后问题的编码、适应度与早停设计

遗传算法是一种受生物进化启发的全局优化方法,其核心在于染色体编码、适应度评估与种群演化机制。在离散组合优化场景中,N皇后问题因其超大规模搜索空间(如100!)成为检验GA工程能力的理想载体。本文围绕适应度函数设计(含+0.001平滑项)、种群初始化(保排列的Fisher-Yates洗牌)及早停机制(基于数学精确阈值)展开技术解析,强调变异操作对解空间结构的适配性,避免交叉导致的非法解。适用于算法工程师快速构建可调试、可复用的GA求解器,并迁移到TSP等排列型优化任务。

weixin_30443747的博客 497

Python遗传算法实战:N皇后问题从编码到收敛的完整工程实现

遗传算法(GA)是一种基于自然选择与群体搜索的通用优化范式,其核心在于染色体编码、适应度评估、选择压力与变异机制的协同作用。在离散组合优化场景中,N皇后问题因其解空间清晰、约束可编码、适应度可精确量化等特性,成为验证GA原理与调参逻辑的理想载体。本文聚焦真实工程落地,详解如何用纯Python实现无框架依赖的GA求解器——涵盖Matlab到Python的可读性重构、仅用变异替代交叉的轻量设计、基于排列编码的硬约束内化、1/q型适应度函数的尺度敏感性设计,以及种群规模与变异率的实测平衡点。所有代码直面调试痛点,

weixin_34357436的博客 463
上一篇: 全排列算法
下一篇: 字符串相似度计算
ae5555
博客等级 码龄15年 21粉丝 143原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值