Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,160,947 members, 7,845,045 topics. Date: Thursday, 30 May 2024 at 11:42 AM

Write An Algorithm To Shuffle An Array - Programming (2) - Nairaland

Nairaland Forum / Science/Technology / Programming / Write An Algorithm To Shuffle An Array (1298 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)

Re: Write An Algorithm To Shuffle An Array by Deicide: 12:48pm On Jul 23, 2022
namikaze:

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.
That's the thing about programming if your solution is not optimised you would know. So there is always room for growth till you move to the next thing.

The randrange you used in python should also depend on random but it's abstracted though am not sure of this.
Re: Write An Algorithm To Shuffle An Array by chukwuebuka65(m): 2:46pm On Jul 23, 2022
function shuffle( arr ) {
Const seenArray = [ ]
Const shuffledArray = [ ]
for ( i=0,i<arr.length-1,i++) {
let randomIndex = math.floor( math.random( )
*arr.length)
If (!seenArray.include(randomIndex)) {
shuffledArray [ randomIndex] = arr[i]
seenArray[i] = randomIndex
} else {
for ( k=0,k<arr.length,k++) {
If ( shuffledArray[k] == null) {
shuffledArray[k] = arr[i]
break;
}
}

}


}
Return shuffledArray;
}
Re: Write An Algorithm To Shuffle An Array by chukwuebuka65(m): 2:50pm On Jul 23, 2022
namikaze:

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.


I think there is a chance this might go into infinite loop
Re: Write An Algorithm To Shuffle An Array by qtguru(m): 3:18pm On Jul 23, 2022
Deicide:
Cause it's one of the best programming languages ever, honestly you should try it.

Everybody that has written it has sworn by it, but I don't know what Project to use it for, what do you use it for or just learning, is it straight forward ?

1 Like

Re: Write An Algorithm To Shuffle An Array by Vicky2k(m): 3:52pm On Jul 23, 2022
chukwuebuka65:
function shuffle( arr ) { Const seenArray = [ ] Const shuffledArray = [ ] for ( i=0,i<arr.length-1,i++) { let randomIndex = math.floor( math.random( ) *arr.length) If (!seenArray.include(randomIndex)) { shuffledArray [ randomIndex] = arr[i] seenArray[i] = randomIndex } else { for ( k=0,k<arr.length,k++) { If ( shuffledArray[k] == null) { shuffledArray[k] = arr[i] break; } }
}

} Return shuffledArray; }
js things point. can someone implement this in c or typescript
Re: Write An Algorithm To Shuffle An Array by Deicide: 4:07pm On Jul 23, 2022
qtguru:


Everybody that has written it has sworn by it, but I don't know what Project to use it for, what do you use it for or just learning, is it straight forward ?
You can actually use it for anything. To be honest I was left with go or rust which to use for Sys admin stuff and I just picked rust all I use it for now is to write some CMD tool to solve admin task. And since it's cross platform it's also a plus though I still use go sometimes for that.

Though I might no be using the full power but it suites my use case just fine.
Re: Write An Algorithm To Shuffle An Array by namikaze: 5:57pm On Jul 23, 2022
Deicide:
That's the thing about programming if your solution is not optimised you would know. So there is always room for growth till you move to the next thing.

The randrange you used in python should also depend on random but it's abstracted though am not sure of this.
No it's not like that. In my case, any value returned by the random() function would be used. In your case any value wouldn't do, it would have to return a new value not inside of the HashSet.
Re: Write An Algorithm To Shuffle An Array by namikaze: 6:00pm On Jul 23, 2022
chukwuebuka65:


