Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,151,313 members, 7,811,933 topics. Date: Monday, 29 April 2024 at 12:03 AM

Write An Algorithm To Shuffle An Array - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / Write An Algorithm To Shuffle An Array (1248 Views)

How Important Is Data Structures And Algorithm To Pro Developers / How To Empty An Array In Javascript / Is It Compulsory To Write An Algorithm Before Coding (2) (3) (4)

(1) (2) (Reply) (Go Down)

Write An Algorithm To Shuffle An Array by Deicide: 8:32am On Jul 23, 2022
Was able to come up with this using rust.
static mut TEMP_V: Vec<i32> = Vec::new();
lazy_static! {
static ref TEMP_SET: HashSet<i32> = {
let mut is_in = HashSet::new();
is_in
};
fn shuffel(nums: &Vec<i32>, count: usize) -> &'static Vec<i32> {
unsafe {
while TEMP_V.len() <= nums.len() {
let rval: u32 = rand::random::<u32>() % nums.len() as u32;
if TEMP_SET.contains(&nums[rval as usize]) {
if count <= 0 {
break;
}
shuffel(&nums, count - 1);
} else {
TEMP_SET.insert(nums[rval as usize]);
TEMP_V.push(nums[rval as usize]);
}
}
return &TEMP_V;
}
}

1 Like

Re: Write An Algorithm To Shuffle An Array by operAhdam: 9:11am On Jul 23, 2022
that's new,,why do you choose rust boss of all this other languages

1 Like

Re: Write An Algorithm To Shuffle An Array by Deicide: 9:18am On Jul 23, 2022
operAhdam:
that's new,,why do you choose rust boss of all this other languages
Cause it's one of the best programming languages ever, honestly you should try it.
Re: Write An Algorithm To Shuffle An Array by operAhdam: 9:24am On Jul 23, 2022
Deicide:
Cause it's one of the best programming languages ever, honestly you should try it.
e easy pass python
Re: Write An Algorithm To Shuffle An Array by Nobody: 9:39am On Jul 23, 2022
Explain the question well, shuffle array as in how?
Re: Write An Algorithm To Shuffle An Array by Deicide: 9:54am On Jul 23, 2022
Think4Myself:
Explain the question well, shuffle array as in how?
You never play WHAT before? How them day take shuffle cards. Let's say you have input [1,2,3] you can shuffle it to be [1, 2, 3] or [1, 3, 2] or [3, 1, 2] etc
Re: Write An Algorithm To Shuffle An Array by Deicide: 9:54am On Jul 23, 2022
operAhdam:

e easy pass python
No but way more faster than python
Re: Write An Algorithm To Shuffle An Array by Ikechukwu183: 10:12am On Jul 23, 2022
Deicide:
Cause it's one of the best programming languages ever, honestly you should try it.
As a C++ and Python programmer, I can tell you that this code is not 'readable' by human eyes... is this even a HLL?
Re: Write An Algorithm To Shuffle An Array by Deicide: 10:15am On Jul 23, 2022
Ikechukwu183:

As a C++ and Python programmer, I can tell you that this code is not 'readable' by human eyes... is this even a HLL?
That's because Nairaland code formatting is useless.
Re: Write An Algorithm To Shuffle An Array by Nobody: 10:16am On Jul 23, 2022
Deicide:

You never play WHAT before? How them day take shuffle cards. Let's say you have input [1,2,3] you can shuffle it to be [1, 2, 3] or [1, 3, 2] or [3, 1, 2] etc

Ok
Re: Write An Algorithm To Shuffle An Array by parkervero(m): 10:26am On Jul 23, 2022
As a Java dev I can't read the code The while loop is not in addendum to Java way of implementing while loop.
Re: Write An Algorithm To Shuffle An Array by namikaze: 10:32am On Jul 23, 2022
Deicide:
Was able to come up with this using rust.
...
Can someone improve on this? use whatever programming language you like. And are there other rust programmers on this section? grin Complexity of this code? O(2^n) yeah it's that terrible.

There is a problem that causes infinity loop in this code can you spot it?
from random import randrange

def shuffle(arr):
for i in range(len(arr)):
rand_idx = randrange(len(arr))
arr[rand_idx], arr[i] = arr[i], arr[rand_idx]
return arr


arr = [1,2,3,4,5]
print(shuffle(arr))

Here's something pretty simple, time complexity should be O (n log n), since the time complexity of the randrange function is O (log n).
It's being quite a while since I did anything in rust, I don't want to fight the borrow checker right now grin Rust used to be my favorite language but it's just too painful to do anything substantial with it, try implementing a doubly linkeldlist in Rust and you'll agree that C++ is easy compared to Rust.

