What is the name of this Sort Algorithm? - javascript

var counter = 0;
function sort(arr)
{
var totalItem = arr.length;
var temp ;
var index;
var isSortDone = true;
for( index = 0 ; index < totalItem ; index ++)
{
if(arr[index] > arr[index+1])
{
temp = arr[index];
arr[index] = arr[index+1];
arr[index+1] = temp ;
isSortDone = false;
}
if(arr[totalItem-(1+index)] < arr[totalItem-(2+index)] )
{
temp = arr[totalItem-(1+index)]
arr[totalItem-(1+index)] = arr[totalItem-(2+index)]
arr[totalItem-(2+index)] = temp
isSortDone = false;
}
counter++;
}
if(isSortDone == true) { console.log(counter + ":Sort is Done", arr); return 0;}
return sort(arr);
}

Looks like a recursive bi-directional version of bubblesort (https://en.wikipedia.org/wiki/Bubble_sort) similar to this variant: https://en.wikipedia.org/wiki/Cocktail_shaker_sort, but with both loops rolled into one (which doesn't make much of a difference wrt. performance or other characteristics).
Note that each recursive call could omit the first and last item, as they will be the smallest / biggest globally (you could implement this by adding an offset parameter).
Given that there may be up to n recursive calls, this is probably likely to cause a stack overflow.

Related

Join string based on startsWith() and endsWith()

I have string var str1 = 'foobarbaz' and var str2 = 'bazfoo'
I want to join them based on overlapping starting and ending characters. The result I am looking for is 'foobarbazfoo'.
I am currently doing it in a following way:
function merge(str1, str2) {
var size = Math.min(str1.length, str2.length);
index = 0;
for (var i = 0; i < size; i++) {
var ends = str1.substr(str1.length - i);
var starts = str2.substr(0, i);
if (ends === starts) {
index = i;
}
}
if (index === 0) {
throw 'Strings do not overlap';
} else {
return str1 + str2.substr(index, str2.length);
}
}
I wonder, if there is more elegant and efficient way of doing it ?
i think it would be a good idea to add the function to the String's prototype and using startsWith() and Conditional (ternary) Operator this what i could come up with :
String.prototype.merge = function(str) {
let match;
for (let i = this.length; i >= 0; i--)
(str.startsWith(this.slice(i))) && (match = this.slice(i));
return this.slice(0, this.indexOf(match)) + str.slice(str.indexOf(match), str.length)
}
let merged = 'foobarbaz'.merge('bazfoo')
console.log(merged);
in terms of speed, both methods are identical ( tested execution time with Performance.now() )
but less lines and a declarative rather than imperative code.
feel free to choose betwee slice and substring ( slice vs substring )

Perform a merge on two strings

I'm trying to build a collaborative doc editor and implement operational transformation. Imagine we have a string that is manipulated simultaneously by 2 users. They can only add characters, not remove them. We want to incorporate both of their changes.
The original string is: catspider
The first user does this: cat<span id>spider</span>
The second user does this: c<span id>atspi</span>der
I'm trying to write a function that will produce: c<span id>at<span id>spi</span>der</span>
The function I've written is close, but it produces c<span id>at<span i</span>d>spider</span> codepen here
String.prototype.splice = function(start, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start);
};
function merge(saved, working, requested) {
if (!saved || !working || !requested) {
return false;
}
var diffSavedWorking = createDiff(working, saved);
var diffRequestedWorking = createDiff(working, requested);
var newStr = working;
for (var i = 0; i < Math.max(diffRequestedWorking.length, diffSavedWorking.length); i++) {
//splice does an insert `before` -- we will assume that the saved document characters
//should always appear before the requested document characters in this merger operation
//so we first insert requested and then saved, which means that the final string will have the
//original characters first.
if (diffRequestedWorking[i]) {
newStr = newStr.splice(i, diffRequestedWorking[i]);
//we need to update the merge arrays by the number of
//inserted characters.
var length = diffRequestedWorking[i].length;
insertNatX(diffSavedWorking, length, i + 1);
insertNatX(diffRequestedWorking, length, i + 1);
}
if (diffSavedWorking[i]) {
newStr = newStr.splice(i, diffSavedWorking[i]);
//we need to update the merge arrays by the number of
//inserted characters.
var length = diffSavedWorking[i].length;
insertNatX(diffSavedWorking, length, i + 1);
insertNatX(diffRequestedWorking, length, i + 1);
}
}
return newStr;
}
//arr1 should be the shorter array.
//returns inserted characters at their
//insertion index.
function createDiff(arr1, arr2) {
var diff = [];
var j = 0;
for (var i = 0; i < arr1.length; i++) {
diff[i] = "";
while (arr2[j] !== arr1[i]) {
diff[i] += arr2[j];
j++;
}
j++;
}
var remainder = arr2.substr(j);
if (remainder) diff[i] = remainder;
return diff;
}
function insertNatX(arr, length, pos) {
for (var j = 0; j < length; j++) {
arr.splice(pos, 0, "");
}
}
var saved = 'cat<span id>spider</span>';
var working = 'catspider';
var requested = 'c<span id>atspi</span>der';
console.log(merge(saved, working, requested));
Would appreciate any thoughts on a better / simpler way to achieve this.

