grev.js (2122B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2020 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var floor = require( '@stdlib/math/base/special/floor' ); 24 25 26 // VARIABLES // 27 28 var M = 3; 29 30 31 // MAIN // 32 33 /** 34 * Reverses a strided array in-place. 35 * 36 * @param {PositiveInteger} N - number of indexed elements 37 * @param {NumericArray} x - input array 38 * @param {integer} stride - index increment 39 * @returns {NumericArray} input array 40 * 41 * @example 42 * var x = [ -2.0, 1.0, 3.0, -5.0, 4.0, 0.0, -1.0, -3.0 ]; 43 * 44 * grev( x.length, x, 1 ); 45 * // x => [ -3.0, -1.0, 0.0, 4.0, -5.0, 3.0, 1.0, -2.0 ] 46 */ 47 function grev( N, x, stride ) { 48 var tmp; 49 var ix; 50 var iy; 51 var m; 52 var n; 53 var i; 54 55 if ( N <= 0 ) { 56 return x; 57 } 58 n = floor( N/2 ); 59 60 // Use loop unrolling if the stride is equal to `1`... 61 if ( stride === 1 ) { 62 m = n % M; 63 iy = N - 1; 64 65 // If we have a remainder, run a clean-up loop... 66 if ( m > 0 ) { 67 for ( ix = 0; ix < m; ix++ ) { 68 tmp = x[ ix ]; 69 x[ ix ] = x[ iy ]; 70 x[ iy ] = tmp; 71 iy -= 1; 72 } 73 } 74 if ( n < M ) { 75 return x; 76 } 77 for ( ix = m; ix < n; ix += M ) { 78 tmp = x[ ix ]; 79 x[ ix ] = x[ iy ]; 80 x[ iy ] = tmp; 81 82 tmp = x[ ix+1 ]; 83 x[ ix+1 ] = x[ iy-1 ]; 84 x[ iy-1 ] = tmp; 85 86 tmp = x[ ix+2 ]; 87 x[ ix+2 ] = x[ iy-2 ]; 88 x[ iy-2 ] = tmp; 89 90 iy -= M; 91 } 92 return x; 93 } 94 if ( stride < 0 ) { 95 ix = (1-N) * stride; 96 } else { 97 ix = 0; 98 } 99 iy = ix + ((N-1)*stride); 100 for ( i = 0; i < n; i++ ) { 101 tmp = x[ ix ]; 102 x[ ix ] = x[ iy ]; 103 x[ iy ] = tmp; 104 ix += stride; 105 iy -= stride; 106 } 107 return x; 108 } 109 110 111 // EXPORTS // 112 113 module.exports = grev;