Monday, August 8, 2016
Private, Public & Inheritance in JS
Access an iframe and its contents using selectors
document.getElementById('frame_id').contentWindow.$('#' + idOfElementInFrame);
Saturday, August 6, 2016
Adding without using + operator
function addWithoutPlusOperator (a, b){ // 111, 111
var sumWithoutCarry = a ^ b; // 000
var carryWithoutSum = (a & b) << 1; //111 << 1 = 1110
return addWithoutPlusOperator( sumWithoutCarry, carryWithoutSum );
}
var sumWithoutCarry = a ^ b; // 000
var carryWithoutSum = (a & b) << 1; //111 << 1 = 1110
return addWithoutPlusOperator( sumWithoutCarry, carryWithoutSum );
}
Swapping without using extra variable
function swap (a, b){ // 5,7
a = b - a; // 7-5 = 2
b = b - a; // 7-2 = 5
a = a + b; // 2 + 5 = 7
}
Private, Public variables using Javascript closures
Tuesday, August 2, 2016
Find Duplicate Element
Given: a list of integers where, the integers in the list are in the range 1..n and the list has a length of n+1. Find the duplicate element. The complexity of should be at most O(n).
Link to Code on JSfiddle: https://jsfiddle.net/dhiviyad/zwsan7zt/1/
Link to Code on JSfiddle: https://jsfiddle.net/dhiviyad/zwsan7zt/1/
Friday, July 29, 2016
Javascript - regular function call vs using new
function test(){
this.a = 1;
return a;
}
var a = test(); //a equals 1, this context in test will be window
var b = new test(); //b equals "test {a: 1}", this context is the function's context
this.a = 1;
return a;
}
var a = test(); //a equals 1, this context in test will be window
var b = new test(); //b equals "test {a: 1}", this context is the function's context
Monday, July 25, 2016
Creating a slideshow UI
Problem - Using the json data provided, create a slideshow that displays the img in the json on the left, the name in json to the right, left, right arrows below them. Clicking on the left and right arrows should show the previous/ next img, name from the json array.
Sunday, July 24, 2016
Make a blue square that when clicked or hovered slides across the screen and the color fades to red
See the Pen Sliding Box by Dhiviya Dhanasekar (@dhiviyadhanasekar) on CodePen.
Saturday, July 23, 2016
Funky Sort
Problem: FunkySort
arr[] is an array filled with random unique integers. Arrange arr[] such that the following condition is met:
arr[0] < arr[1] > arr[2] < arr[3] > arr[4] < arr[5] ... // 23, 31, 40 , 1 // 23 < 40 > 1 < 31
arr[] is an array filled with random unique integers. Arrange arr[] such that the following condition is met:
arr[0] < arr[1] > arr[2] < arr[3] > arr[4] < arr[5] ... // 23, 31, 40 , 1 // 23 < 40 > 1 < 31
import java.util.Arrays;
public class FunkySort{
public static void swap(int[] arr, int pos1, int pos2){
int temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;
}
public static int[] funkySort(int[] arr){
int arrlen = arr.length;
if(arrlen == 0 || arrlen == 1) return arr;
int sign = 1;
for(int i=0; i < arrlen-1; i++){
if(sign == 1){
if(arr[i] > arr[i+1]) swap(arr, i, i+1);
} else if( sign == -1){
if(arr[i] < arr[i+1]) swap(arr, i, i+1);
}
sign *= -1;
}
System.out.println("Array - " + Arrays.toString(arr));
return arr;
}
public static void main(String[] args){
int[] arr = new int[] {1,2,3,4,5};
// funkySort(arr);
// arr = new int[]{};
// funkySort(arr);
// arr = new int[]{1};
// System.out.println(Arrays.toString(funkySort(arr)));
//arr = new int[]{1,2,3,4,5};
funkySort(arr);
}
};
Sort Additional Info
My notes on sorting algorithm comparison:
Space complexity :
Quicksort - O(n) total, O(n) aux
Mergesort - O(n) total, O(n) aux
Insertion sort - O(n)
Bubble sort - O(1)
Heap sort - O(1) aux
Selection sort - O(n) total, O(1) aux
Stable :
Quicksort - typical in-place sort is not stable; stable versions exist
Mergesort - Yes
Insertion sort - Yes
Bubble sort - Yes
Heap sort - No
Selection sort - No
In-Place:
Quicksort - in place version exists
Mergesort - No
Insertion sort - Yes
Bubble sort - Yes
Heap sort - Yes
Selection sort - Yes
Insertion sort:
Best case - sorted input O(N)
Worst case - reverse sorted input O(N2)
Avg case - O(N2)
The average case is also quadratic, which makes insertion sort impractical for sorting large arrays.
However, insertion sort is one of the fastest algorithms for sorting very small arrays, even faster than quicksort; indeed, good quicksort implementations use insertion sort for arrays smaller than a certain threshold, also when arising as subproblems; the exact threshold must be determined experimentally and depends on the machine, but is commonly around ten.
Merge sort:
Best/Avg/Worst - O(nlogN)
Although heapsort has the same time bounds as merge sort, it requires only Θ(1) auxiliary space instead of merge sort's Θ(n).
On typical modern architectures, efficient quicksort implementations generally outperform mergesort for sorting RAM-based arrays.
On the other hand, merge sort is a stable sort and is more efficient at handling slow-to-access sequential media. Merge sort is often the best choice for sorting a linked list: in this situation it is relatively easy to implement a merge sort in such a way that it requires only Θ(1) extra space, and the slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible.
As of Perl 5.8, merge sort is its default sorting algorithm (it was quicksort in previous versions of Perl). In Java, the Arrays.sort() methods use merge sort or a tuned quicksort depending on the datatypes and for implementation efficiency switch to insertion sort when fewer than seven array elements are being sorted. Python uses Timsort, another tuned hybrid of merge sort and insertion sort, that has become the standard sort algorithm in Java SE 7, on the Android platform, and in GNU Octave.
Quick sort:
1. Quicksort also competes with mergesort, another recursive sort algorithm but with the benefit of worst-case O(n^2) and best/average O(n log n) running time.
2. Mergesort is a stable sort, unlike standard in-place quicksort and heapsort, and can be easily adapted to operate on linked lists and very large lists stored on slow-to-access media such as disk storage or network attached storage
Heap sort :
Heapsort primarily competes with quicksort, another very efficient general purpose nearly-in-place comparison-based sort algorithm.
Quicksort is typically somewhat faster due to some factors, but the worst-case running time for quicksort is O(n2), which is unacceptable for large data sets and can be deliberately triggered given enough knowledge of the implementation, creating a security risk. See quicksort for a detailed discussion of this problem and possible solutions.
Thus, because of the O(n log n) upper bound on heapsort's running time and constant upper bound on its auxiliary storage, embedded systems with real-time constraints or systems concerned with security often use heapsort.[citation needed]
Heapsort also competes with merge sort, which has the same time bounds. Merge sort requires Ω(n) auxiliary space, but heapsort requires only a constant amount. Heapsort typically runs faster in practice on machines with small or slow data caches, and does not require as much external memory. On the other hand, merge sort has several advantages over heapsort:
Merge sort on arrays has considerably better data cache performance, often outperforming heapsort on modern desktop computers because merge sort frequently accesses contiguous memory locations (good locality of reference); heapsort references are spread throughout the heap.
Heapsort is not a stable sort; merge sort is stable.
Merge sort parallelizes well and can achieve close to linear speedup with a trivial implementation; heapsort is not an obvious candidate for a parallel algorithm.
Merge sort can be adapted to operate on singly linked lists with O(1) extra space. Heapsort can be adapted to operate on doubly linked lists with only O(1) extra space overhead.[citation needed]
Merge sort is used in external sorting; heapsort is not. Locality of reference is the issue.
Introsort is an alternative to heapsort that combines quicksort and heapsort to retain advantages of both: worst case speed of heapsort and average speed of quicksort.
Quicksort
public class QuickSort {
public static void main(String[] args) {
QuickSort obj = new QuickSort();
int[] a = new int[] {3,5,2,7,6,1};
// int[] a = new int[] {1,2,10,4,5};
obj.quickSort(a, 0, a.length-1);
//System.out.println("sorted array ==" + a.toString());
}
public void swap(int[] a, int index1, int index2){
int temp = a[index1];
a[index1] = a[index2];
a[index2] = temp;
}
public int partition(int[] a, int low, int high){
int pivot = a[high];
int m = low;
for(int i=low; i <= high-1; i++){
if(a[i] < pivot){
//put all elements less than pivot to the left of pivot
swap(a, i, m);
m++;
}
}
swap(a, m, high);
return m;
}
public void quickSort(int[] a, int low, int high){
if(low < high){
int pivot = partition(a, low, high);
quickSort(a, low, pivot-1);
quickSort(a, pivot+1, high);
}
}
}
Thursday, July 21, 2016
Web mining popular foods from Yelp
A couple of months ago, when I tried getting a list of food names (to help with a web mining application, that extracts food names from yelp reviews and provides suggestions on the most popular foods of the restaurant are), I was hardly able to find any. However, I managed to write my algorithm based on wikipedia and wordnet apis to extract out a list of food names, which I am posting here - so some other fellow programmer can benefit from it.
Note: the file preview take a little bit of time to load. You can alternatively find the file at https://gist.github.com/dhiviyadhanasekar/7584daac63e305f3ca89db44f76580eb.js
Code for the application: https://github.com/dhiviyadhanasekar/MiningYelp
Web app code: https://github.com/dhiviyadhanasekar/MiningYelp/tree/master/webapp
Web app demo: http://dhiviyad.96.lt/webapp/popular_foods.php/
Note: the file preview take a little bit of time to load. You can alternatively find the file at https://gist.github.com/dhiviyadhanasekar/7584daac63e305f3ca89db44f76580eb.js
Code for the application: https://github.com/dhiviyadhanasekar/MiningYelp
Web app code: https://github.com/dhiviyadhanasekar/MiningYelp/tree/master/webapp
Web app demo: http://dhiviyad.96.lt/webapp/popular_foods.php/
Labels:
HTML,
Jquery,
Personal Project,
PHP,
Python,
Web mining
Tuesday, June 7, 2016
Progress Bar using vanilla Javascript
Problem
Create a button to add a progress bar on click. Everytime a progress bar is added, it should start loading and reach 100% completion.
See the Pen pbjRPd by Dhiviya Dhanasekar (@dhiviyadhanasekar) on CodePen.
Labels:
Animations,
CSS,
HTML,
Interview,
Javascript
Wednesday, March 16, 2016
Edit textbox on clicking an image & save on clicking outside
This was my response to a stackoverflow question: http://stackoverflow.com/questions/36045974/how-to-create-an-editable-textbox/36046548#36046548
Monday, March 7, 2016
React ContentEditable Div
A custom contentEditable div, with placeholder text styling:
Part 1: The JSX component file
var ContentEditableDiv = module.exports = React.createClass({
handleKeyPress: function(e){
e.stopPropagation();
if(getKeyCode(e) == 13) {
e.preventDefault();
e.target.blur();
if(this.props.onEnterKey) this.props.onEnterKey(e);
}
},
onBlur: function(e){
e.stopPropagation();
// console.log('blurring called from content_editable div react');
if(this.props.onBlur) {
console.log('e', e);
var el = $(e.target);
var text = $.trim(el.text());
el.text(text); //just to keep it in sync
this.props.onBlur(text, e);
}
},
onKeyDown: function(e){
if(this.props.onKeyDown) this.props.onKeyDown(e);
},
render: function(){
// console.log('render content content_editable', this.props.text.length);
var klass = this.props.class + " content_editable";
var placeholder = this.props.placeholder ? this.props.placeholder : "Type here";
return (
<div classname="{klass}" contenteditable="{true}" id="{this.props.id}" onblur="{this.onBlur}" onkeydown="{this.props.onKeyDown}" onkeypress="{this.handleKeyPress}" placeholder="{placeholder}">
{this.props.text}
</div>
)
}
});
Part 2: CSS Styling:
.content_editable
border: none
outline: none
height: 17.55px
padding-right: 2px !important
&:focus
white-space: normal
border-bottom: 1px solid black
.content_editable:empty:before
content: attr(placeholder)
display: block /* For Firefox */
&:hover
cursor: text
.content_editable:focus:empty:before
content: ""
display: block /* For Firefox */
margin-top: 19px /* To make sure the border doesn't go up */
min-width: 90px
Jquery list attributes of an element
$('#ElemId').each(function() {
$.each(this.attributes, function() {
// this.attributes is not a plain object, but an array
// of attribute nodes, which contain both the name and value
if(this.specified) {
console.log(this.name, this.value);
}
});
});
SVG Add Class, Delete Class for Jquery
svgAddClass($(".myClass"), "selected_class");
svgRemoveClass($(".myClass"), "selected_class");
/**
date: 26th Jan 2016
Jquery doesn't support add class for svg currently
workaround function for that
**/
function svgAddClass(svgElem, className){
var classList = svgElem.attr('class') + " " +className;
console.log('classList', classList);
svgElem.attr('class', classList);
}
function svgRemoveClass(svgElem, className){
var classList = svgElem.attr('class').replace(className, '');
console.log('classList', classList);
svgElem.attr('class', classList);
}
Subscribe to:
Posts (Atom)