I'm a fan of Bitcoins and all other alternative coins, so what I am trying to make is a page with all my coins I own, and shows the latest value of each coin.
So what I've got so far is a cURL that gets the content of a website, in this case it is cryptorush.in.
The output of the cURL is:
21 / BTC
13.22000001
42 / BTC
112.10000000
Etc.
So I thought it would be a nice way to recognize "21 / BTC" for example and read the latest value at the next line.
$curlPage is my cURL page.
if (strpos($curlPage,'21 / BTC') !== false) {
//do something
}
Output:
13.22000001
But I really have no idea on how to do this, so I hope anyone could answer my question.
You can use a combination of regexp and the explode function. Please note that this is dependent upon the actual coding of the page you are requesting with cURL, as I am looking at the values being exploded by two returns - \n\n
$curlPage = "21 / BTC \n13.22000001\n\n42 / BTC \n112.10000000";
$arr = explode("\n\n", $curlPage);
foreach($arr as $key)
{
list($top, $bottom) = explode("\n", $key);
$top = preg_replace("/[^0-9]/", "", $top);
if($top == "21") echo($bottom);
}
The first line shows what my value for $curlPage is (for testing it). This should be equal to the contents of the page (provided the contents are what you posted and each section is separated by two line breaks (\n\n)
The two important variables in the foreach() statement is $top and $bottom. $top will be equal to the number, like 21. And the $bottom variable will be equal to the bottom number like 13.22000001
Related
I have started to practice coding problems (hackerearth.com) in PHP to increase my problem-solving skill.
As I saw, most of the coding problems are asked for taking input and then output the correct answer based on entered input.
Eg : Input-
The first line consists of two integers N and
K, N being the number of elements in the array and K denotes the
number of steps of rotation.
The next line consists of N space
separated integers , denoting the elements of the array A.
Till now, I know -
fscanf(STDIN, "%d %d\n", $n, $k); //takes N and K
But I don't know how to take an array of size N.
Please help me how to take array of size N. Then It will help me to code further. Else I will just stuck on taking input.
EDIT:
Please help me any PHP pro coder.
EDIT 2:
The problem on which I am still stuck is given below -
Coding challenge -
Monk and Rotation
Monk loves to preform different operations on arrays, and so being the principal of Hackerearth School, he assigned a task to his new student Mishki. Mishki will be provided with an integer array A of size N and an integer K , where she needs to rotate the array in the right direction by K steps and then print the resultant array. As she is new to the school, please help her to complete the task.
EDIT 3 -
Problem can be found here.
What I have tried till know to solve this problem-
fscanf(STDIN, "%s\n", $t);
fscanf(STDIN, "%s %s\n", $n, $k);
//taking 5 numbers seperated by space.
fscanf(STDIN, "%d %d %d %d %d\n", $item1,$item2,$item3,$item4,$item5);
$arr = [$item1,$item2,$item3,$item4,$item5];
for($i = 0; $i<$k; $i++){
array_unshift($arr, array_pop($arr));
}
echo implode(' ', $arr);
You could use readline to read in the space-separated integers, then just split at the spaces to get an array. Note that the array elements will be of type string.
// input string
$string = readline();
// turn into an array
$array = explode(" ", $string);
In hackerearth for PHP you can do something like this -
function getMyInput($n)
{
echo '<pre>';
print_r($n);
}
$t = fgets(STDIN);
for ($t_itr = 0; $t_itr < $t; $t_itr++) {
$n[] = fgets(STDIN);
}
getMyInput($n);
Reference link
PHP standard input?
What does this code mean "ofstream fout(getenv("OUTPUT_PATH"));"
https://www.php.net/manual/en/function.fgets.php
https://www.php.net/manual/en/function.intval.php
Explanation
Use fgets to read a line from the input using STDIN (I/O reading)
then iterate from zero to the maximum provided INPUT and assign those values into a variable.
create a custom method and pass the I/O data (array variable) as an argument to make your own logic for problem-solving.
I have scraped 5000 files, stored them in individual files (0-4999.txt), now i need to find duplicate content in them. so i am comparing each file with one another in nested loop (ETA 82 hours). This approach will definitely take hours to complete. My main concern here is the no. of iterations. Can anyone suggest a better approach to cut down iterations and reduce time taken?
current code: NCD algorithm
function ncd_new($sx, $sy, $prec=0, $MAXLEN=9000) {
# NCD with gzip artifact correctoin and percentual return.
# sx,sy = strings to compare.
# Use $prec=-1 for result range [0-1], $pres=0 for percentual,
# For NCD definition see http://arxiv.org/abs/0809.2553
$x = $min = strlen(gzcompress($sx));
$y = $max = strlen(gzcompress($sy));
$xy= strlen(gzcompress($sx.$sy));
$a = $sx;
if ($x>$y) { # swap min/max
$min = $y;
$max = $x;
$a = $sy;
}
$res = ($xy-$min)/$max; # NCD definition.
if ($MAXLEN<0 || $xy<$MAXLEN) {
$aa= strlen(gzcompress($a.$a));
$ref = ($aa-$min)/$min;
$res = $res - $ref; # correction
}
return ($prec<0)? $res: 100*round($res,2+$prec);
}
looping over each file:
$totalScraped = 5000;
for($fileC=0;$fileC<$totalScraped;$fileC++)
{
$f1 = file_get_contents($fileC.".txt");
$stripstr = array('/\bis\b/i', '/\bwas\b/i', '/\bthe\b/i', '/\ba\b/i');
$file1 = preg_replace($stripstr, '', $f1);
// 0+fileC => exclude already compared files
// eg. if fileC=10 , start loop 11 to 4999
for($fileD=(0+$fileC);$fileD<$totalScraped;$fileD++)
{
$f2 = file_get_contents($fileD.".txt", FILE_USE_INCLUDE_PATH);
$stripstr = array('/\bis\b/i', '/\bwas\b/i', '/\bthe\b/i', '/\ba\b/i');
$file2 = preg_replace($stripstr, '', $f2);
$total=ncd_new($file1,$file2);
echo "$fileName1 vs $fileName2 is: $total%\n";
}
}
You may want to find a way to distinguish likely candidates from unlikely ones.
So, maybe there is a way that you can compute a value for each file (say: a word count, a count of sentences / paragraphs... maybe even a count of individual letters), to identify the unlikely candidates beforehand.
If you could achieve this, you could reduce the amount of comparisons by ordering your arrays by this computed number.
another process that i tried was:
strip html tags from page
replace \s{2,} with \s, \n{2,} with \n, so that text b/w each tag is presented in a single line(almost)
compare two such generated files by taking a line, preg_matching, if found -> duplicate, else break line into array of words, calculate array_intersect, if count is 70% or more of line length -> duplicate.
which was very efficient and i could compare 5000 files in ~10 minutes
but still slow for my requirements.
So i implemented the first logic "ncd algo" method in C language, and it completes the task with 5-10 seconds (depending on the average page size)
I have been reading/testing examples since last night, but the cows never came home.
I have a file with (for example) approx. 1000 characters in one line and want to split it into 10 equal parts then write back to the file.
Goal:
1. Open the file in question and read its content
2. Count up to 100 characters for example, then put a line break
3. Count 100 again and another line break, and so on till it's done.
4. Write/overwrite the file with the new split content
For example:
I want to turn this => KNMT2zSOMs4j4vXsBlb7uCjrGxgXpr
Into this:
KNMT2zSOMs
4j4vXsBlb7
uCjrGxgXpr
This is what I have so far:
<?php
$MyString = fopen('file.txt', "r");
$MyNewString;
$n = 100; // How many you want before seperation
$MyNewString = substr($MyString,0,$n);
$i = $n;
while ($i < strlen($MyString)) {
$MyNewString .= "\n"; // Seperator Character
$MyNewString .= substr($MyString,$i,$n);
$i = $i + $n;
}
file_put_contents($MyString, $MyNewString);
fclose($MyString);
?>
But that is not working quite the way I anticipated.
I realize that there are other similiar questions like mine, but they were not showing how to read a file, then write back to it.
<?php
$str = "aonoeincoieacaonoeincoieacaonoeincoieacaonoeincoieacaonoeincoieacaon";
$pieces = 10;
$ch = chunk_split($str, $pieces);
$piece = explode("\n", $ch);
foreach($piece as $line) {
// write to file
}
?>
http://php.net/manual/en/function.chunk-split.php
Hold on here. You're not giving a file name/path to file_put_contents();, you're giving a file handle.
Try this:
file_put_contents("newFileWithText.txt", $MyNewString);
You see, when doing $var=fopen();, you're giving $var a value of a handle, which is not meant to be used with file_put_contents(); as it doesnt ask for a handle, but a filename instead. So, it should be: file_put_contents("myfilenamehere.txt", "the data i want in my file here...");
Simple.
Take a look at the documentation for str_split. It will take a string and split it into chunks based on length, storing each chunk at a separate index in an array that it returns. You can then iterate over the array adding a line break after each index.
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