I am looking for solution to pick number randomly from an integer array.
For example I have an array new int[]{1,2,3}
, how can I pick a number randomly?
thecoshman
8,3567 gold badges55 silver badges77 bronze badges
asked Nov 9, 2011 at 13:13
BreakHeadBreakHead
10.4k35 gold badges111 silver badges165 bronze badges
1
public static int getRandom(int[] array) {
int rnd = new Random().nextInt(array.length);
return array[rnd];
}
answered Nov 9, 2011 at 13:15
Chris DennettChris Dennett
22.3k8 gold badges58 silver badges84 bronze badges
12
You can use the Random generator to generate a random index and return the element at that index:
//initialization
Random generator = new Random();
int randomIndex = generator.nextInt(myArray.length);
return myArray[randomIndex];
answered Nov 9, 2011 at 13:17
Luchian GrigoreLuchian Grigore
252k64 gold badges457 silver badges621 bronze badges
If you are going to be getting a random element multiple times, you want to make sure your random number generator is initialized only once.
import java.util.Random;
public class RandArray {
private int[] items = new int[]{1,2,3};
private Random rand = new Random();
public int getRandArrayElement(){
return items[rand.nextInt(items.length)];
}
}
If you are picking random array elements that need to be unpredictable, you should use java.security.SecureRandom rather than Random. That ensures that if somebody knows the last few picks, they won’t have an advantage in guessing the next one.
If you are looking to pick a random number from an Object array using generics, you could define a method for doing so (Source Avinash R in Random element from string array):
import java.util.Random;
public class RandArray {
private static Random rand = new Random();
private static <T> T randomFrom(T... items) {
return items[rand.nextInt(items.length)];
}
}
answered Apr 2, 2016 at 10:33
With Java 7, one can use ThreadLocalRandom
.
A random number generator isolated to the current thread. Like the global Random generator used by the Math class, a ThreadLocalRandom is initialized with an internally generated seed that may not otherwise be modified. When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically encounter much less overhead and contention. Use of ThreadLocalRandom is particularly appropriate when multiple tasks (for example, each a ForkJoinTask) use random numbers in parallel in thread pools.
public static int getRandomElement(int[] arr){
return arr[ThreadLocalRandom.current().nextInt(arr.length)];
}
//Example Usage:
int[] nums = {1, 2, 3, 4};
int randNum = getRandomElement(nums);
System.out.println(randNum);
A generic version can also be written, but it will not work for primitive arrays.
public static <T> T getRandomElement(T[] arr){
return arr[ThreadLocalRandom.current().nextInt(arr.length)];
}
//Example Usage:
String[] strs = {"aa", "bb", "cc"};
String randStr = getRandomElement(strs);
System.out.println(randStr);
answered Jan 26, 2021 at 20:01
Use the Random class:
int getRandomNumber(int[] arr)
{
return arr[(new Random()).nextInt(arr.length)];
}
answered Nov 9, 2011 at 13:17
moongoalmoongoal
2,81721 silver badges23 bronze badges
You can also use
public static int getRandom(int[] array) {
int rnd = (int)(Math.random()*array.length);
return array[rnd];
}
Math.random()
returns an double
between 0.0
(inclusive) to 1.0
(exclusive)
Multiplying this with array.length
gives you a double
between 0.0
(inclusive) and array.length
(exclusive)
Casting to int
will round down giving you and integer between 0
(inclusive) and array.length-1
(inclusive)
answered Nov 9, 2011 at 13:23
ratchet freakratchet freak
47.1k5 gold badges67 silver badges106 bronze badges
1
use java.util.Random
to generate a random number between 0 and array length: random_number
, and then use the random number to get the integer: array[random_number]
answered Nov 9, 2011 at 13:17
James.XuJames.Xu
8,2215 gold badges25 silver badges36 bronze badges
Java has a Random class in the java.util package. Using it you can do the following:
Random rnd = new Random();
int randomNumberFromArray = array[rnd.nextInt(3)];
Hope this helps!
answered Nov 9, 2011 at 13:18
decdendecden
6694 silver badges19 bronze badges
Since you have java 8, another solution is to use Stream API.
new Random().ints(1, 500).limit(500).forEach(p -> System.out.println(list[p]));
Where 1
is the lowest int generated (inclusive) and 500
is the highest (exclusive). limit
means that your stream will have a length of 500.
int[] list = new int[] {1,2,3,4,5,6};
new Random().ints(0, list.length).limit(10).forEach(p -> System.out.println(list[p]));
Random is from java.util
package.
answered Sep 21, 2015 at 11:24
Johnny WillerJohnny Willer
3,6973 gold badges27 silver badges51 bronze badges
package workouts;
import java.util.Random;
/**
*
* @author Muthu
*/
public class RandomGenerator {
public static void main(String[] args) {
for(int i=0;i<5;i++){
rndFunc();
}
}
public static void rndFunc(){
int[]a= new int[]{1,2,3};
Random rnd= new Random();
System.out.println(a[rnd.nextInt(a.length)]);
}
}
answered Mar 6, 2016 at 13:56
You can also try this approach..
public static <E> E[] pickRandom_(int n,E ...item) {
List<E> copy = Arrays.asList(item);
Collections.shuffle(copy);
if (copy.size() > n) {
return (E[]) copy.subList(0, n).toArray();
} else {
return (E[]) copy.toArray();
}
}
answered May 4, 2018 at 11:01
2
package io.github.baijifeilong.tmp;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Stream;
/**
* Created by BaiJiFeiLong@gmail.com at 2019/1/3 下午7:34
*/
public class Bar {
public static void main(String[] args) {
Stream.generate(() -> null).limit(10).forEach($ -> {
System.out.println(new String[]{"hello", "world"}[ThreadLocalRandom.current().nextInt(2)]);
});
}
}
answered Jan 3, 2019 at 11:38
BaiJiFeiLongBaiJiFeiLong
3,5361 gold badge28 silver badges28 bronze badges
Получить случайный элемент массива в JavaScript можно при помощи значения количества его элементов и функций Math.random() и Math.floor().
Случайное значение
Ниже простой пример получения случайного значения массива.
// Определяем массив
var arr = [‘PHP’, ‘JavaScript’, ‘Python’, ‘Perl’, ‘Ruby’, ‘Go’, ‘Java’];
// Получаем случайный ключ массива
var rand = Math.floor(Math.random() * arr.length);
alert(arr[rand]);// Выведем, например: JavaScript
Функция arrayRandElement
Проще определить отдельную функцию arrayRandElement(arr)
для получения случайного элемента массива, которая будет принимать в качестве параметра один параметр — массив, и возвращать его случайное значение.
/**
* Получение случайного элемента массива
* @param arr
* @return {*}
*/
function arrayRandElement(arr) {
var rand = Math.floor(Math.random() * arr.length);
return arr[rand];
}
// Определяем массив
var arr = [‘PHP’, ‘JavaScript’, ‘Python’, ‘Perl’, ‘Ruby’, ‘Go’, ‘Java’];
alert(arrayRandElement(arr));// Выведет, например: Python
Свойство объекта randElement
Еще один изящный способ — повесить на Object.prototype
метод randElement()
, который будет возвращать случайный элемент массива.
/**
* Вешаем на ассоциативный массив метод randElement
* Метод возвращает случайное значение массива при это удаляя его
* @returns mixed элемент массива
*/
Object.defineProperty(
Object.prototype,
‘randElement’,
{
value: function() {
var rand = Math.floor(Math.random() * this.length);
return this[rand];
}
}
);
// Определяем массив
var arr = [‘PHP’, ‘JavaScript’, ‘Python’, ‘Perl’, ‘Ruby’, ‘Go’, ‘Java’];
alert(arr.randElement());// Выведет, например: Go
нет оценок
It’s a simple one-liner:
const randomElement = array[Math.floor(Math.random() * array.length)];
For example:
const months = ["January", "February", "March", "April", "May", "June", "July"];
const random = Math.floor(Math.random() * months.length);
console.log(random, months[random]);
answered Dec 29, 2010 at 0:06
Jacob RelkinJacob Relkin
161k33 gold badges345 silver badges319 bronze badges
5
If you’ve already got underscore or lodash included in your project you can use _.sample
.
// will return one item randomly from the array
_.sample(['January', 'February', 'March']);
If you need to get more than one item randomly, you can pass that as a second argument in underscore:
// will return two items randomly from the array using underscore
_.sample(['January', 'February', 'March'], 2);
or use the _.sampleSize
method in lodash:
// will return two items randomly from the array using lodash
_.sampleSize(['January', 'February', 'March'], 2);
answered Jun 19, 2015 at 18:40
Brendan NeeBrendan Nee
5,0512 gold badges32 silver badges32 bronze badges
1
You may consider defining a function on the Array prototype, in order to create a method [].sample()
which returns a random element.
First, to define the prototype function, place this snippet in your code:
Array.prototype.sample = function(){
return this[Math.floor(Math.random()*this.length)];
}
Later, to sample a random element from the array, just call .sample()
:
[1,2,3,4].sample() //=> a random element
I’m releasing these code snippets into the public domain, under the terms of the CC0 1.0 license.
answered Nov 24, 2015 at 23:52
Ben AubinBen Aubin
5,5242 gold badges34 silver badges54 bronze badges
5
~~
is much faster than Math.Floor()
, so when it comes to performance optimization while producing output using UI elements, ~~
wins the game. MORE INFO
var rand = myArray[~~(Math.random() * myArray.length)];
But if you know that the array is going to have millions of elements then you might want to reconsider between Bitwise Operator and Math.Floor()
, as bitwise operators behave weirdly with large numbers. See below example explained with the output.
var number = Math.floor(14444323231.2); // => 14444323231
var number = 14444323231.2 | 0; // => 1559421343
answered May 5, 2018 at 12:25
Ankur SoniAnkur Soni
5,6395 gold badges47 silver badges81 bronze badges
5
The shortest version:
var myArray = ['January', 'February', 'March'];
var rand = myArray[(Math.random() * myArray.length) | 0]
console.log(rand)
answered Jul 19, 2016 at 2:37
foxirisfoxiris
3,03231 silver badges31 bronze badges
4
Say you want to choose a random item that is different from the last time (not really random, but still a common requirement)…
/**
* Return a random element from an array that is
* different than `last` (as long as the array has > 1 items).
* Return null if the array is empty.
*/
function getRandomDifferent(arr, last = undefined) {
if (arr.length === 0) {
return null;
} else if (arr.length === 1) {
return arr[0];
} else {
let num = 0;
do {
num = Math.floor(Math.random() * arr.length);
} while (arr[num] === last);
return arr[num];
}
}
Implement like this:
const arr = [1,2,3];
const r1 = getRandomDifferent(arr);
const r2 = getRandomDifferent(arr, r1); // r2 is different than r1.
answered Aug 14, 2012 at 1:57
CrazyTimCrazyTim
6,5976 gold badges34 silver badges55 bronze badges
0
If you have fixed values (like a month name list) and want a one-line solution
var result = ['January', 'February', 'March'][Math.floor(Math.random() * 3)]
The second part of the array is an access operation as described in Why does [5,6,8,7][1,2] = 8 in JavaScript?
answered Nov 28, 2014 at 14:58
I.G. PascualI.G. Pascual
5,7605 gold badges42 silver badges58 bronze badges
6
If you want to write it on one line, like Pascual’s solution, another solution would be to write it using ES6’s find function (based on the fact, that the probability of randomly selecting one out of n
items is 1/n
):
var item = ['A', 'B', 'C', 'D'].find((_, i, ar) => Math.random() < 1 / (ar.length - i));
console.log(item);
Use that approach for testing purposes and if there is a good reason to not save the array in a seperate variable only. Otherwise the other answers (floor(random()*length
and using a seperate function) are your way to go.
answered Sep 11, 2017 at 18:01
StephanStephan
1,94814 silver badges19 bronze badges
0
Many of the offered solutions add a method to a specific Array which restricts it’s use to just that array. This solution is reusable code that works for any array and can be made type safe.
TypeScript
export function randChoice<T>(arr: Array<T>): T {
return arr[Math.floor(Math.random() * arr.length)]
}
JavaScript
function randChoice(arr) {
return arr[Math.floor(Math.random() * arr.length)]
}
PauAI
3744 silver badges16 bronze badges
answered Aug 5, 2022 at 5:26
Tony O’HaganTony O’Hagan
21.4k3 gold badges64 silver badges77 bronze badges
Editing Array prototype can be harmful. Here it is a simple function to do the job.
function getArrayRandomElement (arr) {
if (arr && arr.length) {
return arr[Math.floor(Math.random() * arr.length)];
}
// The undefined will be returned if the empty array was passed
}
Usage:
// Example 1
var item = getArrayRandomElement(['January', 'February', 'March']);
// Example 2
var myArray = ['January', 'February', 'March'];
var item = getArrayRandomElement(myArray);
answered Sep 5, 2018 at 22:48
SeagullSeagull
3,2992 gold badges31 silver badges37 bronze badges
If you need to fetch a random item more than once, then, obviously you would use a function. One way is to make that function a method of the Array.prototype
, but that will normally get you shouted down for tampering with built in prototypes.
However, you can add the method to the specific array itself:
var months = ['January', 'February', 'March'];
months.random = function() {
return this[Math.floor(Math.random()*this.length)];
};
That way you can use months.random()
as often as you like without interfering with the generic Array.prototype
.
As with any random function, you run the risk of getting the same value successively. If you don’t want that, you will need to track the previous value with another property:
months.random=function() {
var random;
while((random=this[Math.floor(Math.random()*this.length)]) == this.previous);
this.previous=random;
return random;
};
If you’re going to do this sort of thing often, and you don’t want to tamper with Array.prototype
, you can do something like this:
function randomValue() {
return this[Math.floor(Math.random()*this.length)];
}
var data = [ … ];
var moreData = [ … ];
data.random=randomValue;
moreData.random=randomValue;
answered Jul 12, 2021 at 3:54
ManngoManngo
13.6k10 gold badges85 silver badges105 bronze badges
Faker.js has many utility functions for generating random test data. It is a good option in the context of a test suite:
const faker = require('faker');
faker.helpers.arrayElement(['January', 'February', 'March']);
As commenters have mentioned, you generally should not use this library in production code.
thoroc
3,2012 gold badges27 silver badges34 bronze badges
answered Dec 12, 2017 at 20:42
NathanNathan
5,2542 gold badges25 silver badges28 bronze badges
5
To get crypto-strong random item form array use
let rndItem = a=> a[rnd()*a.length|0];
let rnd = ()=> crypto.getRandomValues(new Uint32Array(1))[0]/2**32;
var myArray = ['January', 'February', 'March'];
console.log( rndItem(myArray) )
answered Sep 16, 2019 at 10:17
Kamil KiełczewskiKamil Kiełczewski
83.2k29 gold badges359 silver badges335 bronze badges
Recursive, standalone function which can return any number of items (identical to lodash.sampleSize):
function getRandomElementsFromArray(array, numberOfRandomElementsToExtract = 1) {
const elements = [];
function getRandomElement(arr) {
if (elements.length < numberOfRandomElementsToExtract) {
const index = Math.floor(Math.random() * arr.length)
const element = arr.splice(index, 1)[0];
elements.push(element)
return getRandomElement(arr)
} else {
return elements
}
}
return getRandomElement([...array])
}
answered Dec 8, 2017 at 14:23
dwiltdwilt
5978 silver badges13 bronze badges
This is similar to, but more general than, @Jacob Relkin’s solution:
This is ES2015:
const randomChoice = arr => {
const randIndex = Math.floor(Math.random() * arr.length);
return arr[randIndex];
};
The code works by selecting a random number between 0 and the length of the array, then returning the item at that index.
answered Jan 2, 2016 at 15:23
Max HeiberMax Heiber
14k11 gold badges58 silver badges95 bronze badges
var item = myArray[Math.floor(Math.random()*myArray.length)];
or equivalent shorter version:
var item = myArray[(Math.random()*myArray.length)|0];
Sample code:
var myArray = ['January', 'February', 'March'];
var item = myArray[(Math.random()*myArray.length)|0];
console.log('item:', item);
answered May 19, 2017 at 9:01
Pavel PPavel P
15.6k11 gold badges79 silver badges127 bronze badges
Simple Function :
var myArray = ['January', 'February', 'March'];
function random(array) {
return array[Math.floor(Math.random() * array.length)]
}
random(myArray);
OR
var myArray = ['January', 'February', 'March'];
function random() {
return myArray[Math.floor(Math.random() * myArray.length)]
}
random();
OR
var myArray = ['January', 'February', 'March'];
function random() {
return myArray[Math.floor(Math.random() * myArray.length)]
}
random();
answered Dec 17, 2017 at 5:42
1
In my opinion, better than messing around with prototypes , or declaring it just in time, I prefer exposing it to window:
window.choice = function() {
if (!this.length || this.length == 0) return;
if (this.length == 1) return this[0];
return this[Math.floor(Math.random()*this.length)];
}
Now anywhere on your app you call it like:
var rand = window.choice.call(array)
This way you can still use for(x in array)
loop properly
answered May 13, 2014 at 10:27
weiskweisk
2,4581 gold badge18 silver badges18 bronze badges
3
I’ve found a way around the top answer’s complications, just by concatenating the variable rand to another variable that allows that number to be displayed inside the calling of myArray[];. By deleting the new array created and toying around with it’s complications, I’ve come up with a working solution:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var myArray = ['January', 'February', 'March', 'April', 'May'];
var rand = Math.floor(Math.random() * myArray.length);
var concat = myArray[rand];
function random() {
document.getElementById("demo").innerHTML = (concat);
}
</script>
<button onClick="random();">
Working Random Array generator
</button>
</body>
</html>
answered Apr 27, 2016 at 22:01
2
static generateMonth() {
const theDate = ['January', 'February', 'March'];
const randomNumber = Math.floor(Math.random()*3);
return theDate[randomNumber];
};
You set a constant variable to the array, you then have another constant that chooses randomly between the three objects in the array and then the function simply returns the results.
answered Mar 15, 2018 at 7:51
Neil MeyerNeil Meyer
4353 silver badges12 bronze badges
Looking for a true one-liner I came to this:
['January', 'February', 'March'].reduce((a, c, i, o) => { return o[Math.floor(Math.random() * Math.floor(o.length))]; })
answered Jul 24, 2020 at 1:47
blagusblagus
2,0364 gold badges19 silver badges22 bronze badges
By adding a method on prototype of array you can get random values easly.
In this example you can get single or multiple random values from array.
You can run to test code by clicking snippet button.
Array.prototype.random = function(n){
if(n&&n>1){
const a = [];
for(let i = 0;i<n;i++){
a.push(this[Math.floor(Math.random()*this.length)]);
}
return a;
} else {
return this[Math.floor(Math.random()*this.length)];
}
}
const mySampleArray = ['a','b','c','d','e','f','g','h'];
mySampleArray.random(); // return any random value etc. 'a', 'b'
mySampleArray.random(3); //retun an array with random values etc: ['b','f','a'] , ['d','b','d']
alert(mySampleArray.random());
alert(mySampleArray.random(3));
answered Jul 24, 2020 at 14:49
Kamuran SönecekKamuran Sönecek
3,2782 gold badges30 silver badges56 bronze badges
Method 1:
- Use Math.random() function to get the random number between(0-1, 1
exclusive). - Multiply it by the array length to get the numbers
between(0-arrayLength). - Use Math.floor() to get the index ranging
from(0 to arrayLength-1).
const arr = [«foo»,»bar»];
const randomlyPickedString=arr[Math.floor(Math.random() * arr.length)];
console.log(randomlyPickedString);
Method 2:
- The random(a, b) method is used to generates a number between(a to b, b exclusive).
- Taking the floor value to range the numbers from (1 to arrayLength).
- Subtract 1 to get the index ranging from(0 to arrayLength-1).
const arr = [«foo»,»bar»];
const randomlyPickedString=arr[Math.floor(random(1, 5))-1];
console.log(randomlyPickedString);
answered May 20, 2021 at 15:19
A generic way to get random element(s):
let some_array = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];
let months = random_elems(some_array, 3);
console.log(months);
function random_elems(arr, count) {
let len = arr.length;
let lookup = {};
let tmp = [];
if (count > len)
count = len;
for (let i = 0; i < count; i++) {
let index;
do {
index = ~~(Math.random() * len);
} while (index in lookup);
lookup[index] = null;
tmp.push(arr[index]);
}
return tmp;
}
answered Oct 11, 2018 at 11:37
RafaelRafael
7,54513 gold badges30 silver badges46 bronze badges
Here is an example of how to do it:
$scope.ctx.skills = data.result.skills;
$scope.praiseTextArray = [
"Hooray",
"You're ready to move to a new skill",
"Yahoo! You completed a problem",
"You're doing great",
"You succeeded",
"That was a brave effort trying new problems",
"Your brain was working hard",
"All your hard work is paying off",
"Very nice job!, Let's see what you can do next",
"Well done",
"That was excellent work",
"Awesome job",
"You must feel good about doing such a great job",
"Right on",
"Great thinking",
"Wonderful work",
"You were right on top of that one",
"Beautiful job",
"Way to go",
"Sensational effort"
];
$scope.praiseTextWord = $scope.praiseTextArray[Math.floor(Math.random()*$scope.praiseTextArray.length)];
mech
2,7255 gold badges30 silver badges38 bronze badges
answered Feb 18, 2016 at 19:39
0
Create one random value and pass to array
Please try following code..
//For Search textbox random value
var myPlaceHolderArray = ['Hotels in New York...', 'Hotels in San Francisco...', 'Hotels Near Disney World...', 'Hotels in Atlanta...'];
var rand = Math.floor(Math.random() * myPlaceHolderArray.length);
var Placeholdervalue = myPlaceHolderArray[rand];
alert(Placeholdervalue);
answered Feb 3, 2017 at 12:49
1
randojs makes this a little more simple and readable:
console.log( rando(['January', 'February', 'March']).value );
<script src="https://randojs.com/1.0.0.js"></script>
answered Dec 2, 2019 at 2:47
1
I am really surprised nobody tried to use native random values:
array[Date.now()%array.length]
It will not work for array length over 160000000000, but I am sure you will never create arrays like this
UPD
As far as you question is how to pick random value from array called myArray
(with len=3), the solution should be:
myArray[Date.now()%myArray.length]
answered Nov 3, 2021 at 5:38
EgorEgor
2695 silver badges21 bronze badges
10
JavaScript Math
Определение и применение
JavaScript метод random() объекта Math возвращает псевдослучайное число от 0 до 1. Обращаю Ваше внимание на то, что метод random() может возвращать значение 0, но никогда не вернет значение 1.
Поддержка браузерами
JavaScript синтаксис:
Math.random();
Версия JavaScript
1.0 (ECMAScript 1st Edition)
Пример использования
Базовое использование
В следующем примере с помощью метода random() мы получим случайное число от 0 (включительно) до 1 (не включая):
const rnd = Math.random(); console.log(rnd); // возвращаемое значение 0.5017845092137254
Получение случайного числа в заданном диапазоне
В следующем примере с помощью метода random() мы рассмотрим как получить случайное число внутри определенного диапазона. Обратите внимание, что возвращаемое значение не может быть меньше параметра min и не более, или равно параметра max:
function getRandomFromRange(min, max) { return Math.random() * (max - min) + min; } console.log(getRandomFromRange(5, 10)); // возвращаемое значение 6.830906542874363 console.log(getRandomFromRange(5, 10)); // возвращаемое значение 9.436449613234068 console.log(getRandomFromRange(5, 10)); // возвращаемое значение 6.4493344451274055 console.log(getRandomFromRange(5, 10)); // возвращаемое значение 5.160973635403946 console.log(getRandomFromRange(5, 10)); // возвращаемое значение 5.369261822513969
Получение случайного целого числа в заданном диапазоне
В следующем примере мы рассмотрим как с помощью метода random(), ceil() и floor() объекта Math получить случайное целое число внутри определенного диапазона. Обратите внимание, что возвращаемое значение не может быть меньше параметра min и не более, или равно параметра max:
function getRandomIntFromRange(min, max) { min = Math.ceil(min); // вычисляет и возвращает наименьшее целое число, которое больше или равно переданному числу (округляет число вверх) max = Math.floor(max); // вычисляет и возвращает наибольшее целое число, которое меньше или равно переданному числу (округляет число вниз) return Math.floor(Math.random() * (max - min)) + min; } console.log(getRandomIntFromRange(5, 10)); // возвращаемое значение 6 console.log(getRandomIntFromRange(5, 10)); // возвращаемое значение 9 console.log(getRandomIntFromRange(5, 10)); // возвращаемое значение 1 console.log(getRandomIntFromRange(5, 10)); // возвращаемое значение 5 console.log(getRandomIntFromRange(5, 10)); // возвращаемое значение 6
Получение случайного элемента в массиве
В следующем примере мы рассмотрим как с помощью методов ceil() и random() найти случайный элемент внутри массива:
const arr = ["a", "b", "c"]; const randomElement = arr[Math.floor(Math.random() * arr.length)]; Например: arr[Math.floor(0.8610795581202113 * 3)]; // индекс будет соответствовать 2
JavaScript Math
На занятии объясняется, как работать с одномерными массивами в Паскале, как использовать генератор случайных чисел — функцию random в Паскале. Рассматривается пример того, как вывести числа Фибоначчи
Материалы сайта labs-org.ru направлены на практическое освоение языка программирования Pascal. Краткие теоретические сведения не претендуют на полное освещение материала по теме; необходимую информацию можно найти в сети Интернет в большом количестве. В наши же задачи входит предоставление возможности получения практических навыков программирования на Паскале. Решенные наглядные примеры и задания изложены по мере увеличения их сложности, что позволит с легкостью изучить материал с нуля.
Содержание:
- Одномерные массивы в Паскале
- Объявление массива
- Инициализация массива
- Вывод элементов массива
- Динамические массивы (pascalAbc.Net)
- Функция Random в Pascal
- Числа Фибоначчи в Паскале
- Максимальный (минимальный) элемент массива
- Поиск в массиве
- Циклический сдвиг
- Перестановка элементов в массиве
- Выбор элементов и сохранение в другой массив
- Сортировка элементов массива
Одномерные массивы в Паскале
Объявление массива
Массивы в Паскале используются двух типов: одномерные и двумерные.
Определение одномерного массива в Паскале звучит так: одномерный массив — это определенное количество элементов, относящихся к одному и тому же типу данных, которые имеют одно имя, и каждый элемент имеет свой индекс — порядковый номер.
Описание массива в Паскале (объявление) и обращение к его элементам происходит следующим образом:
Объявление массива
var dlina: array [1..3] of integer; begin dlina[1]:=500; dlina[2]:=400; dlina[3]:=150; ...
dlina
— идентификатор (имя) массива;Array
(в переводе с англ. «массив» или «набор»);[1..3]
— в квадратных скобках ставится номер (индекс) первого элемента, затем две точки и индекс последнего элемента массива, т.е. по сути, указывается количество элементов; количество элементов массива называется размерностью массиваof integer
(с англ. «из целых чисел») — указывает, к какому типу относится массив, of здесь — служебное слово.Объявить размер можно через константу:
Инициализация массива
Кроме того, массив может быть сам константным, т.е. все его элементы в программе заранее определены. Описание такого массива выглядит следующим образом:
const a:array[1..4] of integer = (1, 3, 2, 5);
Заполнение последовательными числами:
Результат: A[1] = 8, A[2] = 9, A[3] = 10, ..., A[N] = A[N-1] + 1
Ввод с клавиатуры:
Пример: Рассмотрим, как происходит ввод массива в Паскале:
writeln ('введите кол-во элементов: '); readln(n); {если кол-во заранее не известно, - запрашиваем его} for i := 1 to n do begin write('a[', i, ']='); read(a[i]); ... end; ...
✍ Пример результата:
введите кол-во элементов: 3 a[1]=5 a[2]=7 a[3]=4
Вывод элементов массива
Пример: Рассмотрим, как вывести массив в Паскале:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var a: array[1..5] of integer; {массив из пяти элементов} i: integer; begin a[1]:=2; a[2]:=4; a[3]:=8; a[4]:=6; a[5]:=3; writeln('Массив A:'); for i := 1 to 5 do write(a[i]:2); {вывод элементов массива} end. |
✍ Пример результата:
Для работы с массивами чаще всего используется в Паскале цикл for с параметром, так как обычно известно, сколько элементов в массиве, и можно использовать счетчик цикла в качестве индексов элементов.
Задача Array 0. Необходимо задать вещественный массив размерностью 6 (т.е. из шести элементов); заполнить массив вводимыми значениями и вывести элементы на экран. Использовать два цикла: первый — для ввода элементов, второй — для вывода.
Пример результата:
введите элемент массива: 3.0 введите элемент массива: 0.8 введите элемент массива: 0.56 введите элемент массива: 4.3 введите элемент массива: 23.8 введите элемент массива: 0.7 Массив = 3, 0.8, 0.56, 4.3, 23.8, 0.7
[Название файла: taskArray0.pas
]
В данном примере работы с одномерным массивом есть явное неудобство: присваивание значений элементам.
Обработка массивов в Паскале, так же как и заполнение массива, происходит обычно с использованием цикла for
.
Динамические массивы (pascalAbc.Net)
Основным недостатком статических массивов является то, что их размер нельзя задать с учетом текущих обрабатываемых данных. Приходится описывать массивы с максимально возможным значением количества элементов, выделяя для них столько памяти, сколько может потребоваться для хранения самой большого из возможных наборов исходных данных.
Объявление:
var a: array of integer; var n:=readInteger; a:=new integer[n]; // инициализация, выделение памяти для элементов массива
или:
var a: array of integer; var n:=readInteger; SetLength(a,n); // устанавливаем размер
Аналогичным образом массивы могут описываться в качестве параметров подпрограмм, например:
procedure p(a: array of integer);
Созданные элементы сразу получают начальное значение, равное нулевому значению соответствующего типа: для чисел это целый или вещественный нуль, для символов — символ с кодом 0, для строк и других ссылочных типов данных — нулевая ссылка nil
Объявление и инициализация массива:
Пример:
begin var a: array of integer; a := new integer[3]; a[0] := 5; a[1] := 2; a[2] := 3; end.
или в одну строку:
begin var a: array of integer; a := new integer[3](5,2,3); print(a) end.
или короткая запись:
var a:=Arr(1,2,3);// по правой части - integer
Элементы динамического массива всегда индексируются от 0.
Ввод элементов:
Пример:
var a:=ReadArrInteger(5); // ввод пяти целых var a:=ReadArrReal(5); // ввод пяти вещественных
Функции генерации массивов:
1. ArrFill :
var a := ArrFill(10, 1); // массив из 10 целых чисел, равных 1
2. ArrGen :
var a := ArrGen(ReadInteger, 1, e -> e + 2); // массив, состоящий из n первых положительных нечетных чисел a.Print;
Проход по элементам массива:
Пример:
for var i:=0 to a.Length-1 do a[i] += 1;
или:
for var i := 0 to a.High do a[i] += 1;
Проход по элементам (только для чтения):
Пример:
foreach var x in a do Print(x)
Length
Low
и High
, определяющие соответственно нижнюю и верхнюю границу диапазона изменения индекса. Свойство a.Low
всегда возвращает 0, а свойство a.High
определяется как a.High = a.Length – 1
Простой вывод элементов:
Writeln(a); // пример вывода: [1,5,3,13,20]
или метод массива Print
:
a.Print; // пример вывода: 1 5 3 13 20 a.PrintLines; // каждый элемент с новой строки
Функция Random в Pascal
Для того чтобы постоянно не запрашивать значения элементов массива используется генератор случайных чисел в Паскаль, который реализуется функцией Random
. На самом деле генерируются псевдослучайные числа, но суть не в этом.
Для генерации чисел от 0
до n
(не включая само значение n
, целые числа в интервале [0,N)) используется запись random (n)
.
Перед использованием функции необходимо инициализировать датчик случайных чисел с помощью процедуры randomize
.
Диапазон в Паскале тех самых случайных чисел от a
до b
задается формулой:
Пример: Заполнение массива случайными числами в Pascal:
1 2 3 4 5 6 7 8 9 10 |
var f: array[1..10] of integer; i:integer; begin randomize; for i:=1 to 10 do begin f[i]:=random(10); { интервал [0,9] } write(f[i],' '); end; end. |
✍ Пример результата:
Для вещественных чисел в интервале [0,1):
var x: real; ... x := random(0.0,1.0);; { интервал [0,1), т.е. единица не включена }
PascalABC.NET
:
var (a, b, c) := Random3(10.0, 20.0); // диапазон [10, 20) write(a:0:2,' ',b:0:2,' ', c:0:2) // 14.73 18.63 19.72
Пример:
var a:=arrRandomInteger(10);
или с дополнительными параметрами (диапазон [5;15]):
var a:=arrRandomInteger(10,5,15);
Задача Array 1. Необходимо задать массив размерностью 5, заполнить массив случайными числами в интервале [-1,1] и вывести элементы на экран: определить три позиции для вывода каждого элемента, с двумя знаками после запятой.
Пример результата:
Массив = 0.22 0.00 -0.69 -0.35 -0.11
[Название файла: taskArray1.pas
]
Числа Фибоначчи в Паскале
Наиболее распространенным примером работы с массивом является вывод ряда чисел Фибоначчи в Паскаль. Рассмотрим его.
Пример: Ряд чисел Фибоначчи: 1 1 2 3 5 8 13…
f[0]:=1; f[1]:=1; f[2]:=2; …или
f[2]:=f[0]+f[1]; f[3]:=f[1]+f[2];или
Получили формулу элементов ряда.
Пример: Вычислить и распечатать первые 20 чисел Фибоначчи.
1 2 3 4 5 6 7 8 9 10 11 |
var i:integer; f:array[0..19]of integer; begin f[0]:=1; f[1]:=1; for i:=2 to 19 do begin f[i]:=f[i-1]+f[i-2]; writeln(f[i]) end; end. |
На данном примере, становится понятен принцип работы с числовыми рядами. Обычно, для вывода числового ряда находится формула определения каждого элемента данного ряда. Так, в случае с числами Фибоначчи, эта формула-правило выглядит как f[i]:=f[i-1]+f[i-2]
. Поэтому ее необходимо использовать в цикле for
при формировании элементов массива.
Задача Array 2. Дан ряд из 10 произвольных чисел: a[1], a[2], ... , a[10]
(использовать функцию random()
). Подсчитать и напечатать суммы троек стоящих рядом чисел: a[1]+a[2]+a[3]
, a[2]+a[3]+a[4]
, a[3]+a[4]+a[5]
, …… , a[8]+a[9]+a[10]
Пример результата:
Массив = 2 0 4 29 3 11 26 11 9 4 mas[1] + mas[2] + mas[3] = 6 mas[2] + mas[3] + mas[4] = 33 mas[3] + mas[4] + mas[5] = 36 mas[4] + mas[5] + mas[6] = 43 mas[5] + mas[6] + mas[7] = 40 mas[6] + mas[7] + mas[8] = 48 mas[7] + mas[8] + mas[9] = 46 mas[8] + mas[9] + mas[10] = 24
[Название файла: taskArray2.pas
]
Задача Array 3. Написать программу решения задачи о печати ряда чисел 2 4 8 16 32 ... 512
; для заполнения массива использовать цикл Repeat
[Название файла: taskArray3.pas
]
Максимальный (минимальный) элемент массива
Псевдокод:
Поиск максимального элемента по его индексу:
PascalABC.NET
:
Минимальный элемент и его индекс:
Решение 1:
// … var (min, minind) := (a[0], 0); for var i:=1 to a.Length-1 do if a[i]<min then (min, minind) := (a[i], i); Result := (min, minind);
Решение 2:
// … var (min, minind) := (real.MaxValue, 0); for var i:=0 to a.Length-1 do if a[i]<min then (min, minind) := (a[i], i); Result := (min, minind);
Решение 3:
begin var a := new integer[5]; a := arrRandomInteger(5); // [86,37,41,45,76] print(a.Min,a.IndexMin); // 37 1 end.
Задача Array_min: Найдите минимальный элемент массива. Выведите элемент и его индекс.
Пример результата:
9 5 4 22 23 7 3 16 16 8 Минимальный элемент массива A[7]=3
[Название файла: taskArray_min.pas
]
Задача Array 4. Дан массив из 10 целочисленных элементов. Найти количество отрицательных и вывести количество на экран.
Пример результата:
3 4 6 -1 6 -2 1 5 0 1 Количество отрицательных элементов: 2
[Название файла: taskArray4.pas
]
Задача Array 5. Найти минимальное и максимальное из n введенных чисел (массива). Определить расстояние между этими элементами.
3 2 6 1 3 4 7 2 >>> min=1, max=7, distance=3
[Название файла: taskArray5.pas
]
Задача Array 6. Дан целочисленный массив размера N. Вывести все содержащиеся в данном массиве четные числа в порядке убывания их индексов, а также их количество K.
N=4 mas: 8 9 2 5 >>> 2 8 количество= 2
[Название файла: taskArray6.pas
]
Задача Array 7. Ввести с клавиатуры массив из 5 элементов, найти в нем два максимальных элемента и их номера.
Пример:
Исходный массив: 4 -5 10 -10 5 максимальные A[3]=10, A[5]=5
[Название файла: taskArray7.pas
]
Поиск в массиве
Рассмотрим сложный пример работы с одномерными массивами:
Пример: Дан массив из 10 чисел. Определить, есть ли в массиве число, введенное пользователем. Если есть – выводить «найдено», если нет – «не найдено».
Сложность задания заключается в том, что выводить слова «найдено» или «не найдено» необходимо один раз.
Для решения поставленной задачи понадобится оператор break
— выход из цикла.
Решение Вариант 1. Цикл for:
PascalABC.NET
:
Cтандартные методы a.IndexOf(x)
и a.LastIndexOf(x)
:
begin var a := new integer[10]; a := arrRandomInteger(5,0,5); //[1,3,5,4,5] print(a.IndexOf(3)) // 1 end.
или метод a.Contains(x)
наравне с x in a
:
begin var a := new integer[10]; a := arrRandomInteger(5,0,5); //[1,3,5,4,5] print(a.Contains(3)); // True print(3 in a)// True end.
Рассмотрим эффективное решение:
Задача: найти в массиве элемент, равный X
, или установить, что его нет.
Алгоритм:
- начать с 1-го элемента (
i:=1
); - если очередной элемент (
A[i]
) равенX
, то закончить поиск иначе перейти к следующему элементу.
решение на Паскале Вариант 2. Цикл While:
Поиск элемента в массиве
Предлагаем посмотреть подробный видео разбор поиска элемента в массиве (эффективный алгоритм):
Задача Array 8. Заполнить массив из 10 элементов случайными числами в интервале [0..4]
и вывести номера всех элементов, равных X
.
Пример:
Исходный массив: 4 0 1 2 0 1 3 4 1 0 Что ищем? 0 A[2], A[5], A[10]
[Название файла: taskArray8.pas
]
Циклический сдвиг
Пример: сдвинуть элементы массива влево на 1 позицию, первый элемент становится на место последнего.
Решение:
Алгоритм:
A[1]:=A[2]; A[2]:=A[3];… A[N-1]:=A[N];
Программа:
PascalABC.NET
:
Циклический сдвиг влево:
// … var v := a[0]; for var i:=0 to a.Length-2 do a[i] := a[i+1]; a[a.Length-1] := v;
Циклический сдвиг вправо:
// … var v := a[a.Length-1]; for var i:=a.Length-1 downto 1 do a[i] := a[i-1]; a[0] := v;
Задача Array 9. Заполнить массив из 10 элементов случайными числами в интервале [-10..10] и выполнить циклический сдвиг влево без первого элемента.
Пример:
Исходный массив: 4 -5 3 10 -4 -6 8 -10 1 0 Результат: 4 3 10 -4 -6 8 -10 1 0 -5
[Название файла: taskArray9.pas
]
Перестановка элементов в массиве
Рассмотрим, как происходит перестановка или реверс массива.
Пример: переставить элементы массива в обратном порядке
Решение:
Алгоритм:
Псевдокод:
Программа:
PascalABC.NET
:
Перестановка (ревёрс):
Решение 1:
begin var a: array of integer := (1,3,5,7); var n := a.Length; for var i:=0 to n div 2 - 1 do Swap(a[i],a[n-i-1]); End.
Решение 2 (стандартная процедура Reverse()
):
begin var a:=new integer[10]; a:=arrRandomInteger(10); print(a);// [41,81,84,63,12,26,88,25,36,72] Reverse(a); print(a) //[72,36,25,88,26,12,63,84,81,41] end.
Задача Array 10. Заполнить массив из 10 элементов случайными числами в интервале [-10..10] и сделать реверс всех элементов, кроме последнего.
Пример:
Исходный массив: -5 3 10 -4 -6 8 -10 1 0 4 Результат: 0 1 -10 8 -6 -4 10 3 -5 4
[Название файла: taskArray10.pas
]
Выбор элементов и сохранение в другой массив
Пример: найти в массиве элементы, удовлетворяющие некоторому условию (например, отрицательные), и скопировать их в другой массив
Решение:
Решение: подсчитывать количество найденных элементов с помощью счетчика count, очередной элемент устанавливать на место B[count]. Переменой count необходимо присвоить 1.
Вывод массива B:
writeln('Выбранные элементы'); for i:=1 to count-1 do write(B[i], ' ')
PascalABC.NET
:
Процедура SetLength()
:
// ... for var i := 0 to a.length - 1 do if a[i] < 0 then begin b[j] := a[i]; j += 1; end; SetLength(b, j);
Задача Array 11. Заполнить массив случайными числами в интервале [20,100] и записать в другой массив все числа, которые оканчиваются на 0.
Пример:
Исходный массив: 40 57 30 71 84 Заканчиваются на 0: 40 30
[Название файла: taskArray11.pas
]
Сортировка элементов массива
Сортировка методом «Пузырька»
- В таком типе сортировок массив представляется в виде воды, маленькие элементы — пузырьки в воде, которые всплывают наверх (самые легкие).
- При первой итерации цикла элементы массива попарно сравниваются между собой:предпоследний с последним, пред предпоследний с предпоследним и т.д. Если предшествующий элемент оказывается больше последующего, то производится их обмен.
- При второй итерации цикла нет надобности сравнивать последний элемент с предпоследним. Последний элемент уже стоит на своем месте, он самый большой. Значит, число сравнений будет на одно меньше. То же самое касается каждой последующей итерации.
Pascal | PascalABC.NET | ||||
|
|
Задача Array 12. Заполнить массив из 10 элементов случайными числами в интервале [0..100] и отсортировать первую половину массива по возрастанию, а вторую – по убыванию (методом ‘Пузырька’).
Пример: Исходный массив: 14 25 13 30 76 58 32 11 41 97 Результат: 13 14 25 30 76 97 58 41 32 11
[Название файла: taskArray12.pas
]
Сортировка методом выбора
- в массиве ищется минимальный элемент и ставится на первое место (меняется местами с A[1]);
- среди оставшихся элементов также производится поиск минимального, который ставится на второе место (меняется местами с A[2]) и т.д.
Pascal | PascalABC.NET | ||||
|
|
Задача Array 13: Заполнить массив из 10 элементов случайными числами в интервале [0..50] и отсортировать его по возрастанию суммы цифр
Пример: Исходный массив: 14 25 13 12 76 58 21 87 10 98 Результат: 10 21 12 13 14 25 76 58 87 98
[Название файла: taskArray13.pas
]
PascalABC.NET
:
Стандартная процедура sort():
Sort(a); SortByDescending(a);
Быстрая сортировка или quick sort
Алгоритм:
- Выбирается и запоминается средний элемент массива (присвоим X):
- Инициализируем две переменные (будущие индексы массива): L:=1, R:=N (N — количество элементов).
- Увеличиваем L и ищем первый элемент A[L], который больше либо равен X (в итоге он должен находиться справа).
- Уменьшаем R и ищем элемент A[R], который меньше либо равен X (в итоге он должен находиться слева).
- Смотрим, если L<=R, то меняем местами A[L] и A[R], возвращаемся к пункту 3.
Выполнение на Паскале:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
procedure QSort ( first, last: integer); var L, R, c, X: integer; begin if first < last then begin X:= A[(first + last) div 2]; L:= first; R:= last; while L <= R do begin while A[L] < X do L:= L + 1; while A[R] > X do R:= R - 1; if L <= R then begin c:= A[L]; A[L]:= A[R]; A[R]:= c; L:= L + 1; R:= R - 1; end; end; QSort(first, R); QSort(L, last); end; end. |
Задача Array 14:
Заполнить массив из 10 элементов случайными числами в интервале [-50..50] и отсортировать его с помощью алгоритма быстрой сортировки.
[Название файла: taskArray14.pas
]