这个问题与上面建议的问题不重复。标题可能听起来相似,但它的答案不会以任何方式导致结果中描述的结果下面的问题。
我很难以递归方式遍历未知长度的数组来创建唯一的字符串组合。你能帮忙吗?
目标是获取像 foo bar 这样的字符串,并从该字符串创建独特的组合:
foo
bar
bar_foo (alphabetized to make unique combinations, not permutations)
另一个例子:
car bar add 应该返回:
add
add_bar
add_car
add_bar_car
bar
bar_car
car
这是我的进步:
function string_builder($length) {
$arrWords = array('add','bar','car','dew','eat','fat','gym','hey','ink','jet','key','log','mad','nap','odd','pal','qat','ram','saw','tan','urn','vet','wed','xis','yap','zoo');
$arr = array();
for ($i=0; $i < $length; $i++) {
$arr[] = $arrWords[$i];
}
return implode(' ', $arr);
}
function get_combinations($string) {
$combinations = array(); // put all combinations here
$arr = explode(' ',$string);
$arr = array_unique($arr); // only unique words are important
sort($arr); // alphabetize to make unique combinations easier (not permutations)
$arr = array_values($arr); // reset keys
for ($i=0; $i < count($arr); $i++) {
// this is where I'm stuck
// how do I loop recursively through all possible combinations of an array?
}
return $combinations;
}
// Test it!
for ($i=1; $i < 26; $i++) {
$string = string_builder($i);
$combinations = get_combinations($string);
echo $i . " words\t" . count($combinations) . " combinations\t" . $string . "\n";
// print_r($combinations);
}
另一个尝试:
function getCombinations2($str, $min_length = 2) {
$words = explode(' ', $str);
$combinations = array();
$len = count($words);
for ($a = $min_length; $a <= $min_length; $a++) {
for ($pos = 0; $pos < $len; $pos ++) {
if(($pos + $a -1) < $len) {
$tmp = array_slice($words, $pos, $a);
sort($tmp);
$tmp = implode('_',$tmp);
$combinations[] = $tmp;
}
}
}
$combinations = array_unique($combinations);
return $combinations;
}
当您打印出这些组合并寻找一些应该存在的组合(例如,“fat_zoo”、“car_tan”)时,您就可以知道您已经成功了。我的两次尝试都会显示其中的几个,但不会显示全部。
最佳答案
您要搜索的内容很容易使用二进制数构建(并解释)。
二进制 word 中的每个位置都应指示是否附加了数组中的某个单词。
假设,您有一个由两个单词组成的数组:
$words = ["foo","bar"];
您现在期待组合
foo
bar
bar_foo
在二进制中这可以表示为
1 0
0 1
1 1
三个单词 $words = ["foo","bar", "baz"]; 就是组合
foo
bar
baz
foo_bar
foo_baz
bar_baz
foo_bar_baz
可以理解为
1 0 0
0 1 0
0 0 1
1 1 0
1 0 1
0 1 1
1 1 1
(现在忽略字母排序)
让我们将这些二进制数按具体顺序移动并查看它们的十进制值:
0 0 1 // dec 1
0 1 0 // dec 2
0 1 1 // dec 3
1 0 0 // dec 4
1 0 1 // dec 5
1 1 0 // dec 6
1 1 1 // dec 7
注意:您要生成的元素数量是(2^n)-1,其中n 是您的字数。
这基本上就是您需要做的所有事情:
1 迭代到 (2^n)-1。PHP:
print_r(get_combinations("car bar add"));
function get_combinations($str) {
$words = explode(' ',$str);
$elements = pow(2, count($words))-1;
$result = array();
for ($i = 1; $i<=$elements; $i++){
$bin = decbin($i);
$padded_bin = str_pad($bin, count($words), "0", STR_PAD_LEFT);
$res = array();
for ($k=0; $k<count($words); $k++){
//append element, if binary position says "1";
if ($padded_bin[$k]==1){
$res[] = $words[$k];
}
}
sort($res);
$result[] = implode("_", $res);
}
sort($result);
return $result;
}
结果:
Array
(
[0] => add
[1] => bar
[2] => bar_add
[3] => car
[4] => car_add
[5] => car_bar
[6] => car_bar_add
)
您可以在内爆之前按字母顺序对数组 $res 进行排序。
限于长度3:
print_r(get_combinations("car bar add"));
function get_combinations($str) {
$words = explode(' ',$str);
$elements = pow(2, count($words))-1;
$result = array();
for ($i = 1; $i<=$elements; $i++){
$bin = decbin($i);
$padded_bin = str_pad($bin, count($words), "0", STR_PAD_LEFT);
$res = array();
for ($k=0; $k<count($words); $k++){
//break, if maximum length is reached.
if (count($res) == 3){
break;
}
//append element, if binary position says "1";
if ($padded_bin[$k]==1){
$res[] = $words[$k];
}
}
sort($res);
//check result array if combination already exists before inserting.
$res_string =implode("_", $res);
if (!in_array($res_string, $result)){
$result[] = $res_string;
}
}
sort($result);
return $result;
}
关于php - 如何返回给定字符串的所有组合? (例如 'foo bar' = bar、bar_foo、foo),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25068895/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
在我的Rails(2.3,Ruby1.8.7)应用程序中,我需要将字符串截断到一定长度。该字符串是unicode,在控制台中运行测试时,例如'א'.length,我意识到返回了双倍长度。我想要一个与编码无关的长度,以便对unicode字符串或latin1编码字符串进行相同的截断。我已经了解了Ruby的大部分unicode资料,但仍然有些一头雾水。应该如何解决这个问题? 最佳答案 Rails有一个返回多字节字符的mb_chars方法。试试unicode_string.mb_chars.slice(0,50)
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl