Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const zigzag = <T>(array: T[]): T[] => {
- const zigzaggedArray: T[] = [array[0]];
- let isGreaterThanExpected = true;
- for (let i = 0; i < array.length - 1; ++i) {
- if ((isGreaterThanExpected && zigzaggedArray[i] < array[i + 1]) ||
- (!isGreaterThanExpected && zigzaggedArray[i] > array[i + 1])) {
- zigzaggedArray[i + 1] = zigzaggedArray[i];
- zigzaggedArray[i] = array[i + 1];
- }
- else
- zigzaggedArray[i + 1] = array[i + 1];
- isGreaterThanExpected = !isGreaterThanExpected;
- }
- return zigzaggedArray;
- }
- const array = [2, 6, 8, 9, 5, 1];
- const zigzaggedArray = zigzag(array);
- console.log(JSON.stringify(array));
- console.log(JSON.stringify(zigzaggedArray));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement