Jump to content

random numbers without repeating


Rapide
 Share

Recommended Posts

How to generate single digit numbers without repeating? I have wrote this much so far :

$min=1

$max=9

 $result = Consolewrite(Random($min,$max,1))

$temp = $result 

I do not know what to do next. To be more specific, the numbers should repeat, but should not repeat (same number) one after the other. The new result (number) should always be not equal to previous result.

Example:

1 2 9 9 ❌

1 9 2 9 ✔️

Thank you^^

 

 

Link to comment
Share on other sites

Here's one of many ways that it could be done.

Example()
Func Example()
    Const $kNUMBER_OF_DIGITS = 6

    Local $iRandomDigit = 0
    Local $sDigits = ""

    While StringLen($sDigits) < $kNUMBER_OF_DIGITS
        $iRandomDigit = Random(0, 9, 1)
        If StringRight($sDigits, 1) <> $iRandomDigit Then $sDigits &= String($iRandomDigit)
    WEnd

    ConsoleWrite(StringFormat("%s random digits: %s", $kNUMBER_OF_DIGITS, $sDigits) & @CRLF)
EndFunc

 

Link to comment
Share on other sites

pretty much the same thing in a For loop instead of a while loop.  Could probably also use a Do loop in a similar manner to the solution above if you wanted the practice.

$min=1
$max=9
local $last , $out
$EndStringLength = 5

For $i = 1 to $EndStringLength

$n = Random($min,$max,1)
    If $n=$last Then
       $i -= 1
       ContinueLoop
    EndIf
$out &= $n
$last = $n

Next

msgbox(0, '' , $out)

 

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Link to comment
Share on other sites

That isn't a pseudo-random sequence then.

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

  • Moderators

Rapide,

Just use _ArrayShuffle:

#include <Array.au3>

Global $aArray[9]

For $i = 0 To 8
    $aArray[$i] = $i + 1
Next

_ArrayDisplay($aArray, "Loaded", Default, 8)

_ArrayShuffle($aArray)

_ArrayDisplay($aArray, "Shuffled", Default, 8)

The well-known algorithm used for shuffling is as good as you can get.

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

  • Moderators

mikell,

True, I only read the first line of the post ("How to generate single digit numbers without repeating") and not the completely different requirement stated later ("To be more specific, the numbers should repeat, but should not repeat (same number) one after the other").

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

1 hour ago, IAMK said:

It still is, just with 1 more condition.

Hence it isn't a pseudo-random sequence!

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

@jchd

Just joking with trying this one-liner. But is this correct ?

Msgbox(0,"",  Execute(StringRegExpReplace('aaaa', '(^|a)', _ 
    "('$1'=='' ? Eval(Assign('prev', '0')) : (Assign('s', StringReplace('123456789', Eval('prev'), '')) * Assign('a', StringSplit(Eval('s'), '')[Random(1, StringLen(Eval('s')) ,1)]) * Assign('prev', Eval('a'), 'mikell was here') * Eval('a'))) & ") & "''") )

 

Link to comment
Share on other sites

@jchd Correct me if I'm wrong, but it's pseudo-random, because it's not entirely random. The reason it's not random is because it has conditions; The usual ones being a key (usually time and date) and a formula. Hence, adding more conditions while still containing some "random" factor would still make it pseudo-random.

Link to comment
Share on other sites

... my 2 cents

Local $min = 1, $max = 9

For $i = 1 To 40
    ConsoleWrite(_RandomMod($min, $max) & " ")
Next
ConsoleWrite(@CRLF)

Func _RandomMod($min, $max)
    Local Static $iNotOnNextRnd = Random($min, $max, 1)
    $iNotOnNextRnd = Mod(Random($iNotOnNextRnd + 1, $iNotOnNextRnd + ($max - $min), 1), $max + 1)
    $iNotOnNextRnd += ($min * ($iNotOnNextRnd < $min))
    Return $iNotOnNextRnd
EndFunc   ;==>_RandomMod

 

Edited by Chimp
changed var name

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Link to comment
Share on other sites

I liked the array idea too, it seems useful if you ever needed to manipulate the original set

#include<array.au3>
local $rnd=[0,1,2,3,4,5,6,7,8,9]
$old = -1
$out = ""
$length = 7

For $i = 1 to $length
  _ArrayShuffle($rnd)
  $pop = _ArrayPop($rnd)
    If $old > -1 Then _ArrayAdd($rnd , $old)
  $old = $pop
  $out &= $pop
Next

msgbox(0,'', $out)

 

Edited by iamtheky

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Link to comment
Share on other sites

1 hour ago, IAMK said:

Correct me if I'm wrong, but it's pseudo-random, because it's not entirely random. The reason it's not random is because it has conditions; The usual ones being a key (usually time and date) and a formula. Hence, adding more conditions while still containing some "random" factor would still make it pseudo-random.

This isn't the semantic of "pseudo-random" one can find in any mathematical source I know of. The term "pseudo-" is to be understood as opposed to "naturally-". For instance true random generators may be based on some radioelement decay, something which is physically proven random. Careful sampling of genuine white noise can be another "natural" source.

In IT, "pseudo" refers to an algorithmic source, for instance the one used by AutoIt Random() function, because general-purpose computers have long been driven by determinism, something difficult to use to mimic the random characteristic of some physical phenomenoms.

Uncommon requirements like those of the OP could possibly be coined "non-stuttering-biased pseudo random". Resulting sequences are an infinitely small subset of all truly random sequences build from the same digits set.

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

See RdRand for an approach that samples on-chip thermal noise, smilar to what @jchd suggested.

.

Link to comment
Share on other sites

Random is pretty good at the simple distribution test:

; 100,000 non-repeating digits
Local $s
For $i = 1 To 100000
    $s &= _NextRndDigit()
Next
; ConsoleWrite($s & @LF)        ; yes that's a loong string, just for checking the distribution below
Local $aDigits = StringSplit($s, "", 2)
_ArraySort($aDigits)
Local $s = _ArrayToString($aDigits, "")
Local $aHisto[9]
For $i = 0 To 8
    $aHisto[$i] = StringLen(StringRegExp($s, ($i + 1) & "+", 1)[0])
Next
_ArrayDisplay($aHisto)

Func _NextRndDigit()
    Static $aDigits = [1, 2, 3, 4, 5, 6, 7, 8, 9], $iStart = 0
    Local $iIndex = Random($iStart, 8, 1)
    $iStart = 1
    Local $iDigit = $aDigits[$iIndex]
    Local $iOld = $aDigits[0]
    $aDigits[0] = $iDigit
    $aDigits[$iIndex] = $iOld
    Return $iDigit
EndFunc

 

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...