写一段离散化的模板代码
时间: 2024-03-04 07:28:49 浏览: 29
好的,以下是离散化的模板代码:
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10; // 数据范围
int a[N], b[N], c[N]; // 原数组,离散化数组,离散化下标
int n, tot; // 数组长度,离散化范围
int main() {
// 读入数据
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
b[i] = a[i]; // 备份原数组
}
// 离散化
sort(b + 1, b + n + 1);
tot = unique(b + 1, b + n + 1) - b - 1;
for (int i = 1; i <= n; i++) {
c[i] = lower_bound(b + 1, b + tot + 1, a[i]) - b;
}
// 输出离散化结果
for (int i = 1; i <= n; i++) {
printf("%d ", c[i]);
}
return 0;
}
```
希望这段代码对你有所帮助!如果你还有其他问题,可以随时问我。
相关问题
写一段离散傅里叶变换的matlab代码
以下是一段简单的 Matlab 代码,用于计算离散傅里叶变换:
```matlab
% 输入信号
x = [1 2 3 4];
% 信号长度
N = length(x);
% 构建 DFT 矩阵
W = exp(-1i*2*pi/N);
% 构建 DFT 矩阵
F = zeros(N,N);
for n = 0:N-1
for k = 0:N-1
F(n+1,k+1) = W^(n*k);
end
end
% 计算 DFT
X = F * x';
% 输出结果
disp(X);
```
这段代码首先定义了一个输入信号 `x`,然后计算信号长度 `N`。接着,它构建了一个 DFT 矩阵 `F`,该矩阵将在计算离散傅里叶变换时使用。最后,它计算了输入信号的 DFT,并将结果存储在变量 `X` 中。
写一个java关于离散化的代码
好的,我可以回答这个问题。以下是一个简单的Java代码示例,用于将一组连续的数值转换为一组离散的数值:
```
import java.util.*;
public class Discretization {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = sc.nextInt();
}
int[] sortedNums = nums.clone();
Arrays.sort(sortedNums);
Map<Integer, Integer> map = new HashMap<>();
int index = 0;
for (int i = 0; i < n; i++) {
if (!map.containsKey(sortedNums[i])) {
map.put(sortedNums[i], index++);
}
}
for (int i = 0; i < n; i++) {
System.out.print(map.get(nums[i]) + " ");
}
}
}
```
这个程序首先读取一个整数n,表示要离散化的数值的数量。然后,它读取n个整数,存储在一个数组中。接下来,它将这些数值排序,并使用一个哈希表来映射每个数值到它的离散化值。最后,它输出每个数值的离散化值。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)