3 Likes 1 Share

Re: Write An Algorithm To Shuffle An Array by Ikechukwu183: 10:36am On Jul 23, 2022
namikaze:

from random import randrange

def shuffle(arr):
for i in range(len(arr)):
rand_idx = randrange(len(arr))
arr[rand_idx], arr[i] = arr[i], arr[rand_idx]
return arr


arr = [1,2,3,4,5]
print(shuffle(arr))
Brilliant one wink

1 Like

Re: Write An Algorithm To Shuffle An Array by Deicide: 10:38am On Jul 23, 2022
namikaze:

from random import randrange

def shuffle(arr):
for i in range(len(arr)):
rand_idx = randrange(len(arr))
arr[rand_idx], arr[i] = arr[i], arr[rand_idx]
return arr


arr = [1,2,3,4,5]
print(shuffle(arr))
Nice one grin

1 Like

Re: Write An Algorithm To Shuffle An Array by Deicide: 10:42am On Jul 23, 2022
parkervero:
As a Java dev I can't read the code The while loop is not in addendum to Java way of implementing while loop.
You just have to get used to it to love it
Re: Write An Algorithm To Shuffle An Array by namikaze: 10:42am On Jul 23, 2022
Ikechukwu183:
Brilliant one wink
Python for the win cheesy
Re: Write An Algorithm To Shuffle An Array by namikaze: 10:44am On Jul 23, 2022
Deicide:
Nice one grin
I modified my post, check it out.
Re: Write An Algorithm To Shuffle An Array by Deicide: 10:53am On Jul 23, 2022
namikaze:

Here's something pretty simple, time complexity should be O (n log n), since the time complexity of the randrange function is O (log n).
It's being quite a while since I did anything in rust, I don't want to fight the borrow checker right now grin Rust used to be my favorite language but it's just too painful to do anything substantial with it, try implementing a doubly linkeldlist in Rust and you'll agree that C++ is easy compared to Rust.
Yeah I agree there are something that are Impossible in rust without using the unsafe key work like i probably did in my code to reduce time & space complexity. But I love the language grin it makes you as a programmer to be very careful with what you write.

Can you guess the complexity of my code since lookup in a hashmap is O(1) so am thing O(n^2 + random(n)) grin I don't even know what that means grin
Re: Write An Algorithm To Shuffle An Array by TastyFriedPussy: 11:08am On Jul 23, 2022
I'll like to see someone try this with JS

1 Like

Re: Write An Algorithm To Shuffle An Array by Deicide: 11:22am On Jul 23, 2022
TastyFriedPussy:
I'll like to see someone try this with JS
It'll be easy with Js
Re: Write An Algorithm To Shuffle An Array by namikaze: 11:24am On Jul 23, 2022
Deicide:
Yeah I agree there are something that are Impossible in rust without using the unsafe key work like improbable did in my code to reduce time & space complexity. But I love the language grin it makes you as a programmer to be very careful with what you write.

Can you guess the complexity of my code since lookup in a hashmap is O(1) so am thing O(n^2 + random(n)) grin I don't even know what that means grin
My guy even with the unsafe keyword it gets complex real quick, I know what I faced when I tried implementing a doubly linkedlist in Rust, it was crazy. Memory management in C/C++ is much simpler than in Rust.
I agree though learning rust will make you better developer overall.

Guy you're brave, using recursion inside a while loop, I hail thee loolz, well let me see if I can figure out the complexity...
Re: Write An Algorithm To Shuffle An Array by namikaze: 11:29am On Jul 23, 2022
Deicide:
It'll be easy with Js
Sorry, what's the role of the count parameter?
Re: Write An Algorithm To Shuffle An Array by Deicide: 11:31am On Jul 23, 2022
namikaze:

My guy even with the unsafe keyword it gets complex real quick, I know what I faced when I tried implementing a doubly linkedlist in Rust, it was crazy. Memory management in C/C++ is much simpler than in Rust.
I agree though learning rust will make you better developer overall.

Guy you're brave, using recursion inside a while loop, I hail thee loolz, well let me see if I can figure out the complexity...
Even on reddit they would advise you not to implement a double linked list or even a Linked list in rust exexpt you wanna run mad grin But you can use Box<T> to make the running mad slower grin

My code actually runs fast despite the recursion, it mostly just depends on if it gets the random number right. Best case would be O(n) but that's impossible but it can happen just that the chance are small especially if the input is large.

