I need to receive something like this:
a
b
c
d
c
b
a
b
c
d
c
b
a
...
I've created a code that solves it, but partially:
var matrix = ['a', 'b', 'c', 'd'];
for (var i = 0; i < 20; i ++) {
var period = Math.ceil((i + 1) / matrix.length);
var offset = i % matrix.length;
if (period % 2 === 0) {
console.log(period, offset, matrix[matrix.length - offset - 1]);
} else {
console.log(period, offset, matrix[offset]);
}
}
and a response is:
1 0 "a"
1 1 "b"
1 2 "c"
1 3 "d"
2 0 "d"
2 1 "c"
2 2 "b"
2 3 "a"
3 0 "a"
...
Maybe somebody has an experience with this trouble?
Here you go:
var matrix = ["a", "b", "c", "d"];
var length = 20;
for (var i = 0, a = 0, e = 1; i < length; a += e) {
if(a >= matrix.length - 1 || a <= 0 && i++ != 0) e *= -1;
console.log(matrix[a]);
}
JSFiddle: https://jsfiddle.net/p9102usd/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With