我正在使用一种工具集非常有限的奇怪编程语言。
我想对一个整数列表进行排序,但我无法找出在给定工具的情况下有效的算法。我不知道这是否可能。
这是一些记录可用运算符的 JavaScript 代码。
// 1. you can create new variables
// javascript quirk: in order to pass-by-reference, you must store an integer in an object
const v = (value) => {
return { value: value };
}
// 2. you can set A to B, if B is larger than A
const max = (a,b) => {
if(b.value > a.value)
a.value = b.value;
};
// 3. you can set A to B, if B is less than A
const min = (a,b) => {
if(b.value < a.value)
a.value = b.value;
};
// 4. you can swap the values of A and B
const swap = (a,b) => {
let t = a.value;
a.value = b.value;
b.value = t;
};
// 5. you can set A to B
const set = (a,b) => {
a.value = b.value;
};
// 6. you can add B to A
const add = (a,b) => {
a.value = a.value + b.value;
};
// 7. you can subtract B from A
const subtract = (a,b) => {
a.value = a.value - b.value;
};
// 8. you can multiply A by B
const multiply = (a,b) => {
a.value = a.value * b.value;
};
// 9. you can divide A by B, losing the remainder
// if B == 0, then A is not modified
const divide = (a,b) => {
if (b.value == 0) return;
a.value = Math.floor(a.value/b.value);
};
// 10. you can set A to the remainder of A divided by B
// if B == 0, then A is not modified
const mod = (a,b) => {
if (b.value == 0) return;
a.value = a.value % b.value;
};
// 11. you can test if A falls within a range of integers, and if true, call a function
// (see next section for function rules). You cannot do anything with a false
//
// min and max must be hard coded integers (i.e. you cannot pass in variables)
const in_range = (a,min,max) => {
return (a >= min && a <= max);
};
// 12. you can add an integer to A
// x must be a hard-coded integer, you cannot pass in variables
const add2 = (a,x) => {
a.value = a.value + x;
};
// 13. you can set A to an integer
// x must be a hard-coded integer, you cannot pass in variables
const set2 = (a,x) => {
a.value = x;
};
var a = v(2);
var b = v(1);
var c = v(3);
// you may create as many extra variables as you want
var temp = v(0);
a.value == 1
b.value == 2
c.value == 3
仅使用上面列出的操作,可以对整数进行排序吗?
语言非常有限:
没有可用的循环或其他比较/逻辑流程。
没有数组。
您可以编写函数,但它们必须遵循上述规则。您不能将变量传递给函数,必须从全局范围访问它们。
现在的定义max
,并min
已得到修复,你可以做这样的:
var sum = v(0);
add(sum ,a);
add(sum ,b);
add(sum ,c);
//remember a and set a to min
var olda = v(0);
set(olda,a);
min(a,b);
min(a,c);
//set c to max
max(c,olda);
max(c,b);
//calculate b
set(b,sum);
subtract(b,a);
subtract(b,c);
您有比您需要的更多的可用操作。显然,仅对 2 个变量进行排序比这更容易,如果您可以对 2 进行排序,那么您可以使用排序网络对任意数量的变量进行排序。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句