Shuffle Array Elements

Easy
23
50.5% Acceptance

In this lab, you are tasked to implement a function that shuffles elements of a given array. The given array, `nums`, consists of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`.

Your task is to return the array in the form `[x1,y1,x2,y2,...,xn,yn]`.

Example

Example 1:

``````Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7]
Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7, the answer is [2,3,5,4,1,7].``````

Example 2:

``````Input: nums = [1,2,3,4,4,3,2,1], n = 4
Output: [1,4,2,3,3,2,4,1]``````

Example 3:

``````Input: nums = [1,1,2,2], n = 2
Output: [1,2,1,2]``````

Constraints

• `1 <= n <= 500`
• `nums.length == 2n`
• `1 <= nums[i] <= 10^3`

Challenges

1. Implement the `shuffle` function
2. Test the implementation with the given examples
3. Export the `shuffle` function for evaluation

Evaluation Script

``````1import fs from 'fs'
2import { shuffle } from '../index.js'
3
4const testlog = []
5
6try {
7  const result = shuffle([2, 5, 1, 3, 4, 7], 3)
8  if (JSON.stringify(result) === JSON.stringify([2, 3, 5, 4, 1, 7])) {
9    testlog.push({ status: 'pass' })
10  } else {
11    throw new Error('Failed for the provided example 1')
12  }
13} catch (error) {
14  testlog.push({
15    status: 'error',
16    error: error.message || 'Challenge 1 and 2 failed',
17  })
18}
19
20try {
21  const result = shuffle([1, 1, 2, 2], 2)
22  if (JSON.stringify(result) === JSON.stringify([1, 2, 1, 2])) {
23    testlog.push({ status: 'pass' })
24  } else {
25    throw new Error('Failed for the provided example 3')
26  }
27} catch (error) {
28  testlog.push({
29    status: 'error',
30    error: error.message || 'Challenge 3 failed',
31  })
32}
33
34fs.writeFileSync(
35  '/home/damner/code/.labtests/testlog.json',
36  JSON.stringify(testlog),
37)
38
39fs.writeFileSync(
40  process.env.UNIT_TEST_OUTPUT_FILE,
41  JSON.stringify(testlog.map((result) => result.status === 'pass')),
42)``````

Setting Up Test Environment Script

``````1#!/bin/bash
2set -e 1
3
4mkdir -p /home/damner/code/.labtests
5
6cat > /home/damner/code/.labtests/package.json << EOF
7{
8    "type": "module"
9}
10EOF
11
12cd /home/damner/code/.labtests
13mv \$TEST_FILE_NAME ./nodecheck.test.js
14
15# import puppeteer doesn't work without it
17
18node nodecheck.test.js 2>&1 | tee evaluationscript.log``````

Initial File System for User

``````/**
* @param {number[]} nums
* @param {number} n
* @return {number[]}
*/
export var shuffle = function(nums, n) {

};``````
``````{
"name": "codedamn-lab",
"type": "module"
}``````
``````tabs: ['index.js']
terminals: ['yarn install']
``````