there is a function in C# (the main task of the function with an example ) :
Int32[] Spiral_Min(Int32[, ] arr) {
List <Int32> list = new List <Int32> ();
Int32 n = arr.GetLength(0);
Int32 count = n;
Int32 value = -n;
Int32 sum = -1;
do {
value = -1 * value / n;
for (Int32 i = 0; i < count; i++) {
sum += value;
list.Add(arr[sum / n, sum % n]);
}
value *= n;
count--;
for (Int32 i = 0; i < count; i++) {
sum += value;
list.Add(arr[sum / n, sum % n]);
}
} while (count > 0);
return list.ToArray();
}
I'm trying to do the same in PHP, but i ran into a problem in the code, there is a string:
arr[sum / n, sum % n]
I do not understand how to do this in PHP, tried it through array_merge
, but the function still doesn't work.
function f($a)
{
$n = count($a[0]);
$count = $n;
$value = -$n;
$sum = -1;
do
{
$value = -1 * $value / $n;
for ($i = 0; $i < $count; $i++) {
$sum += $value;
$r[] = array_merge($a[$sum / $n], $a[$sum % $n]);
}
$value *= $n;
$count--;
for ($i = 0; $i < $count; $i++) {
$sum += $value;
$r[] = array_merge($a[$sum / $n], $a[$sum % $n]);
}
}
while ($count > 0);
return $r;
}
Please tell me what the problem is and how to do it right?
Assuming $arr
is a two dimensional array, you can access elements from the arrays using $arr[$index1][$index2]
notation. Thus:
arr[sum / n, sum % n]
Would become:
$arr[$sum / $n][$sum % $n]
You can use array_push. Like below:
function f($a)
{
$n = count($a);
$count = $n;
$value = -$n;
$sum = -1;
$r = [];
do
{
$value = -1 * $value / $n;
for ($i = 0; $i < $count; $i++) {
$sum += $value;
array_push($r, $a[$sum / $n], $a[$sum % $n]);
}
$value *= $n;
$count--;
for ($i = 0; $i < $count; $i++) {
$sum += $value;
array_push($r, $a[$sum / $n], $a[$sum % $n]);
}
}
while ($count > 0);
return $r;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.