Very new to coding here. Trying to get five random numbers in a range from -10 to 10 generated at once. I have another .php file in which I use the roll_num function, but I'm trying to avoid writing the function 5 different times.
Here is what I currently have:
function roll_num()
{
for ($result = 0; $result <= 5; $result++)
{
$result = [];
$result = rand(-10, 10);
return $result;
}
}
Looking for the simplest way to write this. Help would be useful as I don't know what I'm doing, and this is for an introductory class lol. The way I'm trying is similar to the class example, so I'd like to keep it about the same so that I can follow alongside the course without getting too lost. (Besides what I need to change, of course!) Thanks in advance!
The problem with your code is the return inside of the for loop. As soon you hit the return command the function will exit returning the current value of the result, with only one element. Your return should be out of the for loop.
Try something like this:
<?php
function roll_num()
{
$result = []; // result should start empty
while (count($result) < 5)
{
// every step of the loop should add random value to the array
$result[] = rand(-10, 10);
}
// after all random values were pushed, you return once
return $result;
}
var_export(roll_num());
// http://sandbox.onlinephpfunctions.com/code/cd35d6d65f763963216423f341a4299ce1cee8fe
In your code, you are saving the random number in a variable result and immediately returning it. You should keep an array outside the loop and add numbers to it iteratively. Also the iterator should be a seperate integer not your array itself which should end at index 4.
<?php
function roll_num()
{
$result = [];
for ($i = 0; $i < 5; $i++)
{
$result[] = rand(-10, 10);
}
return $result;
}
print_r(roll_num());
function roll_num()
{
$min = -10;
$max = 10;
$num = 5;
$count = 0;
$return = [];
while ($count < $num) {
$return[] = mt_rand($min, $max);
$return = array_flip(array_flip($return));
$count = count($return);
}
shuffle($return);
return $return;
}
print_r(roll_num());
Related
For starters, i'm new in PHP.
I have the function, that prints a row of numbers from 1 to $nums.
But my task is not allows me to use loops, lists, arrays, and strings.
So how can I achieve the same result without using these?
I really do not know, though i tried.
function returnString($nums) {
$error = "Error!";
$str = "";
if ($nums > 0) {
for ($i = 0; $i < $nums; $i++) {
$iter = $i + 1;
$str .= $iter . PHP_EOL;
}
return $str;
}
else {
return $error;
}
}
$numString = returnString(30);
echo $numString;
Also, range() is not allowed too, because it's creates an array from range. Maybe i can create a counter, that increments number from 1? Like $num = 0 $num + 1. I need your advice how can i pull this off, guys.
Thanks, any help will be immeasurable!
If strings are allowed for transfer, then recursion is a solution:
function returnString($nums) {
if ($nums<=0)
return '';
return returnString($nums-1) .$nums.PHP_EOL;
}
$numString = returnString(30);
echo $numString;
I want the function to generate random number 5 times. I have already tried to use do/while loop but it doesn't work:
function myfunction(): int {
$i = 0;
do {
$k = mt_rand(10000, 99999);
$i++;
} while($i <= 4);
{
return $k;
}
}
Stack your values in an array, inside your do-while loop and just before your function ends add the return of the array.
Something like this :
function myfunction():array{
$randomNumbers = array();
$i=0;
do{
$k=mt_rand(10000,99999);
$i++;
$randomNumbers[] = $k;
} while($i<=4) ;
return $randomNumbers;
}
print_r(myfunction());
The syntax of do while loop is given below...
do {
code to be executed;
} while (condition is true);
You have to update your code as it is given below...
do{
$k=mt_rand(10000,99999);
$i++;
}while($i<=4);
I have modified the code a little bit and tested it before sending it to you . Please check the following code :-
function fiveRandomNos(){
$rno = array();
$count=0;
while($count <= 4){
$rno[]=mt_rand(10000,99999);
$count++;
}
return $rno;
}
print_r(fiveRandomNos()) ;
I'm trying to create a generator for a lotto that I play very often.
The lotto is a 5 number draw, ranging from number 1-50 and the same number cannot appear again.
My current approach to do this is using array_rand() but after some reading I noticed that I should not use array_rand() for this purpose, instead I should be using random_int().
My current approach below:
$numbers = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50);
for ($i = 0; $i <= 4; $i++) {
$number = array_rand($numbers);
unset($numbers[$number]);
if ($number == 0) {
$number = array_rand($numbers);
unset($numbers[$number]);
}
$out1[] = array("<div class=\"number\">$number</div>");
}
As you can see above, this works and it generates 5 numbers without duplicating because I unset the number after it's been drawn.
My question is:
How can I do the same as above but using random_int()instead?
To clarify: Use random_int() to generate a random number but ensure that it doesnt generate the same number again in that run.
$numbers = array(); // Create an empty array
while (count($numbers) < 5) { // While less than 5 items in the array repeat the following
$random = random_int(1,50); // Generate a random number
if (!in_array($random, $numbers)) { // Check if the random number is already in the array, and if it is not then:
$numbers[] = $random; // add the random number to the array
}
}
foreach ($numbers as $n) { // Loop over your array and output with your added HTML
echo "<div class=\"number\">$n</div>";
}
Here's the way:
$out = [];
$used = [];
for ($i = 0; $i <= 4; $i++) {
do {
$randInt = random_int(1, 50);
} while (in_array($randInt, $used));
$used[] = $randInt;
$out[] = "<div class=\"number\">$randInt</div>";
}
I have two different functions, one that generates 5 random cards from value 0-51 (unique), and one function that contain an array containing those 5 cards, and an array that contains some of the numbers from array #1 that would be stored.
The function two function two is to replace new values to array #1 if the value is not in array #2.
It seems to be something wrong here. after generating numbers for a bit i got:
array(27,18,37,27,45)
returned from the newCards function.
Question: How can i fix newCards function 100% to do what it is supposed to do? (aka use first array, check if number is in 2nd array, if not, make unique here too) since here it went something wrong since it returned two of the same numbers.
code:
function UniqueCards() {
$result = array();
while(count($result) != 5) {
$rand = rand(0,51); // reads as 0 = 1, and 51 = 52. aka starts at zero.
if(!in_array($rand,$result)){
$result[] = $rand;
}
}
return $result;
}
function newCards($input,$exclude) {
$i = 0;
$output = array();
while($i < count($input)) {
$rand = rand(0,51);
if(in_array($input[$i], $exclude)) {
$output[$i] = $input[$i];
$i++;
}
else if(!in_array($rand, $input)){
$output[$i] = $rand;
$i++;
}
}
return $output;
}
If you add checking if $rand is already in $output will it fix the problem?
function newCards($input,$exclude) {
...
else if(!in_array($rand, $input) && !in_array($rand, $output)) {
$output[$i] = $rand;
$i++;
}
...
}
Write a class called math. It is to have one property called num. It also has one method (function) called factorial. This method is to start at 1 and multiply all of the integers to num. If num is 5 then you would multiply 1*2*3*4*5. Of course you are to do this in a loop.
Which loop should I use? For or do while? Also, do I need an inner loop?
I started with
For (i = 1; i <= 5; i++)
{
}
however, i'm stuck on what to do next...any suggestions?
You can do it using any loop. for loop can be converted to while and do .. while and opposite is true too.
for(i=0;i<5;i++)
is same as
i=0; while(i<5){i++;}
To to find the factorial you should multiply all the values from 1 to the number you want factorial of. So if $num = 5. Only one single loop is needed. You'd want to run this loop.
for($i=1;$i<$num;$i++){
$num*=$i;
}
I am not giving a full solution here because the question seems homework. If I give you full solution it will be spoon-feeding.
$result = 1;
$target = 5;
for ($i = 1;$ i <= $target; $i++)
{
$result *= $i;
}
echo $result;
or
$result = 1;
$target = 5;
while($target > 0) {
$result *= $target;
$target--; // You could do this all in one line, but for learners, this is clearer.
}
echo $result;
Each iteration you will want to multiply the total of the factorial by the value of $i
class Math {
public static function Factorial($factorial) {
$output = 1;
for($i = 2; $i <= $factorial; $i++)
$output *= $i;
return $output;
}
}
I've gotten to where I prefer the while(i--) loop:
<?php
class Math {
public $num = 0;
public function factorial() {
$result = 1;
$num = $this->num;
while ($num) {
$result *= $num--;
}
return $result;
}
}
$factor = new Math();
$factor->num = 5;
echo $factor->factorial();
?>
http://codepad.org/hUOgAoz2