Skip to content

Instantly share code, notes, and snippets.

@msusur
Created August 18, 2020 14:34
Show Gist options
  • Save msusur/0d71d7778cdc36f397267a6c54ac0bfa to your computer and use it in GitHub Desktop.
Save msusur/0d71d7778cdc36f397267a6c54ac0bfa to your computer and use it in GitHub Desktop.
/**
* The first, reverseArray, takes an array as argument and
* produces a new array that has the same elements in
* the inverse order
* **/
// input
// [1, 3, 4, 5, 6, 7, 9]
// output 1
// [9, 7, 6, 5, 4, 3, 1]
// output
// [9, 3, 4, 5, 6, 7, 1]
// [9, 7, 4, 5, 6, 3, 1]
// [9, 7, 6, 5, 4, 3, 1]
// input
// [1, 3, 4, 5, 6, 7]
// [7, 3, 4, 5, 6, 1] i=0 arr[0] <==> arr[5]
// [7, 6, 4, 5, 3, 1] i=1 arr[1] <==> arr[4]
// [7, 6, 5, 4, 3, 1] i=2
// Big O notation
// N sayili dizi icin O(N)
const reverseArray = (arr) => {
const newArray = [];
for (let i = arr.length - 1; i > 0; i--) {
newArray.push(arr[i]);
}
return newArray;
};
// Big O notation
// N sayili dizi icin; O(N/2)
const reverArrayInPlace = (arr) => {
const halfTheArrayCount = arr.length / 2;
for (let i = 0; i < halfTheArrayCount; i++) {
const temp = arr[i];
arr[i] = arr[arr.length - i];
arr[arr.length - i] = temp;
}
return arr;
};
/**
* Write a range function that takes two arguments, start and end,
* and returns an array
* containing all the numbers from start up to
* (and including) end.
*/
const range = (start, end) => {
const array = [];
for (let i = start; i <= end; i++) {
array.push(i);
}
return array;
};
/**
* Next, write a sum function that takes an array of numbers and
* returns the sum of these numbers.
* Run the example program and see whether it does indeed return 55.
*/
const sum = (array) => {
let totalSum = 0;
for (let i = 0; i < array.length; i++) {
totalSum = totalSum + array[i];
}
return totalSum;
};
console.log(sum(range(1, 10)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment