Jump to content

Can any body help me with this question. Have to do this in php


Athul

Recommended Posts

 

Watson gives Sherlock an array A of length N. Then he asks him to determine if there exists an element in the array such that the sum of the elements on its left is equal to the sum of the elements on its right. If there are no elements to the left/right, then the sum is considered to be zero.Formally, find an i, such that, A1+A2.....Ai-1 = Ai+1+Ai+2......AN.

Link to comment
Share on other sites

How about this?

$arr = array(1,2,3,4,3,2,1);
$sz = count($arr);
foreach($arr as $k=>$v)
	echo "$k:$v,  ";
echo "<br><br>";
for ($n = 0; $n < $sz; $n++)
{
	$left = $right = 0;
	for($i = 0; $i < $n; $i++)
		$left += $arr[$i];
	for($i = $n+1; $i < $sz; $i++)
		$right += $arr[$i];
	echo "For middle #$n of {$arr[$n]} the left sum is $left and the sum right is $right";
	if ($left == $right)
		echo "***!";
	echo "<br>";
}

I believe this will satisfy your task requirements.  Hopefully it is not HOMEWORK that you decided to farm out.  I took it as a small challenge and threw this together.  If it were anything more than that I would not have done it without seeing your attempts, as Barand has asked about.

Edited by ginerjm
Link to comment
Share on other sites

or

$arr = [ 21, 12, 3 , 4, 25, 26, 14 ];
for ($i=0, $k = count($arr); $i<$k; $i++) {
    $left = array_sum(array_slice($arr, 0, $i));
    $right = array_sum(array_slice($arr, 1+$i-$k));
    if ($left == $right) $arr[$i] = "<sub>$left</sub><span style='font-weight: 600; color: red;'>$arr[$i]</span><sub>$right</sub>";
}
echo join(', ', $arr);  // show solution

image.png.d5d166e674800ec547673f955028f506.png

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.