I think there is a chance this might go into infinite loop
I know, this is not my solution, I was trying to remove the recursion from op's solution, mine's on the first page of the thread.
Re: Write An Algorithm To Shuffle An Array by namikaze: 6:20pm On Jul 23, 2022
chukwuebuka65:
function shuffle( arr ) {
Const seenArray = [ ]
Const shuffledArray = [ ]
for ( i=0,i<arr.length-1,i++) {
let randomIndex = math.floor( math.random( )
*arr.length)
If (!seenArray.include(randomIndex)) {
shuffledArray [ randomIndex] = arr[i]
seenArray[i] = randomIndex
} else {
for ( k=0,k<arr.length,k++) {
If ( shuffledArray[k] == null) {
shuffledArray[k] = arr[i]
break;
}
}

}


}
Return shuffledArray;
}
God of bugs grin grin
In all seriousness lots of syntax errors and even after fixing the errors does not give the desired output. I bet you typed it on nairaland.
Re: Write An Algorithm To Shuffle An Array by Deicide: 6:27pm On Jul 23, 2022
namikaze:

God of bugs grin grin
In all seriousness lots of syntax errors and even after fixing the errors does not give the desired output. I bet you typed it on nairaland.
He should have used typescript
Seun need to fix code formatting on Nairaland even if it's only for this section, I mean see Quora see Reddit.

2 Likes

Re: Write An Algorithm To Shuffle An Array by chukwuebuka65(m): 6:43pm On Jul 23, 2022
namikaze:

God of bugs grin grin
In all seriousness lots of syntax errors and even after fixing the errors does not give the desired output. I bet you typed it on nairaland.


Yea, but I think u didnt get the concept. If you get the concept u can fix it.
Re: Write An Algorithm To Shuffle An Array by Deicide: 7:57pm On Jul 23, 2022

Re: Write An Algorithm To Shuffle An Array by Xedmark: 7:58pm On Jul 23, 2022
Deicide:
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;
}
}

is this what you call array?
Re: Write An Algorithm To Shuffle An Array by Deicide: 8:08pm 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))


Using your python logic in rust, code translate to

fn shuffle(nums: &mut Vec<i32> ) -> Vec<i32> {
let mut rng = rand::thread_rng();
for num in 0..nums.len() {
let x: u32 = rng.gen_range(0..nums.len() as u32);
nums.swap(num, x as usize);
}
return nums.to_vec();
}


This is fucking fast, cause it's using multiple thread and random results are cached grin

Now I can finally rest and watch the sun set on a great universe
Re: Write An Algorithm To Shuffle An Array by Deicide: 8:10pm On Jul 23, 2022
Xedmark:


is this what you call array?
Yes, vectors are dynamic array
Re: Write An Algorithm To Shuffle An Array by Nobody: 9:20pm On Jul 23, 2022
chukwuebuka65:
function shuffle( arr ) {
Const seenArray = [ ]
Const shuffledArray = [ ]
for ( i=0,i<arr.length-1,i++) {
let randomIndex = math.floor( math.random( )
*arr.length)
If (!seenArray.include(randomIndex)) {
shuffledArray [ randomIndex] = arr[i]
seenArray[i] = randomIndex
} else {
for ( k=0,k<arr.length,k++) {
If ( shuffledArray[k] == null) {
shuffledArray[k] = arr[i]
break;
}
}

}


}
Return shuffledArray;
}
Your code still has bugs after testing... it will be impressive to know u wrote it here on nairaland even before testing...

sometimes it prints out empty in the array
Nairaland reduced the quality of the image

Re: Write An Algorithm To Shuffle An Array by namikaze: 9:45pm On Jul 23, 2022
chukwuebuka65:



Yea, but I think u didnt get the concept. If you get the concept u can fix it.
What concept? unless you want me to debug your code lol.
Re: Write An Algorithm To Shuffle An Array by namikaze: 9:48pm On Jul 23, 2022
Deicide:


Using your python logic in rust, code translate to

fn shuffle(nums: &mut Vec<i32> ) -> Vec<i32> {
let mut rng = rand::thread_rng();
for num in 0..nums.len() {
let x: u32 = rng.gen_range(0..nums.len() as u32);
nums.swap(num, x as usize);
}
return nums.to_vec();
}


This is fucking fast, cause it's using multiple thread and random results are cached grin

Now I can finally rest and watch the sun set on a great universe
I see you rustecean, flexing Rust features anyhow grin
You can't rest o, it's night here already grin grin
Re: Write An Algorithm To Shuffle An Array by Nobody: 10:11pm On Jul 23, 2022
LET ME CONTRIBUTE WITH JS

