Codility worng answer on TapeEquilibrium for php - php

I just coded a solution for the TapeEquilibrium problem in php. The thing is i`m getting some wrong answers for the automatic code revitions provided by Codility.
The link to the finished test is
https://codility.com/demo/results/demo2G35FU-EJQ/.
Any idea whats the two elements wrong answer error?
Is it necessary to type (typecast) the variables in php for this test? i mean, how do u tell the compiler X variable is double or int in php? Thx a lot!

Two elements test case is probably {-1000, 1000}. This array can be splited only in one place and the distance is |-1000-1000| = 2000. Your program for this input returns 0, because in the second iteration of the for loop $arr_h is 0 and $sum_total is also 0.
Simply change condition in loop for ($i = $count_-1; $i > 0 ; $i--) to get 100%.

"Two elements" test case is {-1000, 1000}, additional testing (if (N == 2)) can be performed to solve this issue.
"Small elements" test case should be passed after setting a starting value to tmp variable (take a look at my example) prior to entering in the second loop. My example is on C, but it can be easily implementing in other languages:
int TapeEquilibrium(int A[], int N) {
long long sum = 0;
int i = 0, j = 0;
int min = 1000;
if (N == 2) {
return abs(A[0] - A[1]);
}
for(i = 0; i < N; i++)
{
sum += A[i];
}
long long left = 0;
long long right = sum;
int tmp = abs(left - right);
for(j = 1; j < N; j++)
{
right -= A[j - 1];
left += A[j - 1];
tmp = abs(left - right);
if (min > tmp)
{
min = tmp;
}
}
return min;
}

Related

How to solve nth degree equation in php?

How to solve nth degree equations in PHP
Example:
1/(1+i)+1/(1+i)2+...1/(1+i)n=k
While k is the constant,I'd like to find value of i.
How can I achieve this in PHP?
First of all, your expression on the left is a geometric sum, so you can rewrite it as (using x=1+i)
1/x*(1+...+1/x^(n-1)) = 1/x * (1-1/x^n)/(1-1/x) = (1-x^(-n))/(x-1)
and consequently the equation can be rewritten as
(1 - pow( 1+i, -n))/i = k
Now from the original expression one knows that the left side as a sum of convex monotonically decreasing functions is equally so, thus any of bisection, regula falsi variants or secant method will work sufficiently well.
Use
(1+i)^(-n)=1 - n*i + (n*(n+1))/2*i^2 +...
to get the approximative equation and first approximation
1-(n+1)/2*i = k/n <=> i = (1-k/n)*2/(n+1)
so that you can start bracketing method with the interval from 0 to twice this i.
Try something like this....
$n = 5;
$i = 2;
$k = null;
for ($x = 1; $x <= $n; $x++) {
$k += 1 / pow((1 + $i), $x);
}
echo $k; //Answer --> 0.49794238683128

Thinking Process of an algorithm of find the missing element in a given permutation from Codility

I found this perfect answer for the Codility's PermMissingElem Question.
function solution($A) {
$N = count($A);
$sum = ($N + 2) * ($N + 1) / 2;
for($i = 0; $i < $N; $i++){
$sum -= $A[$i];
}
return intval($sum);
}
However I found its puzzled for me regarding the $sum's function. What kind of function is this? It's amazingly correctly, yet, how come someone could make up such function? Is there anyone can somehow reverse engineer the thinking process?
I really want to know the process how it came about.
Thank You !
The sum of integers from 1 to N can be calculated by this formula:
N(N+1)/2
Basically, you take the first number and the last number and add them together, and then the second number and the second to last number..etc.
For example:
The sum of 1 to 100:
(1+100) + (2+99) + (3+98) + (4+97) ...
= (100/2)(101)
= 50 x 101
Here's a good explanation:
http://www.wikihow.com/Sum-the-Integers-from-1-to-N

Convert septet to octet in php

I need to convert septets to octest like this c example:
private void septetToOctet()
{
int len = 1;
int j = 0;
int septetcount = septet.Count;
while (j < septet.Count - 1)
{
string tmp = septet[j]; // storing jth value
string tmp1 = septet[j + 1]; //storing j+1 th value
string mid = SWAP(tmp1);
tmp1 = mid;
tmp1 = tmp1.Substring(0, len);
string add = SWAP(tmp1);
tmp = add + tmp;// +"-";
tmp = tmp.Substring(0, 8);
//txtoctet.Text += tmp + " || ";
octet.Add(tmp);
len++;
if (len == 8)
{
len = 1;
j = j + 1;
}
j = j + 1;
}
}
..only problem is - i need to do it in php. Does anybody have an code example for this ?
Most of the code can be translated to PHP with little changes. For instance, the first two assignments would be just $len = 1 and $j = 0. There is no strong static typing in PHP.
Since numbers and strings are scalars in PHP, you cannot call methods on them, so you cannot do tmp1.substring but would have to do substr($tmp1, …).
septet and octet would be arrays in PHP. Again, there is no methods on arrays in PHP. To add to an array, you simply do $octet[] = $tmp. To count the elements you do count($septet).
There is no SWAP in PHP, but you can derive the rather trivial function from Is there a built in swap function in C?
These hints should get you closer to a working implementation.

Find the missing number in the given array of numbers using PHP

Am new to php i have faced an interview some days ago, and the interviewer asked a question like the following one.
The given array has 99 numbers, which contains the digits from 1 to 100
with one digit missing. Describe two different algorithms that finds you the missing number. The algorithm should optimize for low storage and fast processing. Output should show the execution time of each algorithm.
And i have searched google about it, and come to know its a common puzzle used to ask in interviews. I found out the answer like this way.
int sum = 0;
int idx = -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
idx = i;
} else {
sum += arr[i];
}
}
// the total sum of numbers between 1 and arr.length.
int total = (arr.length + 1) * arr.length / 2;
System.out.println("missing number is: " + (total - sum) + " at index " + idx);
But the code is not in php,
Can u please help me to find out the php code and algorithm name. So i can improve my answer in the next interviews.
In PHP you can easily use some array functions and achieve that. Best way is,
$missing = array_diff(range(1,100),$array);
DEMO.
Another way to do it is by using the array_sum function and the knowledge that all numbers from 1 to 100 added together equals 5050.
$missing = 5050-array_sum($array);
Converted to PHP, it is nearly the same.
(Not tested)
Of course, there are better ways, like the one Rikesh posted, but this is the exact one you asked for:
$sum = 0
$idx = -1
for($i = 0; $i < count($arr); $i++){
if($arr[$i] == 0){
$idx = $i;
}else{
$sum += $arr[$i];
}
}
$total = (count($arr) + 1) * (count($arr) / 2);
echo "Missing: " . ($total - $sum) . " at index " . $idx;
$arr=range(1,99);
$j=1;
for($i=0;$i<100;$i++){
if(!in_array($j,$arr)){
echo $j.'is missing';
}
$j++;
}

looping in two directions

hey I'm looking for are clean solution to this problem:
i start the loop with i = 0 in the second loop step the i = 1, then i = -1 and then i = 2 ect.
how to programm this with a for loop in a clean way?
f(0); //do stuff with 0
for(var i = 1; i<len; i++) //where len = positive boundary
{
f(i); //do stuff with i
f(-i); //do stuff with -i
}
Should do what you want
If you don't mind having the inner loop appear 3 times:
f(0);
for (var i = 1; i <= 3; ++ i) {
f(i);
f(-i);
}
2 times with an if:
for (var i = 0; i <= 3; ++ i) {
f(i);
if (i > 0)
f(-i);
}
single time but with an ugly expression:
for (var j = 1; j <= 7; ++ j) {
var i = j / 2;
if (j % 2) i = -i;
f(i);
}
Each loop, you appear to be adding n*(-1)^(n+1), where n is the step you are currently taking, starting at 1, and starting at i=0.
initialize i = 0
n=0, i+=0*(-1)^1 # 0
n=1, i+=1*(-1)^2 # 1
n=2, i+=2*(-1)^3 # -1
n=3, i+=3*(-1)^4 # 2
etc.
From here, it depends on what language you would wish to write in. Iterate from n = 0 to wherever you are stopping.
edit this is a bad answer. but fun =D
(I added that last bit because as soon as I made that edit, someone downvoted me =( )
Here is implementation in javascript
for ( var i = 0; Math.abs(i)<10; i=(i<=0?Math.abs(i)+1:-i)) {
console.debug(i)
}
Hope it helps.
Just one addition one subtraction and a negation:
for(int i=0, d=1, f=-1; i<10; i+=d, d=f-d, f=-f)
{
printf("%d\n", i);
}
generates an inner loop of:
push esi
push offset string "%d\n" (0D20F4h)
call dword ptr [__imp__printf (0D20A4h)]
mov eax,ebx
add esi,edi
sub eax,edi
add esp,8
neg ebx
mov edi,eax
cmp esi,0Ah
jl wmain+10h (0D1010h)
I used the sine function:
for ($i = 0; $i < 10; $i++)
{
echo round(0.5 * $i * sin((0.5 + $i) * M_PI))."\n";
}
for (int i = 0; i < 10; i++)
{
int div = i / 2;
int mod = i % 2;
int offset = mod == 0 ? div : -div;
}
There is a pattern to this loop. Looking at it on the number line - it goes like:
0 steps backward
1 step forward
2 steps backward
3 steps forward
4 steps backward
Here's one solution - keep incrementing the step size in each iteration of the loop, and flip direction (forward/backward) every time. Keep adding to the current value.
// n is the number of elements to generate
for(var i = 0, value = 0, dir = -1; i < n; i++) {
value = value + (dir * i);
console.log(value);
dir = dir * -1; // reverse direction
}
Another solution using generators in JavaScript 1.7 which is identical to #FallingBullet's solution but more aesthetically pleasing to my eye :)
function sequence() {
var i = 0;
yield i;
while(true) {
i++;
yield i;
yield -i;
}
}
var seq = sequence();
seq.next(); // 0
seq.next(); // 1
seq.next(); // -1
seq.next(); // 2
...
For what it's worth, here is my own interpretation of the problem.
for (var i = 0; i > -8; i = (i<=0) - i) // arbitrary condition stops loop at -8
A modification of falling bullet's solution, that will handle the 0 index case without a special condition.
//do stuff with 0
for(int i = 0; i< (arrayLength/2); i++)
{
//do stuff with i
if(-i != i)
{
//do stuff with negIndex
}
}
In C. The value of N is the total number of values in the sequence you wish to yield.
int i, n = 0, m = 1;
for (i = 1; i < N; i++, m = -m) {
/* n is the next in the sequence */
n += m * i;
}
I'd probably go with:
for (var i = 0; i <= max; i = ( i <= 0 ) ? -i + 1 : -i)
{
f( i );
}

Categories