함수 rand between()

rand_between
randint
  • rand_between(1,6) → 1 or 2 or 3 or 4 or 5 or 6 (Uniform distribution)

1 Bash[ | ]

MIN=1
MAX=6
R=$(($MIN+RANDOM%($MAX-$MIN+1)))
echo $R
# 1-6
function rand_between() {
  echo $(($1+RANDOM%($2-$1+1)))
}
R=`rand_between 1 6`
echo $R
# 1-6

2 Excel[ | ]

=RANDBETWEEN(1,6)

3 Go[ | ]

package main

import (
	"fmt"
	"math/rand"
)

func randBetween(min, max int) int {
	return rand.Intn(max-min+1) + min
}

func main() {
	fmt.Println(randBetween(1, 6))
}

4 Java[ | ]

import java.util.Random;

private static final Random rng = new Random();

public static int randBetween(int min, int max) {
  return min + rng.nextInt(max-min+1);
}

5 JavaScript[ | ]

function rand_between(min, max) {
  return min + Math.ceil( (max-min+1) * Math.random() ) - 1;
}
var r = Math.floor(Math.random() * 3);
// range 0~2

6 Lua[ | ]

local r = math.random(1, 6)
print(r) -- 1-6

7 Objective-C[ | ]

- (int)rand_between:(int)min and:(int)max {
  return min + arc4random() % (max - min + 1)
}

8 Perl[ | ]

sub rand_between {
  my ($min, $max) = @_;
  return $min + int(rand($max-$min+1));
}

9 PHP[ | ]

$r = mt_rand(1,6);
$r = rand(1,6);

10 Python[ | ]

import random
r = random.randint(1,6)
from random import randint
r = randint(1,6)

11 Ruby[ | ]

def rand_between(min, max)
  min + rand(max-min+1)
end

12 Windows Batch[ | ]

@echo off
SET MIN=1
SET MAX=6
SET /A R=%RANDOM% * %MAX% / 32768 + %MIN%
echo %R%
REM 1-6

13 SQL[ | ]

13.1 MySQL[ | ]

SELECT ROUND( RAND() * (10-6) +6 )

14 같이 보기[ | ]

15 참고[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}