explanation.

I am using while loop.

while the length of shuffled array is not equal to given array the loop keeps running.

now each time loops run a random value from given array is produced.

now we push that value to the shuffled array provided it doesn't exist there previously,

This way we get unique random values in shuffled array.

code can be shortened further with ternary operators... for readability lets go with IFS
i know it's neat. grin



function shuffle(arr) {
const shuffled = []

while(shuffled.length!==arr.length){
let randVal = Math.floor(Math.random()*arr.length)
if (!shuffled.includes(arr[randVal])) {

shuffled.push(arr[randVal]);
}

if (shuffled.length===arr.length)
return shuffled
}
}
shuffle(["a", "b", "c", "d", "e","g","h","i"]);

1 Like

Re: Write An Algorithm To Shuffle An Array by Csami(m): 10:51pm On Jul 23, 2022
chukwuebuka65:
function shuffle( arr ) {
Const seenArray = [ ]
Const shuffledArray = [ ]
for ( i=0,i<arr.length-1,i++) {
let randomIndex = math.floor( math.random( )
*arr.length)
If (!seenArray.include(randomIndex)) {
shuffledArray [ randomIndex] = arr[i]
seenArray[i] = randomIndex
} else {
for ( k=0,k<arr.length,k++) {
If ( shuffledArray[k] == null) {
shuffledArray[k] = arr[i]
break;
}
}

}


}
Return shuffledArray;
}

This code is full of bed bugs and caterpillars
Too many syntax errors ranging from ";" to "mixture of capital and small letters "

const number = [23. 474, 74, 37, 27]

function shuffleArray(array) {

return array.sort( () => Math.random() - 0.5 );

}

console.log(shuffleArray(number))
Re: Write An Algorithm To Shuffle An Array by Csami(m): 10:54pm On Jul 23, 2022
GREATIGBOMAN:
LET ME CONTRIBUTE WITH JS

explanation.

I am using while loop.

while the length of shuffled array is not equal to given array the loop keeps running.

now each time loops run a random value from given array is produced.

now we push that value to the shuffled array provided it doesn't exist there previously,

This way we get unique random values in shuffled array.

code can be shortened further with ternary operators... for readability lets go with IFS
i know it's neat. grin



function shuffle(arr) {
const shuffled = []

while(shuffled.length!==arr.length){
let randVal = Math.floor(Math.random()*arr.length)
if (!shuffled.includes(arr[randVal])) {

shuffled.push(arr[randVal]);
}

if (shuffled.length===arr.length)
return shuffled
}
}
shuffle(["a", "b", "c", "d", "e","g","h","i"]);

me likey but it's too much code
Re: Write An Algorithm To Shuffle An Array by Nobody: 10:59pm On Jul 23, 2022
Csami:


me likey but it's too much code

How too much code lol

It's actually short lol
Re: Write An Algorithm To Shuffle An Array by Nobody: 11:53pm On Jul 23, 2022
Csami:


This code is full of bed bugs and caterpillars
Too many syntax errors ranging from ";" to "mixture of capital and small letters "

const number = [23. 474, 74, 37, 27]

function shuffleArray(array) {

return array.sort( () => Math.random() - 0.5 );

}

console.log(shuffleArray(number))

Nice.... but your solution is quite popular on google
Re: Write An Algorithm To Shuffle An Array by chukwuebuka65(m): 1:44pm On Jul 24, 2022
Csami:


This code is full of bed bugs and caterpillars
Too many syntax errors ranging from ";" to "mixture of capital and small letters "

const number = [23. 474, 74, 37, 27]

function shuffleArray(array) {

return array.sort( () => Math.random() - 0.5 );


}

console.log(shuffleArray(number))


I know because I wrote it off-hand here on nairaland while at the market. But you should try to avoid abstractions in your algorithms where necessary so we can determine the time and space complexity . You should have used array.sort().

(1) (2) (Reply)

I Made This Quadratic Solver With Python / Help Wit Project 'intelligent Data Analysis And Decision Support Systems' / Hardware Programming Using PIC PROGRAMMING

(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. 41
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.