Created
February 6, 2022 07:10
-
-
Save jedsada-gh/346275d1eeb0dfbc704ebea92491ae65 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const sortMin2Max = (items: number[]): number[] => { | |
let temp = 0; | |
for (let i = 0; i < items.length; i++) { | |
for (let j = 0; j < items.length; j++) { | |
if (items[j] > items[j + 1]) { | |
temp = items[j]; | |
items[j] = items[j + 1]; | |
items[j + 1] = temp; | |
} | |
} | |
} | |
return items | |
} | |
(() => { | |
const array: number[] = [1, 9, 10, 2, 5, 7, 8, 3, 4, 6]; | |
// 1. cal sum of the array | |
let result: number = 0; | |
for (let i = 0; i < array.length; ++i) { | |
result += array[i]; | |
} | |
// const result = array.reduce((acc, item) => acc += item) | |
// let sum = 0 | |
// const result = array.map(item => sum += item)[array.length - 1] | |
// console.log("result: ", result); | |
// 2. find the even and odd number from the array | |
const evenItems: number[] = []; | |
const oddItems: number[] = []; | |
for (let i = 0; i < array.length; i++) { | |
if (array[i] % 2 === 0) { | |
evenItems.push(array[i]); | |
} else { | |
oddItems.push(array[i]); | |
} | |
} | |
// let times = 0; | |
// while (times < array.length) { | |
// if (array[times] % 2 === 0) { | |
// evenItems.push(array[times]); | |
// } else { | |
// oddItems.push(array[times]); | |
// } | |
// times++; | |
// } | |
console.log("even items: ", evenItems); | |
console.log("odd items: ", oddItems); | |
// 3. Sort min -> max from the array | |
// expectation: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
// input : [1, 9, 10, 2, 5, 7, 8, 3, 4, 6] | |
// solution1 | |
const resultSort = sortMin2Max(array) | |
console.log("sort: ", resultSort); | |
// solution2 | |
// let temp = 0; | |
// for (let i = 0; i < array.length; i++) { | |
// for (let j = i; j < array.length; j++) { | |
// if (array[i] > array[j]) { | |
// temp = array[j]; | |
// array[j] = array[i]; | |
// array[i] = temp; | |
// } | |
// } | |
// } | |
// 4. find two min values in the array | |
const result = sortMin2Max(array) | |
console.log("result: ", result[0], result[1]); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment