Jump to content
php.lv forumi

Recommended Posts

Posted (edited)

Skaitļi ģenerājas, piemēram, no 1-10 un tad tiek izvadīti trīs rezultāti, bet, lai izvadītie rezultāti paši savā starpā nesakrīt.

Izvadās piemēram:

1

5

9

bet lai neizvadās:

1

1

9

 

Pie ģenerēšanas būtu rand(1,10), bet kā parbaudīt, vai nesakrīt uzģenerētie?

 

Kā tā štelle notiek, derētu palīdzība.

Edited by mach1ne^
Posted (edited)
$rand_nums = array(rand(1, 10), rand(1, 10), rand(1, 10));

while (count(array_unique($rand_nums)) != 3) {
  $rand_nums = array_unique($rand_nums);
  $rand_nums[] = rand(1, 10);
}

print_r($rand_nums);

Edited by Aikss
Posted

Es to darītu drīzāk šādi:

$rand_nums = array();

while (count($rand_nums) != 3)
{
$r = rand(1, 10);
if (!in_array($r, $rand_nums))
{
	$rand_nums[] = $r;
}
}

 

Taču, ja tas skaitlis 10 nav liels, tb nav jāizvēlās no liela intervāla tie randomi, tad es darītu šādi:

$rand_nums = range(1, 10);
shuffle($rand_nums);

// tagad lieto $rand_nums[0], $rand_nums[1], $rand_nums[2] kā savus 3 random skaitļus
// ...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...