将整数列表塞入字符串的最紧凑方法是什么?

问题描述 投票:0回答:1

目标:

减小整数数组的大小,如下所示:“[12, 1, -34, 55, 13, 341, 11, 56, 321, -3422, 1222, -4, 237]”,同时能够对其进行转换回到原来的状态。压缩输出必须是字符串。

原因:

字符串过长会导致我使用的数据库管理器在与其交互时冻结。 (字符串用作数组等变量类型的存储格式。)

背景:

我本质上是存储网格坐标列表,如下所示: [Vector3(1,2,3), Vector3(4,5,6)] -> [1,2,3,4,5,6]

我正在 gdscript 中构建它。


我将第一个整数数组示例的数字塞在一起的最佳尝试结果是:

“c1-y.Td,y1.bU,w1-ym,cm-4,n7”

通过将大于 9 的配对数字分配给非数字字符(例如 10 = a、11 = b、61 = Z) 并且仅在由多个字符组成的转换后的数字之间放置逗号(并使用“-”符号作为排序逗号(这有点复杂))。不包括空白(测试了 200 个随机生成的数组),大小平均减少了 48%。

问题:

有更好的方法来做我想做的事吗?

arrays algorithm integer godot
1个回答
0
投票

您可以使用符号转换为 UTF-16 代码 (0 - 65535):

const arr = [12, 1, -34, 55, 13, 341, 11, 56, 321, -3422, 1222, -4, 237];

const result = arr.map(n => (Math.sign(n) < 0 ? '-' : '') + String.fromCharCode(Math.abs(n))).join('');
console.log(result);
console.log(arr.join(',').length, '=>', result.length);

//decode
const out = [];
for(let i=0;i<result.length;i++){
  const sign = result[i]==='-'?-1:1;
  if(sign<0) i++;
  out.push(result[i].charCodeAt()*sign);
}
console.log(...out);

© www.soinside.com 2019 - 2024. All rights reserved.