ndarray.js (2148B)
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 * @param {NonNegativeInteger} offset - starting index 40 * @returns {NumericArray} input array 41 * 42 * @example 43 * var x = [ 1.0, -2.0, 3.0, -4.0, 5.0, -6.0 ]; 44 * 45 * grev( 3, x, 1, x.length-3 ); 46 * // x => [ 1.0, -2.0, 3.0, -6.0, 5.0, -4.0 ] 47 */ 48 function grev( N, x, stride, offset ) { 49 var tmp; 50 var ix; 51 var iy; 52 var m; 53 var n; 54 var i; 55 56 if ( N <= 0 ) { 57 return x; 58 } 59 n = floor( N/2 ); 60 ix = offset; 61 62 // Use loop unrolling if the stride is equal to `1`... 63 if ( stride === 1 ) { 64 m = n % M; 65 iy = ix + N - 1; 66 67 // If we have a remainder, run a clean-up loop... 68 if ( m > 0 ) { 69 for ( i = 0; i < m; i++ ) { 70 tmp = x[ ix ]; 71 x[ ix ] = x[ iy ]; 72 x[ iy ] = tmp; 73 ix += stride; 74 iy -= stride; 75 } 76 } 77 if ( n < M ) { 78 return x; 79 } 80 for ( i = m; i < n; i += M ) { 81 tmp = x[ ix ]; 82 x[ ix ] = x[ iy ]; 83 x[ iy ] = tmp; 84 85 tmp = x[ ix+1 ]; 86 x[ ix+1 ] = x[ iy-1 ]; 87 x[ iy-1 ] = tmp; 88 89 tmp = x[ ix+2 ]; 90 x[ ix+2 ] = x[ iy-2 ]; 91 x[ iy-2 ] = tmp; 92 93 ix += M; 94 iy -= M; 95 } 96 return x; 97 } 98 iy = ix + ((N-1)*stride); 99 for ( i = 0; i < n; i++ ) { 100 tmp = x[ ix ]; 101 x[ ix ] = x[ iy ]; 102 x[ iy ] = tmp; 103 ix += stride; 104 iy -= stride; 105 } 106 return x; 107 } 108 109 110 // EXPORTS // 111 112 module.exports = grev;