ฦididdigar ฦididdige lambobi na iya zama babban ษangaren aikace-aikace da yawa, musamman a cikin ci gaban wasa, ฦirar ฦididdiga, da kwaikwaya. Harshen shirye-shiryen Java yana ba da aikin ginannen aiki don samar da irin waษannan lambobin bazuwar. Aiki ษaya shine Math.random(), kodayake yana haifar da ฦima biyu tsakanin 0.0 (haษe) da 1.0 (keษe). Don samar da adadin bazuwar tsakanin kewayon kewayon kamar 1 zuwa 10, ana buฦatar ฦarin matakai. Wannan labarin yana zurfafa cikin ฦirฦirar lambobi tsakanin 1 da 10 a Java ta amfani da Math.random().
ฦirฦirar Lambobin Random tare da Math.random()
Aikin Java's Math.random() yana dawo da ingantaccen ฦima biyu wanda ya fi ko daidai da 0.0 kuma ฦasa da 1.0. Wadannan dabi'un ana samar da su ne ba da gangan ba, ma'ana cewa tsararrakinsu suna bin takamaiman algorithm amma suna bayyana bazuwar ga mai amfani.
double randomValue = Math.random();
Koyaya, don samar da lamba tsakanin 1 da 10, ba za mu iya yin amfani da Math.random() kai tsaye ba. Madadin haka, muna buฦatar sarrafa ฦimar ninki biyu da Math.random() ya dawo.
Hanyar Samar da Integers Bazuwar Tsakanin 1 da 10
Don yin kwatankwacin ฦirฦirar lambar bazuwar tsakanin 1 da 10, za mu ninka sakamakon Math.random() da 10, ฦara 1, sannan mu jefa sakamakon zuwa lamba (saboda Math.random() ya dawo sau biyu) . Yin jifa zuwa lamba yana yanke juzu'i na decimal, ta haka yana ba mu ฦimar lamba.
int randomInteger = (int)(Math.random() * 10 + 1);
Wannan lambar tana aiki ne saboda Math.random() yana ba da ฦima daga 0.0 zuwa ฦasa da 1.0. Lokacin da kuka ninka wannan ta 10, yana shimfiษa kewayon zuwa 0.0 zuwa ฦasa da 10.0. ฦara 1 yana canza wannan kewayon har ya zama daga 1.0 zuwa kawai ฦasa da 11.0.
Rushewar mataki-mataki
Bari mu zurfafa zurfafa cikin yadda lambar ke aiki:
1.
- Ana kiran aikin Math.random(), wanda ke dawo da pseudorandom ninki biyu fiye da ko daidai da 0.0 da ฦasa da 1.0.
- Ana ninka wannan ฦimar sau biyu ta 10. Yanzu ฦimar ninki biyu ta faษi tsakanin 0.0 da 10.0, har yanzu ฦasa da 10.0.
- Mun ฦara 1 zuwa sakamakon. ฦimar ninki biyu yanzu tsakanin 1.0 da 11.0, har yanzu ฦasa da 11.0.
- A ฦarshe, muna yin nau'in simintin gyare-gyare don canza sau biyu zuwa lamba. Wannan yana yanke sashin goma kuma muna samun lamba tsakanin 1 da 10.
Dakunan karatu da Ayyuka masu alaฦa da ฦirฦirar Lamba bazuwar
Baya ga Math.random(), Java yana ba da wasu hanyoyi don samar da lambobi bazuwar kamar su Random class da ThreadLocalRandom class. Ajin Random yana ba da hanyoyi don samar da lambobi masu ฦima iri daban-daban, kamar int, biyu, dogaye, iyo, Boolean, da sauransu. Ajin Zauren Random yana ba da hanyoyin samar da lambobi masu ฦima a ฦarฦashin yanayi na lokaci guda.
Ayyukan da aka gina a cikin Java da azuzuwan suna ba da cikakkiyar mafita don ฦirฦirar lambobi bazuwar, biyan buฦatu da aikace-aikace iri-iri.