Newtons Method In JS Being Inaccurate

So, I am trying to write a js function that takes 3 inputs (polynomial, guess and limit) and make them return the approximate root of the polynomial. The problem is that, even with a limit of 1000, the result is still very inaccurate. Does anybody have any ideas on why this may be?
The Method
The code:
var derivativeOfATerm = function(arr) {
var one = arr[0];
var two = arr[1];
var derivative = [];
if (two <= 0) {
return [0, 0];
} else {
derivative.push(one * two);
derivative.push(two - 1);
return derivative;
}
};
var derivativeOfPolynomial = function(arr, order = 1) {
var derivative = [];
for (var i = 0; i < arr.length; i++) {
//console.log(arr[i]);
derivative.push(derivativeOfATerm(arr[i]));
}
if (order === 1) {
return derivative;
} else {
return derivativeOfPolynomial(derivative, order - 1);
}
};
var runPolynomial = function(poly, num) {
var array = [];
for (var i = 0; i < poly.length; i++) {
array.push(Math.pow(num, poly[i][1]) * poly[i][0]);
}
return array.reduce((a, b) => a + b);
};
var newtonRootFind = function(polynomial, guess, limit = 10) {
var derivative = derivativeOfPolynomial(polynomial);
var previous = guess;
var next;
for (var i = 0; i < limit; i++) {
next = previous - (runPolynomial(polynomial, previous)) / (runPolynomial(derivative, previous));
previous = next;
console.log("%o : x=%o, p(x)=%o", i+1, next, runPolynomial(polynomial, next));
}
return previous;
};
console.log("result x=",newtonRootFind([[1,2],[1,1],[-5,0]], 5, 10));
I'm only 12 so try not to use that many technical terms.
For example, entering [[1,2],[1,1],[-5,0]] or x^2+x-5, it returns 1.79128784747792, which isn't accurate enough. It equals 4.79... when it should be very close to 5.
As worked out in the comments, the presented code works as intended, the problem was that in checking the solution x^2 was used for the square x*x.
However, x^y in most C- or Java-like languages is the bitwise "exclusive or", XOR, not the power operation. x^y as symbol for the power operation is usually found in Computer Algebra Systems. Script languages as python or gnuplot tend to use x**y.

"Look and say sequence" in javascript

