Shuffle Array Elements

Easy
28
53.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

import fs from 'fs' import { shuffle } from '../index.js' const testlog = [] try { const result = shuffle([2, 5, 1, 3, 4, 7], 3) if (JSON.stringify(result) === JSON.stringify([2, 3, 5, 4, 1, 7])) { testlog.push({ status: 'pass' }) } else { throw new Error('Failed for the provided example 1') } } catch (error) { testlog.push({ status: 'error', error: error.message || 'Challenge 1 and 2 failed', }) } try { const result = shuffle([1, 1, 2, 2], 2) if (JSON.stringify(result) === JSON.stringify([1, 2, 1, 2])) { testlog.push({ status: 'pass' }) } else { throw new Error('Failed for the provided example 3') } } catch (error) { testlog.push({ status: 'error', error: error.message || 'Challenge 3 failed', }) } fs.writeFileSync( '/home/damner/code/.labtests/testlog.json', JSON.stringify(testlog), ) fs.writeFileSync( process.env.UNIT_TEST_OUTPUT_FILE, JSON.stringify(testlog.map((result) => result.status === 'pass')), )

Setting Up Test Environment Script

#!/bin/bash set -e 1 mkdir -p /home/damner/code/.labtests cat > /home/damner/code/.labtests/package.json << EOF { "type": "module" } EOF cd /home/damner/code/.labtests mv $TEST_FILE_NAME ./nodecheck.test.js # import puppeteer doesn't work without it npm link puppeteer node 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']