randomIntsRange.mjs

  1. import isint from './isint.mjs'
  2. import ispint from './ispint.mjs'
  3. import cint from './cint.mjs'
  4. import random from './random.mjs'
  5. /**
  6. * 產生位於指定範圍內隨機整數陣列,各元素值域為[vstart,vend],代表值會大於等於vstart且小於等於vend
  7. *
  8. * Unit Test: {@link https://github.com/yuda-lyu/wsemi/blob/master/test/randomIntsRange.test.mjs Github}
  9. * @memberOf wsemi
  10. * @param {Integer} [vstart=0] 輸入範圍最小值整數,預設0
  11. * @param {Integer} [vend=100] 輸入範圍最大值整數,預設100
  12. * @param {Integer} [n=1] 輸入產生數量整數,預設1
  13. * @returns {Integer} 回傳位於指定範圍內隨機整數
  14. * @example
  15. *
  16. * let rs
  17. *
  18. * rs = randomIntsRange()
  19. * console.log('randomIntsRange', rs)
  20. * // => randomIntsRange [ [0,100] ] (預設範圍為0至100)
  21. *
  22. * rs = randomIntsRange(0, 100)
  23. * console.log('randomIntsRange(0, 100)', rs)
  24. * // => randomIntsRange(0, 100) [ [0,100] ]
  25. *
  26. * rs = randomIntsRange(0, 100, 2)
  27. * console.log('randomIntsRange(0, 100, 2)', rs)
  28. * // => randomIntsRange(0, 100, 2) [ [0,100], [0,100] ]
  29. *
  30. * rs = randomIntsRange(123, 4567)
  31. * console.log('randomIntsRange(123, 4567)', rs)
  32. * // => randomIntsRange(123, 4567) [ [123,4567] ]
  33. *
  34. * rs = randomIntsRange(123, 4567, 2)
  35. * console.log('randomIntsRange(123, 4567, 2)', rs)
  36. * // => randomIntsRange(123, 4567, 2) [ [123,4567], [123,4567] ]
  37. *
  38. */
  39. function randomIntsRange(vstart = 0, vend = 100, n) {
  40. //vstart
  41. if (!isint(vstart)) {
  42. vstart = 0
  43. }
  44. vstart = cint(vstart)
  45. //vend
  46. if (!isint(vend)) {
  47. vend = 100
  48. }
  49. vend = cint(vend)
  50. //n
  51. if (!ispint(n)) {
  52. n = 1
  53. }
  54. n = cint(n)
  55. //check
  56. if (vstart > vend) {
  57. throw new Error(`vstart[${vstart}] > vend[${vend}]`)
  58. }
  59. //rs
  60. let rs = []
  61. for (let i = 1; i <= n; i++) {
  62. //random, [0,1)
  63. let pr = random()
  64. //r
  65. let rng = vend - vstart + 1 //要額外+1才能使取ceil時讓各整數出現機率一致
  66. let r = pr * rng + vstart
  67. r = Math.floor(r)
  68. //push
  69. rs.push(r)
  70. }
  71. return rs
  72. }
  73. export default randomIntsRange