• 0

Random Number Generator


Question

24 answers to this question

Recommended Posts

  • 0

It'd help to know what language you need it in. Either I'm blind or you added that VB note as I posted this.

In C# I'd do:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> usedNumbers = new List<int>();
            string outv = "";
            Random r = new Random();

            for (int i = 0; i < 100; i++)
            {
                calc:
                int nextVal = r.Next(0, 101);
                if (usedNumbers.Contains(nextVal)) goto calc;
                outv += nextVal.ToString() + " ";
                usedNumbers.Add(nextVal);
            }
            outv = outv.Substring(0, outv.Length - 1);
            Console.Write(outv);
        }
    }
}

Here it is converted to VB:

Imports System.Collections.Generic
Imports System.Linq
Imports System.Text

Namespace Test
	Class Program
		Private Shared Sub Main(args As String())
			Dim usedNumbers As New List(Of Integer)()
			Dim outv As String = ""
			Dim r As New Random()

			For i As Integer = 0 To 99
				calc:
				Dim nextVal As Integer = r.[Next](0, 101)
				If usedNumbers.Contains(nextVal) Then
					GoTo calc
				End If
				outv += nextVal.ToString() & " "
				usedNumbers.Add(nextVal)
			Next
			outv = outv.Substring(0, outv.Length - 1)
			Console.Write(outv)
		End Sub
	End Class
End Namespace

  • 0
  On 03/10/2010 at 00:50, unr3al said:

I need to make a random number generator where it displays all the numbers 1-100 in a text box. All numbers need to be displayed once in a random order.

This has to be coded in visual basic. Can anyone help me out with the code?

Much appreciated if you do help!

It couldn't be easier :D Lucky for you VB already has a sort of RNG so really all you have to do is work on the presentation...

I found this doing a google on 'visual basic rng':

Private Function RandomNumber() as Integer

Randomize Timer

RandomNumber = Int(Rnd * 100)

End Sub

  • 0
  On 03/10/2010 at 01:00, omnicoder said:

It'd help to know what language you need it in. Either I'm blind or you added that VB note as I posted this.

In C# I'd do:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> usedNumbers = new List<int>();
            string outv = "";
            Random r = new Random();

            for (int i = 0; i < 100; i++)
            {
                calc:
                int nextVal = r.Next(0, 101);
                if (usedNumbers.Contains(nextVal)) goto calc;
                outv += nextVal.ToString() + " ";
                usedNumbers.Add(nextVal);
            }
            outv = outv.Substring(0, outv.Length - 1);
            Console.Write(outv);
        }
    }
}

Here it is converted to VB:

I'm so sorry :(

It has to be coded in VB. My fault, I updated my post.

I'd love if you could convert that to VB6.

  • 0

Private Shared Sub Main(args As String())
                        Dim usedNumbers As New List(Of Integer)()
                        Dim outv As String = ""

                        For i As Integer = 0 To 99
                                calc:
                                Dim nextVal As Integer = Rand(0, 101)
                                If usedNumbers.Contains(nextVal) Then
                                        GoTo calc
                                End If
                                outv += nextVal.ToString() & " "
                                usedNumbers.Add(nextVal)
                        Next
                        MsgBox(outv)
                End Sub

Can't test if that compiles as I no longer have VB6 but should be pretty close.

  • 0
  On 03/10/2010 at 01:06, omnicoder said:

Private Shared Sub Main(args As String())
                        Dim usedNumbers As New List(Of Integer)()
                        Dim outv As String = ""

                        For i As Integer = 0 To 99
                                calc:
                                Dim nextVal As Integer = Rand(0, 101)
                                If usedNumbers.Contains(nextVal) Then
                                        GoTo calc
                                End If
                                outv += nextVal.ToString() & " "
                                usedNumbers.Add(nextVal)
                        Next
                        MsgBox(outv)
                End Sub

Can't test if that compiles as I no longer have VB6 but should be pretty close.

I can't get it to compile. I'm a VB6 beginner, so I might be doing something wrong.