1
11
12
1121
122111
112213
122211
....
I was trying to solve this problem. It goes like this.
I need to check the former line and write: the number and how many time it was repeated.
ex. 1 -> 1(number)1(time)
var antsArr = [[1]];
var n = 10;
for (var row = 1; row < n; row++) {
var lastCheckedNumber = 0;
var count = 1;
antsArr[row] = [];
for (var col = 0; col < antsArr[row-1].length; col++) {
if (lastCheckedNumber == 0) {
lastCheckedNumber = 1;
antsArr[row].push(lastCheckedNumber);
} else {
if (antsArr[row-1][col] == lastCheckedNumber) {
count++;
} else {
lastCheckedNumber = antsArr[row-1][col];
}
}
}
antsArr[row].push(count);
antsArr[row].push(lastCheckedNumber);
}
for (var i = 0; i < antsArr.length; i++) {
console.log(antsArr[i]);
}
I have been on this since 2 days ago.
It it so hard to solve by myself. I know it is really basic code to you guys.
But still if someone who has a really warm heart help me out, I will be so happy! :>
Try this:
JSFiddle Sample
function lookAndSay(seq){
var prev = seq[0];
var freq = 0;
var output = [];
seq.forEach(function(s){
if (s==prev){
freq++;
}
else{
output.push(prev);
output.push(freq);
prev = s;
freq = 1;
}
});
output.push(prev);
output.push(freq);
console.log(output);
return output;
}
// Sample: try on the first 11 sequences
var seq = [1];
for (var n=0; n<11; n++){
seq = lookAndSay(seq);
}
Quick explanation
The input sequence is a simple array containing all numbers in the sequence. The function iterates through the element in the sequence, count the frequency of the current occurring number. When it encounters a new number, it pushes the previously occurring number along with the frequency to the output.
Keep the iteration goes until it reaches the end, make sure the last occurring number and the frequency are added to the output and that's it.
I am not sure if this is right,as i didnt know about this sequence before.Please check and let me know if it works.
var hh=0;
function ls(j,j1)
{
var l1=j.length;
var fer=j.split('');
var str='';
var counter=1;
for(var t=0;t<fer.length;t++)
{
if(fer[t]==fer[t+1])
{
counter++;
}
else
{
str=str+""+""+fer[t]+counter;
counter=1;
}
}
console.log(str);
while(hh<5) //REPLACE THE NUMBER HERE TO CHANGE NUMBER OF COUNTS!
{
hh++;
//console.log(hh);
ls(str);
}
}
ls("1");
You can check out the working solution for in this fiddle here
You can solve this by splitting your logic into different modules.
So primarily you have 2 tasks -
For a give sequence of numbers(say [1,1,2]), you need to find the frequency distribution - something like - [1,2,2,1] which is the main logic.
Keep generating new distribution lists until a given number(say n).
So split them into 2 different functions and test them independently.
For task 1, code would look something like this -
/*
This takes an input [1,1,2] and return is freq - [1,2,2,1]
*/
function find_num_freq(arr){
var freq_list = [];
var val = arr[0];
var freq = 1;
for(i=1; i<arr.length; i++){
var curr_val = arr[i];
if(curr_val === val){
freq += 1;
}else{
//Add the values to the freq_list
freq_list.push([val, freq]);
val = curr_val;
freq = 1;
}
}
freq_list.push([val, freq]);
return freq_list;
}
For task 2, it keeps calling the above function for each line of results.
It's code would look something like this -
function look_n_say(n){
//Starting number
var seed = 1;
var antsArr = [[seed]];
for(var i = 0; i < n; i++){
var content = antsArr[i];
var freq_list = find_num_freq(content);
//freq_list give an array of [[ele, freq],[ele,freq]...]
//Flatten so that it's of the form - [ele,freq,ele,freq]
var freq_list_flat = flatten_list(freq_list);
antsArr.push(freq_list_flat);
}
return antsArr;
}
/**
This is used for flattening a list.
Eg - [[1],[1,1],[1,2]] => [1,1,1,1,2]
basically removes only first level nesting
**/
function flatten_list(li){
var flat_li = [];
li.forEach(
function(val){
for(ind in val){
flat_li.push(val[ind]);
}
}
);
return flat_li;
}
The output of this for the first 10 n values -
OUTPUT
n = 1:
[[1],[1,1]]
n = 2:
[[1],[1,1],[1,2]]
n = 3:
[[1],[1,1],[1,2],[1,1,2,1]]
n = 4:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1]]
n = 5:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3]]
n = 6:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1]]
n = 7:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1],[1,1,2,3,1,2,3,1,1,1]]
n = 8:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1],[1,1,2,3,1,2,3,1,1,1],[1,2,2,1,3,1,1,1,2,1,3,1,1,3]]
n = 9:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1],[1,1,2,3,1,2,3,1,1,1],[1,2,2,1,3,1,1,1,2,1,3,1,1,3],[1,1,2,2,1,1,3,1,1,3,2,1,1,1,3,1,1,2,3,1]]

Generating a random value, keeping a history of returned values

