The Crazy Sort

dev-challenges
thebotguys-tavern

#1

Hi,

Today I am going to ask you something weird.
In Algorithms Optimization, there are times where problems were faced with fun in mind. I want to bring you here one of this cases.

Meet the Crazy Sort

This sorting algorithm is very (very) particular : you have an infinite loop, and you want to sort an array. At each round of the loop, every item is swapped randomly with another one in the same array.

Your objective for today is to create a Golang version of this crazy algorithm.

Here some pseudocode to help you

loop until array is sorted
    swap randomly one element with another element

Have fun,

The Bot Guy

#2

Hi. This is my solution

package main

import (
	"fmt"
	"math/rand"
	"sort"
	"time"
)

// randomArray returns an array of length "len".
// Each index contains an integer random number (range [0, len-1])
func randomArray(len int) []int {
	a := make([]int, len)
	for i := 0; i < len; i++ {
		a[i] = rand.Intn(len)
	}
	return a
}}

func main() {
	// rand.Seed() provides a unique seed to the program.
	// Without it, the default seed is 1, so rand.Intn() will return the same number
	// You don't have to call it every time you call rand.Intn()
	rand.Seed(time.Now().UnixNano())
	array := randomArray(10)
	fmt.Printf("Before sort: %v", array)
	i := 0

	// Infinite loop that loops until the array is sorted
	for !sort.IntsAreSorted(array) {
		r1 := rand.Intn(len(array))
		r2 := rand.Intn(len(array))

		// swap two array positions
		x, y := array[r1], array[r2]
		array[r1], array[r2] = y, x

		i++
	}
	fmt.Printf("\n\nAfter sort: %v", array)
	fmt.Printf("\n\nNeeded %d iterations", i)
}

#3

Hello, I have few comments

  1. Could you edit your solution by adding comments explaining what you are doing? it’s not necessary to do line per line comments
  2. This piece of code can be enhanced by putting the solution somewhere else
    if sort.IntsAreSorted(array) {
        break
    }
    

Hence the situation it’s better to post a new message with corrections. And also, go to “The Tavern Stories” Section and tell us about your story. We are curious to know how did you come here (I see you are a new user) :smiley:


#4

I’ve edited the first post, sorry :sweat_smile:

Anyway, for more info about how the sort package works, check https://tour.golang.org/flowcontrol/1


#5

@Redrace this guy won today’s tip! @Parkour please create a discord account for syscoin and DM me

The amount is 100 SYS :smiley:


#6