I appreciate your help though.

  • 0

Try

Private Sub Generate(args As String)
                        Dim usedNumbers As New List(Of Integer)()
                        Dim outv As String = ""

                        For i As Integer = 0 To 99
                                calc:
                                Dim nextVal As Integer = Rand(0, 101)
                                If usedNumbers.Contains(nextVal) Then
                                        GoTo calc
                                End If
                                outv = outv + nextVal.ToString() & " "
                                usedNumbers.Add(nextVal)
                        Next
                        MsgBox(outv)
                End Sub

  • 0
  On 03/10/2010 at 01:17, omnicoder said:

Try

Private Sub Generate(args As String)
                        Dim usedNumbers As New List(Of Integer)()
                        Dim outv As String = ""

                        For i As Integer = 0 To 99
                                calc:
                                Dim nextVal As Integer = Rand(0, 101)
                                If usedNumbers.Contains(nextVal) Then
                                        GoTo calc
                                End If
                                outv = outv + nextVal.ToString() & " "
                                usedNumbers.Add(nextVal)
                        Next
                        MsgBox(outv)
                End Sub

20896312.jpg

  • 0
  On 03/10/2010 at 01:22, omnicoder said:

Ah VB6 doesn't have a List class. I'll have to change it to an array. Gimmie a minute.

From the original post, and admittedly my recent programming skills are virtually non-existent as I learned to code pre-Windows, the above code won't do exactly what is requested.

As I understand the task,

"I need to make a random number generator where it displays all the numbers 1-100 in a text box. All numbers need to be displayed once in a random order."

Generating 100 random numbers between one and 100 won't guarantee there won't be repeats.

Instead, and I can't write the code for it, simply put the numbers 1-100 in an array, list, or whatever... Then you simply perform say, 100 shuffles of 1 number for another in the list, each shuffle randomly determined, then spit the results out. The exact number of shuffles is arbitary but you'd want enough to theoretically at least shuffle each number once. So shuffling each number in the list at least once would ensure about as random as you're gonna get.

  • 0
  On 03/10/2010 at 01:38, krasch said:

From the original post, and admittedly my recent programming skills are virtually non-existent as I learned to code pre-Windows, the above code won't do exactly what is requested.

As I understand the task,

"I need to make a random number generator where it displays all the numbers 1-100 in a text box. All numbers need to be displayed once in a random order."

Generating 100 random numbers between one and 100 won't guarantee there won't be repeats.

Instead, and I can't write the code for it, simply put the numbers 1-100 in an array, list, or whatever... Then you simply perform say, 100 shuffles of 1 number for another in the list, each shuffle randomly determined, then spit the results out. The exact number of shuffles is arbitary but you'd want enough to theoretically at least shuffle each number once. So shuffling each number in the list at least once would ensure about as random as you're gonna get.

omnicoder's code ensures each number will only be displayed once. It uses a calculation to determine a random number between 1 and 100. It stores displayed numbers in a list (an array, in the case of VB6) and checks the list before showing the next number, each time; if the number has been displayed, it will search for another number between 1 and 100.

His C# code works very nicely.

  • 0
  On 03/10/2010 at 01:41, Calum said:

omnicoder's code ensures each number will only be displayed once. It uses a calculation to determine a random number between 1 and 100. It stores displayed numbers in a list (an array, in the case of VB6) and checks the list before showing the next number, each time; if the number has been displayed, it will search for another number between 1 and 100.

His C# code works very nicely.

I need omnicoder's code to work in VB6!

Thanks for the replies guys.

  • 0
  On 03/10/2010 at 01:45, unr3al said:

I need omnicoder's code to work in VB6!

Thanks for the replies guys.

Out of curiosity, how much experience have you had with both programming and VB6? I'm just wondering, again out of curiosity, do you understand exactly what omnicoder's code does? If not, it may be beneficial if it is explained to you, so you learn from this :)

  • 0
  On 03/10/2010 at 01:50, Calum said:

