Results 1 to 21 of 21

Thread: Reordering an array

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Dec 2022
    Posts
    72

    Reordering an array

    Hi all, I'm working on a game that when a button is pressed a number is added to an array up to 10. What I'm trying to figure out is how to reorder the array from the smallest number to the largest number each time the button is clicked. I appreciate any help. Thanks...

  2. #2

    Thread Starter
    Lively Member
    Join Date
    Dec 2022
    Posts
    72

    Re: Reordering an array

    I guess I should have said the number is a random number each button clicked.

  3. #3
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,138

    Re: Reordering an array

    You need to provide more information. What does:
    a number is added to an array up to 10
    mean? Do you mean that the value is no greater than 10 or that there are no more than 10 elements in the array? Are you resizing the array each time or starting with "blank" elements? The short answer is that you use the Array.Sort method to sort an array, but the specific details may be more complex in your specific case, but we can't know that because of a lack of information. ALWAYS show us (only) the relevant code. That's not something we should ever have to ask for.
    Last edited by jmcilhinney; Jun 12th, 2025 at 01:20 AM.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  4. #4

    Thread Starter
    Lively Member
    Join Date
    Dec 2022
    Posts
    72

    Re: Reordering an array

    I'm sorry the array is myArray(9). A random number up to 10 is added to the array each click.

  5. #5
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,175

    Re: Reordering an array

    It’s as simple as…

    Code:
    Array.Sort(myArray)
    For more information about sorting Arrays, Lists, or Collections…

    http://www.scproject.biz/Sorting_Techniques.php

  6. #6

    Thread Starter
    Lively Member
    Join Date
    Dec 2022
    Posts
    72

    Re: Reordering an array

    I know this isn't right but is this close...
    Code:
    For i = 0 To 9
         b2.Text = myArray(i).Sort
    Next

  7. #7

    Thread Starter
    Lively Member
    Join Date
    Dec 2022
    Posts
    72

    Re: Reordering an array

    Ok thanks for the help, I figured it out.

  8. #8
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,138

    Re: Reordering an array

    The possible issue with using an array and the default sort is that all your elements will be zero by default so sorting in ascending order will put all those defaults first and the other values at the end. Maybe you want the values you added first, in ascending order, followed by the default zeroes. Of course, if you use a List(Of Integer) instead of an array then there are no "empty" values. The list itself will be empty by default and only contain the items you add, so you can sort that using its own Sort method and not have to worry about anything.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  9. #9
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,901

    Re: Reordering an array

    Quote Originally Posted by PJ17limited View Post
    I know this isn't right but is this close...
    Code:
    For i = 0 To 9
         b2.Text = myArray(i).Sort
    Next
    This suggests that you want to add the items to a textbox. How about a Listbox? That would show an array somewhat better.
    My usual boring signature: Nothing

  10. #10

    Thread Starter
    Lively Member
    Join Date
    Dec 2022
    Posts
    72

    Re: Reordering an array

    Hey jmcilhinney, I was thinking about your suggestion about a list of Integers. Would this be on the right track?
    Code:
            Dim numberList = Enumerable.Range(1, 10).ToList()
            numberList(0) = TextBox1.Text
            numberList(1) = TextBox2.Text
            numberList.Sort()
            Label1.Text = numberList(0)
            Label2.Text = numberList(1)

  11. #11
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,138

    Re: Reordering an array

    No, that's not how you would use a list. What would be the point of populating the list with numbers first, then replacing those numbers? As I said, a List(Of T) is empty by default, so you can then just add the items you want it to contain. There's no reason to add dummy items. If you do that then you're just making it work like an array.
    Code:
    Dim numbers As New List(Of Integer)
    
    'numbers conntainns zero items here.
    
    numbers.Add(Convert.ToInt32(TextBox1.Text))
    numbers.Add(Convert.ToInt32(TextBox2.Text))
    
    'numbers contains two items here.
    
    numbers.Sort()
    
    Label1.Text = numbers(0)
    Label2.Text = numbers(1)
    Note that I am also adding Integers to a List(Of Integer), not Strings. If you don't already, turn Option Strict On in your project properties and also in the VS options, so it will be On by default in all future projects. That will prevent you misusing types like that and help avoid using the wrong types at the wrong times. The code I've written here still doesn't guarantee success, if the user hasn't populated those TextBoxes, but that's a different issue.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  12. #12

    Thread Starter
    Lively Member
    Join Date
    Dec 2022
    Posts
    72

    Re: Reordering an array

    Ok This is what I've got now. It's pretty much the same I think, I just changed the text input names but I get an error message wrong format.
    Code:
                Dim numbers As New List(Of Integer)
                'numbers conntainns zero items here.
                numbers.Add(Convert.ToInt32(l1.Text))
                numbers.Add(Convert.ToInt32(l2.Text))
                'numbers contains two items here.
                numbers.Sort()
                b1.Text = numbers(0)
                b2.Text = numbers(1)

  13. #13
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,175

    Re: Reordering an array

    Quote Originally Posted by PJ17limited View Post
    Ok This is what I've got now. It's pretty much the same I think, I just changed the text input names but I get an error message wrong format.
    Code:
                Dim numbers As New List(Of Integer)
                'numbers conntainns zero items here.
                numbers.Add(Convert.ToInt32(l1.Text))
                numbers.Add(Convert.ToInt32(l2.Text))
                'numbers contains two items here.
                numbers.Sort()
                b1.Text = numbers(0)
                b2.Text = numbers(1)
    That’ll work as long as l1 and l2 contain integers.
    Also, to use those correctly…

    b1.Text = numbers(0).ToString
    b2.Text = numbers(1).ToString

  14. #14
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,175

    Re: Reordering an array

    Code:
    Dim x As Integer
    If integer.TryParse(l1.Text, x) Then
        numbers.Add(x)
    Else
        MsgBox(“Invalid input”)
        Return
    End if

  15. #15

    Thread Starter
    Lively Member
    Join Date
    Dec 2022
    Posts
    72

    Re: Reordering an array

    Hay I'm really sorry, your example was correct I had a typo inputting into my first text input text. Hey man I appreciate all your help.

  16. #16

    Thread Starter
    Lively Member
    Join Date
    Dec 2022
    Posts
    72

    Re: Reordering an array

    Wow, now this brought up another issue what happens when the random generates two of the same numbers. I tried this but it didn't work.
    Code:
                For i = 0 To 2
                    If Not numbers(i).Items.Contains(SB1.Text) Then  'Check If Item already exist in list
                        l3.Text = SB1.Text
                    End If
                Next i

  17. #17

    Thread Starter
    Lively Member
    Join Date
    Dec 2022
    Posts
    72

    Re: Reordering an array

    Oops I see the problem, numbers(i).Items should have been.... numbers(i).ToString.

  18. #18
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,175

    Re: Reordering an array

    Not

    Code:
    numbers(i).Items.Contains(SB1.Text)
    Not

    Code:
    numbers(i).ToString.
    If you want to test if a number exist in your list...

    Code:
    If Not numbers.Contains(aNumber) Then

  19. #19
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,138

    Re: Reordering an array

    Quote Originally Posted by .paul. View Post
    Also, to use those correctly…

    b1.Text = numbers(0).ToString
    b2.Text = numbers(1).ToString
    Oops! Missed that part.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  20. #20
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,175

    Re: Reordering an array

    Quote Originally Posted by jmcilhinney View Post
    oops! Missed that part.
    lol...
    Last edited by .paul.; Jun 13th, 2025 at 11:17 AM.

  21. #21
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    12,129

    Re: Reordering an array

    Looking back at your original requirements, along with your updates, I would suggest that you take this approach:
    1. Create two separate collections.
    2. One collection will be a List(Of Integer) and this will represent the numbers generated after clicking the button
    3. One collection will be a Queue(Of Integer) and this will represent a predefined set of numbers, 1 - 10, in a random order
    4. When the user clicks on the button, it will dequeue the top-most item from your queue into your list, and then the list will be sorted


    By doing it like this, you guarantee that you will always have numbers between 1 - 10 and you also guarantee that you don't ever include a duplicate number.

    Take a look at this example:
    Code:
    Public Class Form1
    
        Private ReadOnly _random As New Random()
        Private ReadOnly _queue As New Queue(Of Integer)
        Private ReadOnly _list As New List(Of Integer)
    
        Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            HydrateQueue()
        End Sub
    
        Private Sub HydrateQueue()
            Dim numbers As IEnumerable(Of Integer) = Enumerable.Range(1, 10)
            Dim randomlyOrderedNumbers As IEnumerable(Of Integer) = numbers.OrderBy(Function(i) _random.Next())
            For Each randomlyOrderedNumber As Integer In randomlyOrderedNumbers
                _queue. Enqueue(randomlyOrderedNumber)
            Next
        End Sub
    
        Private Sub DequeueToList()
            ' add the top-most item in the queue to the list and sort the list
            If (_queue. Count > 0) Then
                _list.Add(_queue. Dequeue())
                _list.Sort()
            End If
        End Sub
    
        Private Sub ButtonAddToList_Click(sender As Object, e As EventArgs) Handles ButtonAddToList.Click
            DequeueToList()
            ' loop over every item in the list
            For index As Integer = 0 To _list. Count - 1
                ' this assumes the controls are named TextBox1, TextBox2, etc...
                Dim textbox As Control = Me.Controls.Find($"TextBox{index + 1}", true).FirstOrDefault()
                If (textbox IsNot Nothing) Then
                    ' set the textbox's text to the iterated item
                    textbox.Text = _list.Item(index).ToString()
                End If
            Next
        End Sub
    
        Private Sub ButtonReset_Click(sender As Object, e As EventArgs) Handles ButtonReset.Click
            ' loop over every item in the list
            For index As Integer = 0 To _list. Count - 1
                Dim textbox As Control = Me.Controls.Find($"TextBox{index + 1}", true).FirstOrDefault()
                If (textbox IsNot Nothing) Then
                    ' clear the textbox's text
                    textbox.Clear()
                End If
            Next
            ' clear the queue and the list, then rehydrate the queue
            _queue.Clear()
            _list.Clear()
            HydrateQueue()
        End Sub
    End Class
    Example (Console Application): https://dotnetfiddle.net/qpRmp7

    Edit - I apologize if there are spaces or misspellings throughout, apparently Chrome likes to autocorrect my free-typed code
    Last edited by dday9; Jun 13th, 2025 at 08:00 AM.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width