생활

로또번호 뽑기

1~45 중 중복 없는 6개 번호를 원하는 게임 수만큼 무작위로 바로 뽑아볼 수 있습니다.

입력값은 브라우저에서만 계산되며 서버로 전송되지 않습니다.

1~45 중 중복 없는 6개 번호를 뽑습니다.

추첨 결과

—

번호 뽑기를 눌러주세요.

재미용 도구입니다. 당첨을 보장하지 않으며 구매는 본인 판단과 책임으로 해주세요.

최근 입력0/8

입력이 3초간 멈추면 이 브라우저에 자동 저장됩니다.

입력이 3초간 멈추면 이 브라우저에만 저장됩니다. 항목을 클릭하면 그때의 입력값으로 복원됩니다.

이 도구는 이렇게 계산합니다

결과를 믿기 전에 계산 원리와 가정을 확인하세요.

  1. 브라우저의 crypto.getRandomValues로 난수를 만들고, 1~45 범위에서 중복 없이 6개를 선택합니다.
  2. 번호는 오름차순으로 정렬해 보여줍니다.
  3. 게임 수는 1·5·10게임 중 선택할 수 있습니다.

자주 묻는 질문

번호는 정말 무작위인가요?

브라우저의 암호학적 난수 생성기(crypto.getRandomValues)를 사용해 1~45 범위에서 중복 없이 6개를 뽑습니다.

이 번호를 쓰면 당첨 확률이 높아지나요?

아니요. 어떤 번호 조합도 당첨 확률을 높이지 않습니다. 이 도구는 재미용이며 구매는 본인 판단과 책임으로 해주세요.

제작 코드

이 페이지에서 실제로 사용하는 Vue 3 컴포넌트입니다. 계산식과 화면 구성을 그대로 확인하고 복사할 수 있습니다.

도구 전체 코드 보기
<script setup lang="ts">
import { computed, ref } from 'vue'
import CalculatorHistory from '~/components/calculators/CalculatorHistory.vue'

const count = ref(5)
const games = ref<number[][]>([])
const copied = ref(false)

function randomInt(max: number): number {
  const cryptoObj = globalThis.crypto
  if (!cryptoObj?.getRandomValues) {
    return Math.floor(Math.random() * max)
  }
  const limit = Math.floor(0x100000000 / max) * max
  const buffer = new Uint32Array(1)
  do {
    cryptoObj.getRandomValues(buffer)
  } while (buffer[0] >= limit)
  return buffer[0] % max
}

function generate() {
  const gameCount = Math.max(1, Math.min(10, Math.floor(Number(count.value) || 0)))
  games.value = Array.from({ length: gameCount }, () => {
    const numbers = new Set<number>()
    while (numbers.size < 6) numbers.add(randomInt(45) + 1)
    return [...numbers].sort((a, b) => a - b)
  })
  copied.value = false
}

async function copy() {
  if (!games.value.length) return
  const text = games.value
    .map((numbers, index) => `${index + 1}게임: ${numbers.join(' ')}`)
    .join('\n')
  try {
    await navigator.clipboard.writeText(text)
    copied.value = true
    setTimeout(() => { copied.value = false }, 1600)
  } catch {
    copied.value = false
  }
}

const historySnapshot = computed(() => ({ count: count.value, games: games.value }))
const historyLabel = computed(() => `${count.value}게임${games.value.length ? ` · ${games.value[0]?.join(' ') ?? ''}` : ''}`)
function restoreHistory(data: Record<string, unknown>) {
  count.value = Number(data.count) || 5
  const rawGames = Array.isArray(data.games) ? data.games : []
  games.value = rawGames
    .filter((game): game is number[] => Array.isArray(game))
    .map((game) => game.map(Number).filter((number) => Number.isInteger(number) && number >= 1 && number <= 45).slice(0, 6))
    .filter((game) => game.length === 6)
}
</script>

<template>
  <div class="calc-card">
    <div class="calc-grid">
      <div class="calc-form">
        <div class="calc-field">
          <label for="lotto-count">게임 수</label>
          <select id="lotto-count" v-model.number="count" class="calc-select">
            <option :value="1">1게임</option>
            <option :value="5">5게임</option>
            <option :value="10">10게임</option>
          </select>
          <p class="calc-hint">1~45 중 중복 없는 6개 번호를 뽑습니다.</p>
        </div>
        <div class="calc-actions">
          <button type="button" class="krds-btn medium primary" @click="generate">번호 뽑기</button>
          <button type="button" class="krds-btn medium secondary" :disabled="!games.length" @click="copy">
            {{ copied ? '복사됨' : '복사' }}
          </button>
        </div>
      </div>

      <div class="calc-result" aria-live="polite">
        <template v-if="games.length">
          <p class="calc-result-label">추첨 결과</p>
          <ul class="calc-lotto-list">
            <li v-for="(numbers, index) in games" :key="index" class="calc-lotto-row">
              <span class="calc-lotto-label">{{ index + 1 }}게임</span>
              <span v-for="number in numbers" :key="number" class="calc-lotto-ball">{{ number }}</span>
            </li>
          </ul>
        </template>
        <template v-else>
          <p class="calc-result-label">추첨 결과</p>
          <p class="calc-result-hero">—</p>
          <p class="calc-result-sub">번호 뽑기를 눌러주세요.</p>
        </template>
      </div>
    </div>

    <p class="calc-note">재미용 도구입니다. 당첨을 보장하지 않으며 구매는 본인 판단과 책임으로 해주세요.</p>
  </div>

  <CalculatorHistory tool="lotto" :snapshot="historySnapshot" :label="historyLabel" @restore="restoreHistory" />
