I was practicing a problem on CodeChef.com.
https://www.codechef.com/problems/CHOPRT --> Link to the question I was solving.
I successfully solved the question using C.
My C code:
#include <stdio.h>
int main() {
int t;
int num1;
int num2;
scanf("%d", &t);
while(t--) {
scanf("%d %d", &num1, &num2);
if(num1 > num2)
printf(">");
else if(num1 < num2)
printf("<");
else
printf("=");
printf("\n");
}
return 0;
}
But I am not able to solve it using PHP:
My PHP code:
<?php
$t = intval(fgets(STDIN));
while($t--) {
$line = split(" ", trim(fgets(STDIN)));
$num1 = intval($line[0]);
$num2 = intval($line[1]);
if($num1 < $num2)
print("<");
else if($num1 > $num2)
print(">");
else
print("=");
print("\n");
}
?>
Though both the programs run perfectly on my MacBook Pro, the PHP code is not run on codechef.com and gives a WA(Wrong Answer). C code is run perfectly though and that to within 0.00 seconds.
Please, enlighten me with the difference between the two respective codes, which I personally believe, should be working the same, and also produce the same output.
Often i hear that some testcases are erroneous.I have a corner case for you which would give perfect result for your C code but not for your PHP
Do this :
1
10 10
Notice there is more than one space between the two digits.
I tested it here.
Instead of the expected output which is:
=
your Output is:
>
Though C would pass this test case as scanf searches for the next integer number you type, PHP would fail since there is more than one space.
To make it work in PHP i did suggest you to code in such a way that the spaces between the two numbers dont affect your expected output.
That's the only way i believe your PHP Code won't work.If this indeed was the issue it's not your fault!
Related
i am using this code
<?php
function random()
{
return rand(1111111111,9999999999);
};
for ($x = "1";$x <= "5";$x++)
{
echo $x." : ".random()."<br>";
};
echo "<hr>";
?>
some outputs :
1 : 1303960718
2 : 1308203081
3 : 1280148745
4 : 1263151923
5 : 1124814399
i tried generating more numbers and all of it starts with 1
i tried to used rand() directly and the same thing happend
Run this code and you will get your answer yourself
return rand(2147483647,9999999999);
Then try running
echo getrandmax();
Depending upon your system you might get something like 2147483647
That means your upper limit is pretty much useless beyond that number. And on certain systems that max can even be lower than that. You also have to research about integer overflow.
Now if you were to go easy on your system and remove 1 digit from your number and make the new range
return rand(111111111,999999999);
Then your code would work just fine, because there are no overflows.
I have two apps one written in php and one in python and both of them use the same mysql database.
For the public id of the entries in some of the tables I use binary(16) fields(I can't change this, it must remain this way).
The question is how does python does the conversion of this binary field?
Let's take one of the entries as an example.
When I get it in php(from the db) the value of the public id is °•WiCÄ‘õ0Iò|–g, the same value is shown in SequelPro. But php myAdmin does a hex function over binary fields and shows 0bb09557691443c491f53049f27c9667. Now I managed in php to convert the binary to the value showed in php myAdmin and it works for all the entries but I've just noticed that python does another conversion. When I get the entry used in this example via python the public id is owwweye1rjnvt3i1d0ib18x3.
What I need to achieve is to convert in php what I get from MySql: °•WiCÄ‘õ0Iò|–g to what python sees: owwweye1rjnvt3i1d0ib18x3. The php app makes calls on the python one(not developed by me) and thus the id needs to be in the same format for a successfull call.
Any suggestions are welcomed. Thanks.
EDIT: If i send °•WiCÄ‘õ0Iò|–g from php to python and print it rigth away I get: °•WiCÄ‘õ0Iò|–g
Finally I've sorted this out.
Seems that python converts to base36 not hex as I've wrongly supposed.
I've tried to simply base_convert 0bb09557691443c491f53049f27c9667 from 16 to 36 but I've got owwweye1rk04k4cskkw4s08s. Not really what I needed but still a great step further as it started to look like owwweye1rjnvt3i1d0ib18x3.
This difference I supposed to appear because of the large values to be converted(loss of precision), so I've further researched and found the bellow function, written by Clifford dot ct at gmail dot com on the php.net website:
<?php
function str_baseconvert($str, $frombase=10, $tobase=36) {
$str = trim($str);
if (intval($frombase) != 10) {
$len = strlen($str);
$q = 0;
for ($i=0; $i<$len; $i++) {
$r = base_convert($str[$i], $frombase, 10);
$q = bcadd(bcmul($q, $frombase), $r);
}
}
else $q = $str;
if (intval($tobase) != 10) {
$s = '';
while (bccomp($q, '0', 0) > 0) {
$r = intval(bcmod($q, $tobase));
$s = base_convert($r, 10, $tobase) . $s;
$q = bcdiv($q, $tobase, 0);
}
}
else $s = $q;
return $s;
}
?>
I don't think others will come across this issue very often, but still if it happens hope they'll find this instead of burning their brains out like I did :))))
I found this code snippet for PHP and Javascript, but I was wondering if it could be made work in classic asp? Here's a whole article on the topic for reference.
http://24ways.org/2010/calculating-color-contrast/
PHP code
function getContrast50($hexcolor){
return (hexdec($hexcolor) > 0xffffff/2) ? 'black':'white';
}
Well, nothing built into the language. Converting hex to decimal is as easy as CLng("&H" & hexValue) but from quick look in the PHP manual I saw that hexdec() method ignores any invalid characters, while the VBScript CLng() will just crash.
So here is a working function that as far as I can tell doing the same thing:
Function GetContrast50(hexColor)
Const strValidChars = "1234567890abcdef"
Dim maxValue, decValue, sanitizedColor
Dim x, curChar
sanitizedColor = ""
For x=1 To Len(hexColor)
curChar = LCase(Mid(hexColor, x, 1))
If InStr(strValidChars, curChar)>0 Then
sanitizedColor = sanitizedColor & curChar
End If
Next
If Len(sanitizedColor)=0 Then
GetContrast50 = "invalid color string"
Exit Function
End If
maxValue = CLng("&H" & "ffffff")
decValue = CLng("&H" & sanitizedColor)
If decValue > (maxValue / 2) Then
GetContrast50 = "black"
Else
GetContrast50 = "white"
End If
End Function
It's pretty easy to extend the validation to check the given string is in valid range.
A site I'm working on (which I inherited...I don't know javascript that well) has code currently set up to display ".00" at the end of any number in the database (a PHP include page, actually) such that it displays as currency on an online form.
My client now wants to add an amount to the list which includes cents ($5.50), and I need help modifying or amending the script so I can include these non-whole currency amounts.
Here is the snippet of the script that (I think/presume) addresses the currency formatting:
function CurrencyFormatted(amount)
{
var i = parseFloat(amount);
if(isNaN(i)) { i = 0.00; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
i = parseInt((i + .005) * 100);
i = i / 100;
s = new String(i);
if(s.indexOf('.') < 0) { s += '.00'; }
if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
s = minus + s;
return s;
}
Is there a way to add to or change this code so that I can display the specific cents needed for this one (and future similar) amounts?
That code is doing some interesting rounding things, which I can't really address, but to format a number with a fixed number of digits to the right of the decimal, use the toFixed function on numbers:
var n = 1.2345;
n.toFixed(2); // "1.23"
Note that it does rounding, so:
(1.234).toFixed(2); // "1.23"
(1.235).toFixed(2); // "1.24"
(You don't need the parens when you're calling toFixed on a variable, but you do need them when calling it on a literal as I did in the two examples above. Naturally, in your case, you'll be using a variable so no need for them.)
Re your comment/question below:
Thanks for the quick replies! I guess I should have said I don't know javascript AT ALL, so my questions are: 1) where do I insert the codes you offer above into my existing code...
1) The code you quoted in your question is doing a bunch of operations on the number fed into it, including adding half a cent to it before trying to round it to two digits (in a very non-optimal way). If the goal now is to faithfully reproduce a rounded-to-two-digits version of the number fed in (none of this adding half-a-cent stuff), you can replace the entire function with this:
function CurrencyFormatted(amount)
{
return parseFloat(amount).toFixed(2);
}
If you want to continue adding half a cent to it:
function CurrencyFormatted(amount)
{
return (parseFloat(amount) + 0.005).toFixed(2);
}
...and 2) will this allow all of my existing other numbers to continue displaying as they are (e.g. "25" in my include file displays as "25.00")?
Any number (or numeric string) you feed into the above will be formatted with two digits to the right of the decimal, even if those digits are 00. So with the above, CurrencyFormatted("25") will return "25.00".
...Or do I use this code you suggest to replace part or all of the sample code I posted, and thus, would I then need to change all my database numbers to accommodate this? (i.e. should I add two zeros to the end of all my whole numbers now? (25 becomes 2500, etc.)
You don't need to add .00 to whole numbers in the database or anything like that.
If you wanted todo this with PHP checkout money_format() heres an example:
<?php
$value = 5;
setlocale(LC_MONETARY, 'en_US');
echo '$'.money_format('%i', $value) . "\n";//$5.00
$value = 5.545;
setlocale(LC_MONETARY, 'en_US');
echo '$'.money_format('%i', $value) . "\n";//$5.54
$value = 9.99;
setlocale(LC_MONETARY, 'en_US');
echo '$'.money_format('%i', $value) . "\n";//$9.99
?>
There is a problem in Interview Street challange. Maybe the most easiest of all challenges. "Unfriendly Numbers", is the name and question goes like this.
There is one friendly number and N unfriendly numbers. We want to find how many numbers are there which exactly divide the friendly number, but does not divide any of the unfriendly numbers.
Input Format:
The first line of input contains two numbers N and K seperated by spaces. N is the number of unfriendly numbers, K is the friendly number.
The second line of input contains N space separated unfriendly numbers.
Output Format:
Output the answer in a single line.
I did a PHP programming like this:
<?php
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
$handle = fopen ("php://stdin","r");
$input = fgets($handle);
$num_unfriendly_number=substr($input,0,1);
$friendly_number=substr($input,2,1);
$input2=fgets($handle);
for($i=0;$i<=($num_unfriendly_number); $i=$i+2){
$unfriendly_numbers[$i]=substr($input2,$i,1);
}
//truncates additional input
//now getting divisiors of given friendly numbers
$check_num=1;
//one is always a divisor of any number
$divisior[0]=1;
$arrayindex=1;
for($check_num; $check_num<=$friendly_number; $check_num++){
$hold_var=$friendly_number%$check_num;
if($hold_var==0){
$divisor[$arrayindex]=$check_num;
$arrayindex++;
}
}
$index=0;
foreach($divisor as $test_div){
$output=true;
foreach($unfriendly_numbers as $test_unfrnd){
if($test_unfrnd%$test_div){
$output=false;
}
}
if ($output){
$outputarray[$index]=$test_div;
$index++; //edited afterwards after #Boris's suggestion but didn't work :(
}
}
$num_of_output=count($outputarray);
define('STDOUT',fopen("php://stout","r"));
fwrite(STDOUT,$num_of_output);
?>
The above programme worked fine for 2 testcases but did not applied for other tests. I did some research but did not found any errors. Any helps please. Thanks in advance.
Fist of all I would like to mention that I do not know php. However, I think this is simple enough I can try to help.
Several errors I see:
for($i=0;$i<=($num_unfriendly_number); $i=$i+2){
$unfriendly_numbers[$i]=substr($input2,$i,1);
}
Here you use substr($input2,$i,1);, this however assumes all your unfriendly numbers are digits, which might not always be the case. Better use the split function in php. Replace the whole while with the following:
$unfriendly_numbers = explode(" ", $input2);
After that:
$index=0;
foreach($divisor as $test_div){
$output=true;
foreach($unfriendly_numbers as $test_unfrnd){
if($test_unfrnd%$test_div){
$output=false;
}
}
if ($output){
$outputarray[$index]=$test_div;
}
}
Here you never increase the $index variable. Isn't this meaning that you will override the divisors one with other? USe the operator []=. It appends to an array in php:
if ($output){
$outputarray []= $test_div;
}
EDIT One more error I see is that you count on the friendly number to be a digit too. You can fix this too:
$friendly_number=substr($input,2,1);
->
$friendly_number=explode(" ", $input)[0];
I have the same problem I can't understand why this code can't finish in less than 16 seconds!
I would like to hear your tricks
a = raw_input()# this will read this line: 8 16
b = raw_input()# this will read this line: 2 5 7 4 3 8 3 18
al = a.split()
bl = b.split()
blint = []
fn = int(al[1])
fnlist = [fn]
half_fn = fn / 2 # only I go to half the number to save some time
k = 1
while k <= half_fn:
if fn % k == 0:
fnlist.append(k)
k += 1
plist = []
for j in bl:
blint.append(int(j)) # here I changed the bl list elements which are string to int
for i in fnlist:
for j in blint: #I have the int elements so I don't need every time bring the string and change it to int
if j % i == 0:
plist.append(i)
break
counter = len(fnlist) - len(plist)
print counter