Advertisement
BEmanuel87

Ordered set up to nth element

May 5th, 2016
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <html>
  2. <head>
  3.      <title>Ordered</title>
  4. </head>
  5. <body>
  6.     <h1> Test Header </h1>
  7.    
  8.   <script>
  9.     var p = 7,
  10.             vector = [3, 5, 13, 26, 54, 22];
  11.            
  12. function isOrdered(array, elementNumber) {
  13.      // Check if the array has enough elements
  14.      if (array.length < elementNumber) {
  15.           return[null, 'Array does not have '+elementNumber+((elementNumber == 1) ? ' element' : ' elements')];
  16.      }
  17.    
  18.      // Initialize direction
  19.      var direction = null,
  20.                  segment = [],
  21.                  currentComparition;
  22.      
  23.      // Loop up to the nth element
  24.      for (var i = 0; i < elementNumber-1; i++) {
  25.                 // Compare elements
  26.                 if (array[i] < array[i+1]) {
  27.                      currentComparition = 'lower';
  28.                 } else if (array[i] == array[i+1]) {
  29.                      currentComparition = 'equal';
  30.                 } else if (array[i] > array[i+1]) {
  31.                      currentComparition = 'bigger';
  32.                 }
  33.                
  34.              // Set the direction (if not set)
  35.              if (!direction) {
  36.                   if (currentComparition != 'equal') {
  37.                      direction = currentComparition;
  38.                   }
  39.              }
  40.              
  41.              // Add the first compared element to the segment
  42.              segment.push(array[i]);
  43.              
  44.              // Check if direction is kept
  45.              if (direction) {
  46.                   // Unordered
  47.                   if (direction != currentComparition && currentComparition != 'equal') {
  48.                      // Add last element
  49.                      segment.push(array[i]);
  50.                      return [false, segment];
  51.                   }
  52.              }
  53.      }
  54.      
  55.      // Add last element
  56.      segment.push(array[i]);
  57.      // Return ordered result
  58.      return [true, segment];
  59. }
  60.  
  61. var result = isOrdered(vector, p);
  62.  
  63. if (result[0]) {
  64.     document.write('Set is ordered: ' + result[1].join(', '));
  65. } else {
  66.   if (result[0] === null) {
  67.      document.write(result[1]);
  68.   } else {
  69.     document.write('Set is not ordered');
  70.   }
  71. }
  72.   </script>
  73. </body>
  74. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement