see-189. Rotate Array

本文介绍了一种数组旋转算法的实现方法,通过三次反转操作达到指定元素旋转k位的效果,并附带了C++代码实现。该算法适用于解决数组中元素按特定数值旋转的问题。

[1,2,3,4,5,6,7]和k=3为例,处理之后的答案为[5,6,7,1,2,3,4],对该答案反转可以得到[4,3,2,1,7,6,5]。观察可知,相当于把原先的元素根据K值大小分为二段,分别反转,之后再把整个数组反转即可。

且元素的移动是有周期的,周期即为数组的长度。针对k值大于数组元素个数的情况,可以先进行一个模运算。

class Solution {
public:
    
    void rotate(vector<int>& nums, int k) 
    {
        k=k%nums.size();
        
        reverse(nums,0,(nums.size()-k-1));
        reverse(nums,nums.size()-k,nums.size()-1);
        reverse(nums,0,nums.size()-1); 
    }
    
    void reverse(vector<int>& nums,int begin,int end)
    {
        while(begin<end)
        {
            int temp=nums[begin];
            nums[begin]=nums[end];
            nums[end]=temp;
            
            begin++;
            end--;
        }
    }
};

 

class SH_R(Directivity): """ This class defines Directivities whose directional responses are spherical harmonics. Parameters ---------- order, degree : int Index to this spherical harmonics. This code follows the ambisonics convention by calling the nonnegative index 'order' and the other 'degree'. These names may be swapped elsewhere. ind : int Single-integer index, used if both order and degree are None. normalized : bool Specifies whether the directional response is normalized (i.e. unit mean square value). kwargs : Passed to Directivity. This covers orientation params in particular. """ def __init__(self, order = None, degree = None, ind = None, normalized = True, **kwargs): super().__init__(**kwargs) self.set_normalized(normalized) if order is None and degree is None: order = int(np.sqrt(ind)) degree = ind - order * (order + 1) self.order = order self.degree = degree # Override def _get_params(self): return {'order' : self.order, 'degree' : self.degree, 'normalized' : self.normalized} # Override def _get_shortlabel(self): return 'SpH' def dir_gain(self, azimuth, colatitude = None): """ Unoriented directional gain (which is a spherical harmonics). Parameters ---------- azimuth : array Angles (in radians) to return directional gains for. colatitude, frequency : None Unused. Returns ------- gain : array_like(azimuth) Directional gains in *azimuth*. """ return self.h_gain * sph_harm_r(self.degree, self.order, azimuth=azimuth, colatitude=colatitude) # if self.degree < 0: # return self.h_gain * np.sqrt(2) * (-1) ** self.degree * scipy.special.sph_harm(-self.degree, self.order, azimuth, colatitude).imag # if self.degree > 0: # return self.h_gain * np.sqrt(2) * (-1) ** self.degree * scipy.special.sph_harm(self.degree, self.order, azimuth, colatitude).real # return self.h_gain * scipy.special.sph_harm(0, self.order, azimuth, colatitude).real def set_normalized(self, normalized): self.normalized = normalized if normalized: self.h_gain = np.sqrt(4 * np.pi) else: self.h_gain = 1 @staticmethod def index_to_orderdegree(index): order = int(np.sqrt(index)) degree = index - order * (order + 1) return order, degree @staticmethod def orderdegree_to_index(order, degree): index = order * (order + 1) + degree return index @staticmethod def rot_mats(max_order, O = None, **kwargs): """ Compute a collection of rotation matrices for mixture-of-SH directivities. Parameters ---------- max_order : int Highest CH order to be rotated. O : Orientation The rotation to be applied. kwargs : Passed to Orientation if O is None. Returns ------- mats : list[array] A list of *max_order* matrices that rotate SH weights of orders 1, ..., max_order, respectively. """ if O is None: O = Orientation(**kwargs) # A pseudorandom list of angles n0 = 2 * np.pi * (103 ** np.arange(2 * max_order + 1) % 997) / 997 n1 = np.pi * (101 ** np.arange(2 * max_order + 1) % 997) / 997 N2 = np.array([n0, n1]) MN2 = np.array(ut3d.xyz_to_azcl(*O.M.dot(ut3d.azcl_to_xyz(*N2)))) mats = [] for M in range(max_order): order = M + 1 # Responses of order M in the set of random angles A = np.array([SH_R(order=order, degree=d).dir_gain(*N2[:, :(2 * order + 1)]) for d in range(-order, order + 1)]) # [ch, dir] # # Condition number of the above. Stable inversion requires the condition number be numerically significant. # eig_A = np.abs(np.linalg.eig(A)[0]) # condition_k = np.max(eig_A) / np.min(eig_A) # Responses in rotated random angles # MN2 = ut3d.xyz_to_azcl(*O.M.dot(ut3d.azcl_to_xyz(*N2))) B = np.array([SH_R(order=order, degree=d).dir_gain(*MN2[:, :(2 * order + 1)]) for d in range(-order, order + 1)]) # Solve for the rotation matrix of order M R = B.dot(np.linalg.inv(A)) mats.append(R) return mats @staticmethod def rotate(c, mats, axis = 0): """ Rotate one mixture-of-SH directional response to another. In typical usage *c* contains perfect square number of channels (1 + max_order) ^ 2 and *mats* contain at least max_order matrices where the kth matrix is (2k + 1) by (2k + 1). If less than max_order matrices are available the corresponding high order weights are not rotated. If *c* contains non-perfect-square number of channels the imcomplete top order is not rotated. Parameters ---------- c : array Array encoding the original directional response as CH weights. By default the first dimension (axis 0) are the SH channels, i.e. c[0] contain weight(s) of the 0th order. This can be reconfigured via *axis*. mats : list[array2d] List of rotation matrices to be applied. See also rot_mats. axis : int Index to dimension of *c* that indices SH channels. Returns ------- c_rot : array Array encoding the rotated directional response as SH weights. """ c_rot = c + 0 c_rot = c_rot.swapaxes(0, axis) max_o = min(len(mats), int(np.floor(np.sqrt(len(c_rot)))) - 1) for o in range(max_o): # SH weights of order o + 1 c_o = c_rot[(o + 1) * (o + 1) : (o + 2) * (o + 2)] # Rotation matrices are left operators hence the transpose when applied on the right. # c_o[:] = c_o.T.dot(mats[o].T).T c_o[:] = np.tensordot(mats[o], c_o, axes=1) return c_rot.swapaxes(0, axis) 这个类是什么类,,其中那部分是球谐变换吗,与Y_max = spa.sph.sh_matrix(self.Nmax, self.azi, self.zen, ‘real’) Y_max_inv = np.linalg.pinv(Y_max)是对应的意思吗
最新发布
11-12
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值