[英]how to find the number of repeating strings and their array index in a string array in matlab
我有一個很長的字符串數據數組(1x75000!)。 在此數組中,有重復的字符串。 我想找到數組索引和每個重復字符串的數量。 例如
A = ['abc''efg''hij''abc''hij''efg''klm']; 答案應該是:數組索引為1的'abc'的2倍,數組索引為2的'efg'的2倍,數組索引為3的'hij'的2倍,數組2的'hij'的2倍,數組索引7的'klm'的1倍
注意陣列的大尺寸(1x75000)
此代碼應工作:
<?php
$array = array('abc','wrerwe','wrewer','abc');
$out = array();
foreach ($array as $key => $value) {
if (!isset($out[$value])) {
$out[$value]['nr'] = 0;
$out[$value]['index'] = array();
}
++$out[$value]['nr'] ;
$out[$value]['index'][] = $key;
}
foreach ($out as $k => $v) {
echo "item ".$k." repeats ".$v['nr'].' times at positions: ';
echo implode(', ', $v['index']);
echo "<br />";
}
但是到目前為止,我還沒有在如此大的陣列上進行測試。 實際上,我認為您不應該在如此大的陣列上運行。 您應該將其划分為較小的數組。
我已經使用代碼在75000數組上對其進行了測試(來自如何使用PHP創建隨機字符串的源代碼):
<?php
$array = randomTexts(75000);
$out = array();
foreach ($array as $key => $value) {
if (!isset($out[$value])) {
$out[$value]['nr'] = 0;
$out[$value]['index'] = array();
}
++$out[$value]['nr'] ;
$out[$value]['index'][] = $key;
}
foreach ($out as $k => $v) {
echo "item ".$k." repeats ".$v['nr'].' times at positions: ';
echo implode(', ', $v['index']);
echo "<br />";
}
function randomTexts($nr) {
$out = array();
$validString = 'abddefghihklmnopqrstuvwzyx';
for ($i=0; $i< $nr; ++$i) {
$len = mt_rand(5,10);
$out[] = get_random_string($validString, $len);
}
return $out;
}
function get_random_string($valid_chars, $length)
{
// start with an empty random string
$random_string = "";
// count the number of chars in the valid chars string so we know how many choices we have
$num_valid_chars = strlen($valid_chars);
// repeat the steps until we've created a string of the right length
for ($i = 0; $i < $length; $i++)
{
// pick a random number from 1 up to the number of valid chars
$random_pick = mt_rand(1, $num_valid_chars);
// take the random character out of the string of valid chars
// subtract 1 from $random_pick because strings are indexed starting at 0, and we started picking at 1
$random_char = $valid_chars[$random_pick-1];
// add the randomly-chosen char onto the end of our string so far
$random_string .= $random_char;
}
// return our finished random string
return $random_string;
}
它似乎也可以工作,但是要花幾秒鍾
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.