fueanta

Convert array into Zig-Zag fashion

Jul 3rd, 2021 (edited)
1,103
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const zigzag = <T>(array: T[]): T[] => {
  2.     const zigzaggedArray: T[] = [array[0]];
  3.     let isGreaterThanExpected = true;
  4.  
  5.     for (let i = 0; i < array.length - 1; ++i) {
  6.         if ((isGreaterThanExpected && zigzaggedArray[i] < array[i + 1]) ||
  7.             (!isGreaterThanExpected && zigzaggedArray[i] > array[i + 1])) {
  8.  
  9.             zigzaggedArray[i + 1] = zigzaggedArray[i];
  10.             zigzaggedArray[i] = array[i + 1];
  11.         }
  12.         else
  13.             zigzaggedArray[i + 1] = array[i + 1];
  14.  
  15.         isGreaterThanExpected = !isGreaterThanExpected;
  16.     }
  17.  
  18.     return zigzaggedArray;
  19. }
  20.  
  21. const array = [2, 6, 8, 9, 5, 1];
  22. const zigzaggedArray = zigzag(array);
  23.  
  24. console.log(JSON.stringify(array));
  25. console.log(JSON.stringify(zigzaggedArray));
  26.  
RAW Paste Data