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++;
}
Related
My task, using php, is to create a random number, then make that number multiply itself. However i cannot use the multiply operator (*) and have been told to create a for loop instead however I'm having some troubles.
$startNum = rand(1,10);
for ($i = $startNum; $i <= 10; $i++)
{
echo $i;
}
This is what i have so far, however this is completely wrong and will only get a random number and count to 10 from it.
Any help would be very appreciated, thanks.
When squaring you are just multiplying a number by itself, another way to do this is through addition, add a number to itself x amount of times. So, with 4 squared, that is 4 * 4 or, 4 + 4 + 4 + 4.
Doing this in a for loop should be as simple as
$startNum = rand(1,10);
$endNum = 0;
for ($i = 0; $i < $startNum; $i++)
{
$endNum += $startNum;
}
echo $endNum;
Caveat: I don't program Php so forgive syntax errors.
$startNum*$startNum means that the loop should loop $startNum times and in each iteration add $startNum, i.e., the number itself
$s = 0;
for($i=1;$i<=$startNum;$i++){
$s += $startNum;
}
echo $s;
Still not using the multiplication operator :p
$n = mt_rand(1, 10);
echo array_sum(array_fill(0, $n, $n));
you can do this by simple addition(+) operator
square means add that number into same number for same time.
example : square of 2 means : 2+2;
square of 4 means : addition of 4 with 4 for 4 times : 4+4+4+4
so you can do like that
$startNum = rand(1,10);
$ans=0;
for ($i = 0 ;$i < $startNum; $i++)
{
echo $ans+=$startNum;
}
I am trying to implement the BBP algorithm in php. My code is returning a decimal which i thought was odd as it should be in hex. I was told to convert to decimal from hex by multiplying by 16 also but now its all just wrong. Here is a sample:
$n1=$n2=$n3=$n4=$n5=$n6=$n7=$n8 =0;
$S1=$S2=$S3=$S4=$S5=$S6=$S7=$S8 = 0; //initializing
$k = 0;
$m1= 8*$k + 1;
$m2 = 8*$k + 4;
$m3 = 8*$k + 5;
$m4 = 8*$k = 6;
$b =16;
$e=$n-$k;
while($k<$n){ //Sum 1 of 8
$S1 +=Modular($b, $m1, $e)/$m1; //see Moduler_Expansion.php
$k++;
}
$k = $n +1; //redefine for second sum, and every other
while($k<$limit){ //Sum 2 of 8
$S2 += (pow($b,$n-$k))/($m1);
$k++; //now repeat similar process for each sum.
}
and I repeat the process for each term of BBP then:
$S = 4*($S1 + $S2) - 2*($S3+$S4) -($S5+$S6) - ($S7+$S8);
`
Following the wiki page I then strip the integer and multiply by 16, but for $k =0 I get; 3.4977777777778
and for $k = 1: 7.9644444444448.
I dont think these are right, it could just be i do not know how to interpret th ouput properly. Can anyone offer any advice?
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
I need to find a (the next) fibonacci number given a integer N. So let's say I have n = 13 and I need to output the next fibonacci number which is 21 but how do I do this? How can I find the previous number that summed up to form it?
I mean I could easily come up with a for/while loop that returns the fibonacci sequence but how can I find the next number by being given the previous one.
<?php
$n = 13;
while($n < 1000) {
$n = $x + $y;
echo($n."<br />");
$x = $y;
$y = $n;
}
?>
You can use Binet's Formula:
n -n
F(n) = phi - (-phi)
---------------
sqrt(5)
where phi is the golden ratio (( 1 + sqrt(5) ) / 2) ~= 1.61803...
This lets you determine exactly the n-th term of the sequence.
Using a loop you could store the values in an array that could stop immediately one key after finding the selected number in the previous keys value.
function getFib($n) {
$fib = array($n+1); // array to num + 1
$fib[0] = 0; $fib[1] = 1; // set initial array keys
$i;
for ($i=2;$i<=$n+1;$i++) {
$fib[$i] = $fib[$i-1]+$fib[$i-2];
if ($fib[$i] > $n) { // check if key > num
return $fib[$i];
}
}
if ($fib[$i-1] < $n) { // check if key < num
return $fib[$i-1] + $n;
}
if ($fib[$i] = $n-1) { // check if key = num
return $fib[$i-1] + $fib[$i-2];
}
if ($fib[$i-1] = 1) { // check if num = 1
return $n + $n;
}
}
$num = 13;
echo "next fibonacci number = " . getFib($num);
Please note that I haven't tested this out and the code could be optimized, so before downvoting consider this serves only as a concept to the question asked.
You can do it in 1 step:
phi = (1+sqrt(5))/2
next = round(current*phi)
(Where round is a function that returns the closest integer; basically equivalent to floor(x+0.5))
For example, if your current number is 13: 13 * phi = 21.034441853748632, which rounds to 21.
I need to generate x amount of random odd numbers, within a given range.
I know this can be achieved with simple looping, but I'm unsure which approach would be the best, and is there a better mathematical way of solving this.
EDIT: Also I cannot have the same number more than once.
Generate x integer values over half the range, and for each value double it and add 1.
ANSWERING REVISED QUESTION: 1) Generate a list of candidates in range, shuffle them, and then take the first x. Or 2) generate values as per my original recommendation, and reject and retry if the generated value is in the list of already generated values.
The first will work better if x is a substantial fraction of the range, the latter if x is small relative to the range.
ADDENDUM: Should have thought of this approach earlier, it's based on conditional probability. I don't know php (I came at this from the "random" tag), so I'll express it as pseudo-code:
generate(x, upper_limit)
loop with index i from upper_limit downto 1 by 2
p_value = x / floor((i + 1) / 2)
if rand <= p_value
include i in selected set
decrement x
return/exit if x <= 0
end if
end loop
end generate
x is the desired number of values to generate, upper_limit is the largest odd number in the range, and rand generates a uniformly distributed random number between zero and one. Basically, it steps through the candidate set of odd numbers and accepts or rejects each one based how many values you still need and how many candidates still remain.
I've tested this and it really works. It requires less intermediate storage than shuffling and fewer iterations than the original acceptance/rejection.
Generate a list of elements in the range, remove the element you want in your random series. Repeat x times.
Or you can generate an array with the odd numbers in the range, then do a shuffle
Generation is easy:
$range_array = array();
for( $i = 0; $i < $max_value; $i++){
$range_array[] .= $i*2 + 1;
}
Shuffle
shuffle( $range_array );
splice out the x first elements.
$result = array_slice( $range_array, 0, $x );
This is a complete solution.
function mt_rands($min_rand, $max_rand, $num_rand){
if(!is_integer($min_rand) or !is_integer($max_rand)){
return false;
}
if($min_rand >= $max_rand){
return false;
}
if(!is_integer($num_rand) or ($num_rand < 1)){
return false;
}
if($num_rand <= ($max_rand - $min_rand)){
return false;
}
$rands = array();
while(count($rands) < $num_rand){
$loops = 0;
do{
++$loops; // loop limiter, use it if you want to
$rand = mt_rand($min_rand, $max_rand);
}while(in_array($rand, $rands, true));
$rands[] = $rand;
}
return $rands;
}
// let's see how it went
var_export($rands = mt_rands(0, 50, 5));
Code is not tested. Just wrote it. Can be improved a bit but it's up to you.
This code generates 5 odd unique numbers in the interval [1, 20]. Change $min, $max and $n = 5 according to your needs.
<?php
function odd_filter($x)
{
if (($x % 2) == 1)
{
return true;
}
return false;
}
// seed with microseconds
function make_seed()
{
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 100000);
}
srand(make_seed());
$min = 1;
$max = 20;
//number of random numbers
$n = 5;
if (($max - $min + 1)/2 < $n)
{
print "iterval [$min, $max] is too short to generate $n odd numbers!\n";
exit(1);
}
$result = array();
for ($i = 0; $i < $n; ++$i)
{
$x = rand($min, $max);
//not exists in the hash and is odd
if(!isset($result{$x}) && odd_filter($x))
{
$result[$x] = 1;
}
else//new iteration needed
{
--$i;
}
}
$result = array_keys($result);
var_dump($result);