Skip to content

Instantly share code, notes, and snippets.

@woonketwong
woonketwong / mergeTwoSortedArray
Created December 31, 2013 18:58
Given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order.
var mergeTwoSortedArray = function(array1, array2){
var array1IndexEnd = array1.length - array2.length - 1;
var arrayExtraIndexEnd = array1.length - 1;
var array2IndexEnd = array2.length - 1;
while( array2IndexEnd >= 0){
if ( array1[array1IndexEnd] > array2[array2IndexEnd]){
array1[arrayExtraIndexEnd] = array1[array1IndexEnd];
arrayExtraIndexEnd--;
array1IndexEnd--
@woonketwong
woonketwong / sortAndGroupAnagram
Created December 30, 2013 18:33
A method to sort an array of strings so that all the anagrams next to each other.
var sortAndGroupAnagram = function(array){
var result = {};
var sortedResult = [];
var currentKey;
var allKey;
for (var i = 0; i < array.length; i++){
currentKey = array[i].split('').sort().join('');
if ( result.hasOwnProperty(currentKey) ){
result[currentKey].push(array[i]);
@woonketwong
woonketwong / selectionRank
Last active October 3, 2023 13:18
Selection Rank is a well known algorithm in computer science to find the ith smallest (or largest) element in an array in linear time. If the elements are unique, you can find the ith smallest or largest element in expected O(n) time. The code below implements finding the ith smallest element in javascript.
var selectionRank = function(array, rank){
// randomly select a pivot
var pivotIndex = Math.floor( (Math.random() * array.length) );
var pivot = array[pivotIndex];
// left array stores the smallest <rank> elements in the array
var leftArr = [];
var rightArr = [];
// partition into left and right arrays
for (var i = 0; i < array.length; i++){
@woonketwong
woonketwong / jugglingDBWithPostgres
Last active December 29, 2015 05:09
JugglingDB with Postgres
var q = require('q');
var Schema = require('jugglingdb').Schema;
var schema = new Schema('postgres', {
database: 'woonketwong',
username: 'woonketwong'
});
// The first argument to schema.define is the table
// and schema name. Do not use any capital letter
// in the table name because the database create table