</template>
공통 입력 기록 컴포넌트 보기
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'

interface HistoryEntry {
  id: string
  at: number
  label: string
  data: Record<string, unknown>
}

const props = defineProps<{
  tool: string
  snapshot: Record<string, unknown>
  label: string
}>()

const emit = defineEmits<{ restore: [data: Record<string, unknown>] }>()

const MAX_ENTRIES = 8
const SAVE_DELAY = 3000

const entries = ref<HistoryEntry[]>([])
const ready = ref(false)
const restoredId = ref('')
const storageKey = computed(() => `euninfo.calc-history.v1:${props.tool}`)
let saveTimer: ReturnType<typeof setTimeout> | undefined
let initialTimer: ReturnType<typeof setTimeout> | undefined
let initialSnapshot = ''

onMounted(() => {
  load()
  ready.value = true
  // 부모의 onMounted 기본값 주입(날짜 등) 뒤에 초기 상태를 캡처한다.
  initialTimer = setTimeout(() => {
    initialSnapshot = JSON.stringify(props.snapshot)
  }, 0)
})

onBeforeUnmount(() => {
  if (saveTimer) clearTimeout(saveTimer)
  if (initialTimer) clearTimeout(initialTimer)
})

watch(
  () => props.snapshot,
  () => {
    if (!ready.value) return
    if (saveTimer) clearTimeout(saveTimer)
    saveTimer = setTimeout(save, SAVE_DELAY)
  },
  { deep: true },
)

function load() {
  try {
    const raw = localStorage.getItem(storageKey.value)
    if (!raw) return
    const parsed: unknown = JSON.parse(raw)
    if (!Array.isArray(parsed)) return
    entries.value = parsed
      .filter((item): item is HistoryEntry => {
        if (!item || typeof item !== 'object') return false
        const entry = item as Partial<HistoryEntry>
        return typeof entry.id === 'string' && typeof entry.at === 'number' && typeof entry.label === 'string' && !!entry.data && typeof entry.data === 'object'
      })
      .slice(0, MAX_ENTRIES)
  } catch {
    entries.value = []
  }
}

function persist() {
  try {
    localStorage.setItem(storageKey.value, JSON.stringify(entries.value))
  } catch {
    // 저장 공간이 없거나 브라우저가 막은 경우 조용히 무시한다.
  }
}

function save() {
  const data = JSON.parse(JSON.stringify(props.snapshot)) as Record<string, unknown>
  const json = JSON.stringify(data)
  if (!entries.value.length && json === initialSnapshot) return

  const now = Date.now()
  const label = props.label.trim() || '최근 입력'
  const existing = entries.value.find((entry) => JSON.stringify(entry.data) === json)

  if (existing) {
    existing.at = now
    existing.label = label
    entries.value = [existing, ...entries.value.filter((entry) => entry.id !== existing.id)]
  } else {
    entries.value = [
      {
        id: `${now}-${Math.random().toString(36).slice(2, 8)}`,
        at: now,
        label,
        data,
      },
      ...entries.value,
    ].slice(0, MAX_ENTRIES)
  }
  persist()
}

function restore(entry: HistoryEntry) {
  emit('restore', JSON.parse(JSON.stringify(entry.data)) as Record<string, unknown>)
  restoredId.value = entry.id
  setTimeout(() => {
    if (restoredId.value === entry.id) restoredId.value = ''
  }, 1500)
}

function remove(id: string) {
  entries.value = entries.value.filter((entry) => entry.id !== id)
  persist()
}

function clear() {
  entries.value = []
  try {
    localStorage.removeItem(storageKey.value)
  } catch {
    // ignore
  }
}

function formatTime(at: number) {
  return new Intl.DateTimeFormat('ko-KR', {
    month: 'numeric',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  }).format(new Date(at))
}
</script>

<template>
  <section class="calc-history" aria-label="최근 입력 기록">
    <div class="calc-history-head">
      <strong>최근 입력</strong>
      <span class="calc-history-count">{{ entries.length }}/{{ MAX_ENTRIES }}</span>
      <button v-if="entries.length" type="button" class="calc-history-clear" @click="clear">전체 삭제</button>
    </div>

    <p v-if="!entries.length" class="calc-history-empty">
      입력이 3초간 멈추면 이 브라우저에 자동 저장됩니다.
    </p>
    <ul v-else class="calc-history-list">
      <li v-for="entry in entries" :key="entry.id" class="calc-history-row" :class="{ restored: restoredId === entry.id }">
        <button type="button" class="calc-history-load" :aria-label="`${entry.label} 입력값 불러오기`" @click="restore(entry)">
          <span class="calc-history-label">{{ entry.label }}</span>
          <time class="calc-history-time">{{ formatTime(entry.at) }}</time>
        </button>
        <button type="button" class="calc-history-remove" :aria-label="`${entry.label} 기록 삭제`" @click="remove(entry.id)">×</button>
      </li>
    </ul>

    <p class="calc-history-note">
      입력이 3초간 멈추면 이 브라우저에만 저장됩니다. 항목을 클릭하면 그때의 입력값으로 복원됩니다.
    </p>
  </section>
</template>

함께 쓰면 좋은 도구

이런 계산기가 필요하세요?

우리 업무에 맞는 계산기·관리 도구를 함께 만들 수 있습니다.

의뢰 등록하기