Out of curiosity, how much experience have you had with both programming and VB6? I'm just wondering, again out of curiosity, do you understand exactly what omnicoder's code does? If not, it may be beneficial if it is explained to you, so you learn from this :)

I just started a couple of weeks ago.

I don't have any experience in C#; Visual Basic 6 is currently the only language I have experience with.

Explanations would help!

  • 0
  On 03/10/2010 at 01:53, unr3al said:

I just started a couple of weeks ago.

I don't have any experience in C#; Visual Basic 6 is currently the only language I have experience with.

Explanations would help!

I see. Once you and omnicoder have sorted out code which works and functions as it should, make sure you understand every line - every single part of it - and if not, ask questions here until you do :)

It really is important you understand what every line of this code does and why certain decisions were made. When I was first starting out learning programming, I was guilty of just copying code of those that helped me without ensuring I understood it; that only made it harder for me in the longrun (although I'm decent at it now and ensure I learn as much as possible).

  • 0
  On 03/10/2010 at 01:58, Calum said:

I see. Once you and omnicoder have sorted out code which works and functions as it should, make sure you understand every line - every single part of it - and if not, ask questions here until you do :)

It really is important you understand what every line of this code does and why certain decisions were made. When I was first starting out learning programming, I was guilty of just copying code of those that helped me without ensuring I understood it; that only made it harder for me in the longrun (although I'm decent at it now and ensure I learn as much as possible).

Thanks for the advice.

  • 0

This is a VBS script that will generate a radom list of 100 numbers.

It uses the Randomize method and Dictionary object, you should be

able to convert it to your VB 6 project.

Run this script using Cscript.exe or you will get a lot of messageboxes.

Save As RandomNumbers.vbs

Dim Dic :Set Dic = CreateObject("Scripting.Dictionary")
Dim a,i
 Randomize
    For i = 0 To 99
     a = Int((100 - i + 1) * Rnd + 1)
     If Not Dic.Exists(a) Then
      Dic.Add  a, a 
      WScript.Echo a
      WScript.Sleep 100
     End If
    Next

  • 0
  On 03/10/2010 at 16:54, jake1eye said:

This is a VBS script that will generate a radom list of 100 numbers.

It uses the Randomize method and Dictionary object, you should be

able to convert it to your VB 6 project.

Run this script using Cscript.exe or you will get a lot of messageboxes.

Save As RandomNumbers.vbs

Dim Dic :Set Dic = CreateObject("Scripting.Dictionary")
Dim a,i
 Randomize
    For i = 0 To 99
     a = Int((100 - i + 1) * Rnd + 1)
     If Not Dic.Exists(a) Then
      Dic.Add  a, a 
      WScript.Echo a
      WScript.Sleep 100
     End If
    Next

Could you please convert this to VB6?

  • 0

It would be a lot more efficient to generate an array of numbers from 1 to 100, and then shuffle it for a while. It'd result in O(n) complexity rather than O(n?), like the suggested solution.

Generating an array of 100 numbers from 1 to 100 is trivial.

As for shuffling, generate two random numbers between 0 and 99 (or 1 to 100 depending on whether VB6 indexes from 0 or 1, I'm not sure), and then swap the values located at these indexes in the array. Repeat at least 50 times. The more you repeat the more random it gets.

  • 0

i'm not trying to be an asshat here.. but these type of threads should be closed.

this is not helping you learn anything, and the type of problem you are solving is clearly a typical school/uni assignment..

i would have hoped people to have more sense than to just post up answer for you huh.gif

in any case, there is PLENTY enough detail in this thread to set you on your way to be able to do it in VB6.. you don't even have to work out how to solve the issue, but just write it on in another language..

good luck :)

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Yeah, I've had a Recycle Bin on my taskbar since XP and till last year when I got a new laptop with Windows 11. It was especially useful for touch workflow - I could drag files into Recycle Bin from anywhere because my Taskbar is always visible, unlike desktop icons.
    • Not after SP1. There was a legitimate file copy issue prior.
    • Microsoft 365 security in the spotlight after Washington Post hack by Paul Hill The Washington Post has come under cyberattack which saw Microsoft email accounts of several journalists get compromised. The attack, which was discovered last Thursday, is believed to have been conducted by a foreign government due to the topics the journalists cover, including national security, economic policy, and China. Following the hack, the passwords on the affected accounts were reset to prevent access. The fact that a Microsoft work email account was potentially hacked strongly suggests The Washington Post utilizes Microsoft 365, which makes us question the security of Microsoft’s widely used enterprise services. Given that Microsoft 365 is very popular, it is a hot target for attackers. Microsoft's enterprise security offerings and challenges As the investigation into the cyberattack is still ongoing, just how attackers gained access to the accounts of the journalists is unknown, however, Microsoft 365 does have multiple layers of protection that ought to keep journalists safe. One of the security tools is Microsoft Defender for Office 365. If the hackers tried to gain access with malicious links, Defender provides protection against any malicious attachments, links, or email-based phishing attempts with the Advanced Threat Protection feature. Defender also helps to protect against malware that could be used to target journalists at The Washington Post. Another security measure in place is Entra ID which helps enterprises defend against identity-based attacks. Some key features of Entra ID include multi-factor authentication which protects accounts even if a password is compromised, and there are granular access policies that help to limit logins from outside certain locations, unknown devices, or limit which apps can be used. While Microsoft does offer plenty of security technologies with M365, hacks can still take place due to misconfiguration, user-error, or through the exploitation of zero-day vulnerabilities. Essentially, it requires efforts from both Microsoft and the customer to maintain security. Lessons for organizations using Microsoft 365 The incident over at The Washington Post serves as a stark reminder that all organizations, not just news organizations, should audit and strengthen their security setups. Some of the most important security measures you can put in place include mandatory multi-factor authentication (MFA) for all users, especially for privileged accounts; strong password rules such as using letters, numbers, and symbols; regular security awareness training; and installing any security updates in a timely manner. Many of the cyberattacks that we learn about from companies like Microsoft involve hackers taking advantage of the human in the equation, such as being tricked into sharing passwords or sharing sensitive information due to trickery on behalf of the hackers. This highlights that employee training is crucial in protecting systems and that Microsoft’s technologies, as advanced as they are, can’t mitigate all attacks 100 percent of the time.
    • Comments like these are genuinely fascinating to me because they're so far from anything I experience as a daily user of Win 11 since the first public beta. AI stuff? Have it turned off completely, never pops up anywhere. Forced MS account? Yes, they strongly recommend it and kinda push it lately during big updates and such, but it's still not forced. Pop up dialogs when you're not using Edge? Yeah, I vaguely remember seeing some reminders about using Edge a long time ago. I just clicked them away and kept using Vivaldi as usual (but frankly, I'd still much rather use Edge than Chrome - which I'm forced to use at work - I've grown to dislike Google a lot more than Microsoft lately, even if I am still deeply rooted in their ecosystem unfortunately). Awful context menus? A single simple tweak will get you the old context menus. Search in Windows using Bing? People use search in Windows for anything else than to search for local files or apps? Why? I just don't get a lot of the complains people have about Win 11.
    • Nice, but if you change the colour, the folder no longer shows image preview on the actual folder icon.
  • Recent Achievements

    • Explorer
      Legend20 went up a rank
      Explorer
    • One Month Later
      jezzzy earned a badge
      One Month Later
    • First Post
      CSpera earned a badge
      First Post
    • One Month Later
      MIR JOHNNY BLAZE earned a badge
      One Month Later
    • Apprentice
      Wireless wookie went up a rank
      Apprentice
  • Popular Contributors

    1. 1
      +primortal
      618
    2. 2
      ATLien_0
      277
    3. 3
      +FloatingFatMan
      179
    4. 4
      Michael Scrip
      151
    5. 5
      Steven P.
      115
  • Tell a friend

    Love Neowin? Tell a friend!