Вход

Просмотр полной версии : помогите решить задачу конверта 4 значного числа в время


AnthonyFink
03.11.2018, 20:31
есть номер 1234 надо его разделить на часы допустим 12:34, 21:34, 13:24 итд

как это лучше сделать

рони
03.11.2018, 21:10
AnthonyFink,
<script>
function fn(e) {
x:
for (var g = [], b = e.length, h = Math.pow(b, b - 2);; h++) {
var d = h.toString(b),
c = d.length;
if (c > b) break;
c < b && (d = 0 + d);
var f = "";
for (c = 0; c < b; c++) {
var a = a = parseInt(d[c], b);
f += e[a];
if(f.length == 2) {
if(+f > 23) continue x;
f += ":"
}
};
e.every(function(b) {
return 0 <= f.indexOf(b)
}) && g.push(f)

}
return g
};
document.write(JSON.stringify(fn(['1','2','3','4'])));</script>

AnthonyFink
03.11.2018, 21:28
рони можешь плиз написать коменты к действиям я просто даже не понимаю как всему этому делу сделать валидацию времени

Aetae
03.11.2018, 22:01
рони, не бывает 41 часа.)

рони
03.11.2018, 22:46
не бывает 41 часа.)
часы поправил :)

рони
03.11.2018, 22:58
AnthonyFink,
это генератор(16, 17, 18 ... 256 в 100, 101, 102 ... 10000 потом замена 0 на 1 , 1 на 2, 2 на 3, 3 на 4) всех возможных вариантов (нерационально), ограничение по длине входящих данных (остановка генерации строка 7) и фильтрация число должно содержать все входящие элементы строка 18.
alert((16).toString(4))

Malleys
03.11.2018, 23:05
Я понимаю так, что нужно взять две последние цифры и заменить их на двоеточие + две последние цифры. Вот функция printTime...

function printTime(time) { return String(time).padStart(4, "0").replace(/(\d{2}$)/, ":$1"); }

// пример
alert(printTime(1234));

UPDMalleys,
рони это сделал идеально =)Да! Но с другой стороны тема не называется "помогите решить задачу: составьте из 4 цифр всевозможные времена", поэтому я не понял, почему это так сложно. Перестановки из 4-ёх элементов дают 24 варианта, среди них выбрать только те, которые могут быть показаниями часов.

<script>
const permutations = xs0 => [xs0, ...perms(xs0, [])];
const perms = ([t, ...ts], is) => {
if(t === undefined) return [];
const interleave = (r, xs) => {
const interleaveHelper = (f, [y, ...ys]) => {
if(y === undefined) return [ts, r];
const [us, zs] = interleaveHelper(x => f([y, ...x]), ys, r);
return [[y, ...us], [f([t, y, ...us]), ...zs]];
};
const [, zs] = interleaveHelper(x => x, xs, r);
return zs;
};
return permutations(is).reduceRight(interleave, perms(ts, [t, ...is]));
};

const times = permutations([1, 2, 3, 4])
.filter(([a, b]) => 10 * a + b < 24)
.map(([a, b, c, d]) => `${a}${b}:${c}${d}`)
.join(", ");

document.write(times)</script>

UPD2 рони, зачем у вас цикл для поиска перестановок из 4-ёх элементов совершает 240 проходов, достаточно на порядок меньше homepage.math.uiowa.edu/~goodman/22m150.dir/2007/Permutation%20Generation%20Methods.pdf (http://homepage.math.uiowa.edu/~goodman/22m150.dir/2007/Permutation%20Generation%20Methods.pdf)<script>
function* permutations(xs0) {
const length = xs0.length, c = Array(length).fill(0);
let i = 1, j;

yield xs0.slice();

while(i < length)
if (c[i] < i) {
j = i % 2 && c[i];
[xs0[i], xs0[j]] = [xs0[j], xs0[i]];
c[i]++, i = 1;
yield xs0.slice();
} else
c[i] = 0, i++;
}

const times = [...permutations([1, 2, 3, 4])]
.filter(([a, b]) => 10 * a + b < 24)
.map(([a, b, c, d]) => `${a}${b}:${c}${d}`)
.join(", ");

document.write(times)</script>

UPD3 Логику поиска времён можно внедрить в алгоритм поиска перестановок...<script>function* getTimes(xs0) {
const length = xs0.length, c = Array(length).fill(0);
let i = 0, j, xs, isFirst = true;

while(i < length)
if (c[i] < i || isFirst) {
isFirst = false;
j = i % 2 && c[i];
[xs0[i], xs0[j]] = [xs0[j], xs0[i]];
c[i]++, i = 1;
xs = xs0.slice();
if(10 * xs[0] + xs[1] < 24) yield xs.join("").replace(/(\d{2}$)/, ":$1");
} else
c[i] = 0, i++;
}

document.write([...getTimes([1, 2, 3, 4])].join(", "))</script>

UPD4 Гениально и просто, на основе предыдущих ответов<script>function* permutations(xs0){
if(xs0.length == 0) yield []
for(const a of xs0) for(const x of permutations(xs0.filter(x => x !== a)))
yield [a, ...x]
}
function* getTimes(l) {
for(const [a, b, c, d] of permutations(l)) {
if(10 * a + b >= 24) break
yield `${a}${b}:${c}${d}`
}
}
document.write([...getTimes([1, 2, 3, 4])].join(", "))</script>

P. S. Тут используется рекурсивный генератор!

AnthonyFink
03.11.2018, 23:11
Malleys,
рони это сделал идеально =)

Vlasenko Fedor
04.11.2018, 04:00
Данный вариант не претендует на лучший
Это пример подхода

<script>
const combinator = matrix => matrix.reduceRight((prev, current) => {
var result = []
current.forEach(a => prev.forEach(b => result.push([a].concat(b))))
return result
})
const arr = [1, 2, 3, 4]
const data = (new Array(4)).fill(arr)
const result = combinator(data)
.filter(v => !/(\d).*\1+/.test(v.join('')) && (v[0] < 2 || (v[0] === 2 && v[1] < 4)))
.map(([a, b, c, d]) => `${a}${b}:${c}${d}`)
document.write(JSON.stringify(result))
</script>

рони
04.11.2018, 07:40
Malleys,
мне далеко до ваших знаний. :thanks: