shuffleArray.js( ***REVISE***)
/*Shuffle array
Description
Given an array consisting of 2n elements in the form [x1, x2, ..., xn, y1, y2, ..., yn],
suffle the array into [x1, y1, x2, y2, ... , xn, yn]. Assume that n is never 0.
Input format
First line contains a positive integer, denoting n. It is followed by 2n lines. Each line contains one integer.
Output format
2n lines where each line contains one element of the shuffled array.
Sample input
3
2
5
1
3
4
7
Sample output
2
3
5
4
1
7
Explanation
1) First line is 3, i.e. Following 6 lines are the elements of the array.
2) The first 3 lines contains the first half of the array and the 2nd set
of 3 elements contain the second half of the array.
3) First 2 lines of output will be first element of first half, first element
of second half so the first 2 lines of the output are 2 and 3.
4) Next 2 lines of output will be second element of first half and second element
of second half, so the next 2 lines of output will be 5 and 4
5) Next 2 lines of output will be third element of first half and third element of second half,
so the next 2 lines of output will be 1 and 7
*/
let fs = require("fs");
let data = fs.readFileSync(0, 'utf-8');
let idx = 0;
data = data.split('\n');
function readLine() {
idx++;
return data[idx - 1].trim();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
let n = parseInt(readLine());//3
let arr = [];
for (let i = 0; i < 2 * n; i++) // 1.(i=0<6, true), 2.(i=1<6,true), 3.(i=2<6,true),
4.(i=3<6,true),5.(i=4<6,true),6.(i=5<6,true),6.(i=6<6,false exit the loop)
{
arr[i] = parseInt(readLine());
// [ 2 ]
// [ 2, 5 ]
// [ 2, 5, 1 ]
// [ 2, 5, 1, 3 ]
// [ 2, 5, 1, 3, 4 ]
// [ 2, 5, 1, 3, 4, 7 ] all yellow color
}
//console.log(arr) // [ 2, 5, 1, 3, 4, 7 ] yellow color
for (let j = 0; j < n; j++) // 1.(j=0<3,true), 2.(j=1<3,true), 3.(j=2<3,true),
4.(j=3<3, false exit the loop )
{
console.log(arr[j]);// 1.(2) 2.(5) 3.(1)
console.log(arr[j + n]);// 1.(2,3) 2.(2,3,5,4) 3.(2,3,5,4,1,7) ,
Hence the answer
}
// J+n means we are increasing the indexing by n , so for
// j=0, arr[j]= arr[0] and arr[j+n] = arr[0+3] = arr[3] i.e, 3
// j=1 ,arr[j]= arr[1] and arr[j+n] = arr[1+3] = arr[4] i.e, 4
//////////////////////////////////////////////////////////////////////////////////////////////
TERMINAL:

Comments
Post a Comment