For a project I'm working on, I needed a Javascript function that would return a random number, in a given range, without repeating itself until the whole range is 'depleted'. As there was no such thing around, I have managed to create it myself.
The function will also require an id to be passed. This way, if you require multiple random numbers, each with their own history, the id keeps track of them all.
The function works, however I need some advice;
is this the 'proper' way to achieve what I want to achieve?
how fast will inArray() perform with very big ranges (maxNum) values? I have a feeling that large numbers will slow the function down, as it is randomizing numbers until it generates a number that is still 'valid' (i.e. not in the history array). But I can't figure out another way to do this..
The script:
var UniqueRandom = {
NumHistory: [],
generate: function (maxNum, id) {
if (!this.NumHistory[id]) this.NumHistory[id] = [];
if (maxNum >= 1) {
var current = Math.round(Math.random() * (maxNum - 1)), x = 0;
if (maxNum > 1 && this.NumHistory[id].length > 0) {
if (this.NumHistory[id].length !== maxNum) {
while ($.inArray(current, this.NumHistory[id]) !== -1) {
current = Math.round(Math.random() * (maxNum - 1));
x = x + 1;
}
this.NumHistory[id].push(current);
} else {
//reset
this.NumHistory[id] = [current];
}
} else {
//first time only
this.NumHistory[id].push(current);
}
return current;
} else {
return maxNum;
}
},
clear: function (id) {
this.NumHistory[id] = [];
}
};
usage would be: (100 being the range (0-100) and the_id being.. well, the id)
UniqueRandom.NumHistory[100, 'the_id']
I have set up a Fiddle with a demo.
It's not best practice. Imo it would be better to instantiate an object per series of numbers that needs to be generated.
I'd suggest generating an array of all possible values and shuffling it. Then you can just pop of it.
I took Jack's code and adapted it to work with the popping array method.
function fisherYates ( myArray ) {
var i = myArray.length;
if ( i == 0 ) return false;
while ( --i ) {
var j = Math.floor( Math.random() * ( i + 1 ) );
var tempi = myArray[i];
var tempj = myArray[j];
myArray[i] = tempj;
myArray[j] = tempi;
}
}
function RandomGenerator(maxNum) {
this.max = maxNum;
this.initRandomArray();
}
RandomGenerator.prototype.generate = function() {
// if no more numbers available generate new array
if( this.left === 0 ) this.initRandomArray();
this.last = this.arr.pop();
this.left = this.arr.length;
this.history.push( this.last );
return this.last;
}
RandomGenerator.prototype.initRandomArray = function() {
this.arr = [];
this.history = [];
this.last = null;
this.left = this.max;
for( var i = 0; i < this.max; i++ ) {
this.arr.push( i );
}
fisherYates( this.arr );
}
var mygen = new RandomGenerator(100);
console.log( mygen.generate() );
I got the fisherYates algorithm from here.
The approach of generating a new random number if it is already found in a history object will result in unnecessary looping.
Fiddle here
I tend to think that it is indeed not most efficient. I dont immediately get the //first time only.
Further, you can make code more readable by skipping the else return .. and writing the condition to be the opposite, e.g.:
if (maxNum >= 1) {
//code
} else {
return maxNum;
}
becomes
if (maxNum < 1) { // or maybe even if maxNum == 0
return maxNum;
}
//code
Also your x variable seems to be redundant.
I would probably implement it like this, using actual instances of random generators. This keeps the history of each generator separated.
function RandomGenerator(maxNum)
{
this.max = maxNum;
this.history = {};
this.histn = 0;
}
// generate random number in range [0..maxNum)
RandomGenerator.prototype.generate = function()
{
var value;
if (this.histn == this.max ) {
return false;
}
do {
value = Math.floor(Math.random() * this.max );
} while (this.history[value]);
this.history['' + value] = 1;
++this.histn;
return value;
}
var mygen = new RandomGenerator(100);
console.log(mygen.generate());
In my implementation I'm choosing a plain object for the history instead of an array; testing whether a value has been generated before is done by testing a property instead of $.inArray().
I agree with Alex that in most use cases, you'd want to generate an array of all values, shuffle them, and then pop them as you need them instead.
Here is an example:
var getShuffledUniqueRandoms = function(count, suffix) {
var values = [];
for (var i = 1; i < count+1; i++) {
values.push(i + suffix);
}
// Shuffle function originally from:
//+ Jonas Raoni Soares Silva
//# http://jsfromhell.com/array/shuffle [v1.0]
return (function(o){ //v1.0
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
})(values);
}
var values = getShuffledUniqueRandoms(10, "index");
$('button').click(function() {
if (values.length == 0) {
$('body').append('<p>Out of values.</p>');
} else {
$('body').append('<p>' + values.pop() + '</p>');
}
});
​
​FIDDLE
With this algorithm, it has a bigger upfront cost, but at least it has a known time it'll take to complete (roughly O(n)).
With the algorithm where you are constantly checking to see if a random value is in an array, it'll get slower and slower with each new iteration.
Now if your data set is always relatively small, your algorithm could work a little better, but anything larger than 10 or so and it starts losing it's edge.

Categories

Resources