I'll rewrite this code in C++ so I can test the complexity properly. The lazy_load for HasSet I did up there I don't have the crate for it grin
Re: Write An Algorithm To Shuffle An Array by Deicide: 11:32am On Jul 23, 2022
namikaze:

Sorry, what's the role of the count parameter?
That's the base case of the recursion; if that's not there the code would run forevergrin
Re: Write An Algorithm To Shuffle An Array by namikaze: 11:37am On Jul 23, 2022
Deicide:
That's the base case of the recursion; if that's not there the code would run forevergrin
Ok, say for instance I called the function on a vector, [1,2,3,4,5];
what would pass as argument for the count parameter?
Re: Write An Algorithm To Shuffle An Array by Deicide: 11:43am On Jul 23, 2022
namikaze:

Ok, say for instance I called the function on a vector, [1,2,3,4,5];
what would pass as argument for the count parameter?
like this shuffle([1,2,3,4,5], 5);

5 here is the length of the vector.
Re: Write An Algorithm To Shuffle An Array by namikaze: 11:44am On Jul 23, 2022
Deicide:
Even on reddit they would advise you not to implement a double linked list or even a Linked list in rust exexpt you wanna run mad grin But you can use Box<T> to make the running mad slower grin

My code actually runs fast despite the recursion, it mostly just depends on if it gets the random number right. Best case would be O(n) but that's impossible but it can happen just that the chance are small especially if the input is large.

I'll rewrite this code in C++ so I can test the complexity properly. The lazy_load for HasSet I did up there I don't have the crate for it grin
I remember the Box<T> construct lol, and to think I was able to implement a linkedlist (single) in it grin I don't think I have the code anymore but I'll check my GitHub later.

Ofcourse it would run fast, rust if fast af. I do think it's not that great to let your algorithm depend on "picking the right number" but I get you.
Re: Write An Algorithm To Shuffle An Array by namikaze: 11:46am On Jul 23, 2022
Deicide:
like this shuffle([1,2,3,4,5], 5);
5 here is the length of the vector.
Ok sure.
Re: Write An Algorithm To Shuffle An Array by Deicide: 11:54am On Jul 23, 2022
namikaze:

I remember the Box<T> construct lol, and to think I was able to implement a linkedlist (single) in it grin I don't think I have the code anymore but I'll check my GitHub later.

Ofcourse it would run fast, rust if fast af. I do think it's not that great to let your algorithm depend on "picking the right number" but I get you.
That's why this code wouldn't work if they we duplicate in the input array. Who knows maybe if I stroll out later the solution might come to my head grin
Re: Write An Algorithm To Shuffle An Array by namikaze: 12:05pm On Jul 23, 2022
Deicide:
That's why this code wouldn't work if they we duplicate in the input array. Who knows maybe if I stroll out later the solution might come to my head grin
You should definitely go for walk grin
You used the hashset to reduce lookup from O(n) to O(1) didn't you? nice one.
Also an instance where random() keeps returning an index to a value that's already in the hashset continuously till count gets to zero would yield undesired results.
Re: Write An Algorithm To Shuffle An Array by Deicide: 12:15pm On Jul 23, 2022
namikaze:

You should definitely go for walk grin
You used the hashset to reduce lookup from O(n) to O(1) didn't you? nice one.

Yeah, Things I learnt on leetcode grin

Also an instance where random() keeps returning an index to a value that's already in the hashset continuously till count gets to zero would yield undesired results.
Yes the complexity is dependent on the random number. So it can be infinite ): so don't try on large dataset.
Re: Write An Algorithm To Shuffle An Array by namikaze: 12:34pm On Jul 23, 2022
Deicide:

Yeah, Things I learnt on leetcode grin

Yes the complexity is dependent on the random number. So it can be infinite ): so don't try on large dataset.
Another way to express your solution without the recursion would be;
function shuffle(Array arr) 
{
HashSet seenIndices = new HashSet()
Array result = new Array()
for (int i in 0 to arr.length())
{
rand_idx = random num in range(0, arr.length())
while (seenIndices.contains(rand_idx)
{
rand_idx = random num in range(0, arr.length())
}
result.add(arr[rand_idx])
seenIndices.add(rand_idx)
}
return result;
}

This I think follows the same idea, but would still depend on the random function, so not recommended.

(1) (2) (Reply)

Error Running Asp.net Application / For The Best Code Monkeys - Crack This And Get A Chance To Join Uk Intelligence / Biology Android App: Reviews and Suggestions are welcome

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 46
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.