String.prototype.reverseStr = function () {
var len = this.length - 1;
var j = 0;
for (i = len; i >= Math.floor(len / 2); i--) {
var tmp = this[i];
this[i] = this[j];
this[j] = tmp;
j++;
}
return this;
}
alert("abcde".reverseStr());
Why doesn't this work ? It outputs "abcde" and not reversed string .
Overkill.
"abcde".split('').reverse().join('');
The same code but with some edits
String.prototype.reverseStr = function () {
var len = this.length - 1;
var tmp = '';
for (var i = len; i >= 0; i--) {
tmp += this[i];
}
return tmp;
}
alert("abcde".reverseStr());
See a fiddle here
Related
I am trying to write an insertion sort function that works from right to left.
Not in descending order. I just am not understanding why this code would not properly sort numbers.
function reverseInsertionSort(arr) {
for(var i = arr.length -1; i >0; i--)
var val = arr[i];
var j;
for(j = i; j > 0 && arr[j-1] < val; j--) {
arr[j-1] = arr[j]; }
va=arr[j]; }
function insertionSort(arr) {
for(var i = 1; i < arr.length; i++) {
var val = arr[i];
var j;
for(j = i; j > 0 && arr[j-1] > val; j--) {
arr[j] = arr[j-1]; }
arr[j] = val; }
}
arr[j] = val;
}
}
var length = Math.floor(Math.random()*100)+1;
var arr = new Array();
for(let i = 0; i < length; i++) {
arr.push(Math.floor(Math.random()*10000)+1);
}
var arr2= arr.slice();
reverseInsertionSort(arr2);
console.log(arr2)
It is not sorted, and the output ends in undefined.
arr is being used to test the insertionsort fun
Happy to accept constructive criticism.
This will work.
function reverseInsertionSort(arr) {
for(var i = arr.length-2; i>=0; i--) {
var value = arr[i];
var j;
for(j = i; ((j < arr.length) && (arr[j+1] > value)); j++){
arr[j] = arr[j+1];
}
arr[j] = value;
}
return arr;
}
//test
var inputArray = [3,2,4,5,1,10,23];
var resultArray = reverseInsertionSort(inputArray);
console.log(resultArray); //[23, 10, 5, 4, 3, 2, 1]
You should start the outer loop from the last element ie. len-1. The undefined member of the array is created due to your outer loop starting from arr.length .
Try this :
function insSort(arr){
for(var i=arr.length-1;i>=0;i--){
key=arr[i];
j=i+1;
while(j<arr.length&&arr[j]<=key){
arr[j-1]=arr[j];
j++;
}
arr[j-1]=key;
}
}
var length = Math.floor(Math.random()*100)+1;
var arr = new Array();
for(let i = 0; i < length; i++) {
arr.push(Math.floor(Math.random()*10000)+1);
}
console.log(arr);
insSort(arr);
console.log(arr);
I am attempting to write a javascript file that has a insertion sort function, a function to check a sorted array and return true or false, and an insertion sort function that works from the end of the array index to the beginning.
Here is the code i have
function insertionSort(arr) {
for(var i = 1; i < arr.length; i++) {
var val = arr[i]; var j; for(j = i; j > 0 && arr[j-1] > val; j--) {
arr[j] = arr[j-1]; } arr[j] = val; }
}
function reverseInsertionSort(arr) {
for(var i = arr.length; i >1; i--)
{ var val = arr[i]; var j;
for(j = i; j > 0 && arr[j-1] > val; j--)
{ arr[j] = arr[j-1]; } arr[j] = val;
} }
var length = Math.floor(Math.random()*100)+1;
var arr = new Array();
for(let i = 0; i < length; i++) {
arr.push(Math.floor(Math.random()*10000)+1);
}
console.log(arr);
//function sortCheck(arr) {
//for( var i = 0 ; i < arr.length; i++){
// if(arr[i]>rr[i+1]){
// return false
// }
//}
//return true}
var sortedArr = insertionSort(arr);
console.log(sortedArr);
console.log("And with reverse \n");
var reverseSortedArr = reverseInsertionSort(arr);
console.log(reverseSortedArr);
//console.log(sortCheck(sortedArr));
The issue I am having right now is that sortedArr is undefined when output with console.log, it appears that the issue is that my function is "undefined" but seeing how i define it above, i dont understand how that is.
Your insertionSort function doesn't return a value, it modifies the array passed as an argument. Instead of var sortedArr = insertionSort(arr), just call insertionSort(arr) and then do console.log(arr).
You have to return arr from the function. It is not returning anything that's why you are getting undefined
function insertionSort(arr) {
for(var i = 1; i < arr.length; i++) {
var val = arr[i]; var j; for(j = i; j > 0 && arr[j-1] > val; j--) {
arr[j] = arr[j-1]; } arr[j] = val; }
return arr; }
function reverseInsertionSort(arr) {
for(var i = arr.length; i >1; i--)
{ var val = arr[i]; var j;
for(j = i; j > 0 && arr[j-1] > val; j--)
{ arr[j] = arr[j-1]; } arr[j] = val;
} return arr}
var length = Math.floor(Math.random()*100)+1;
var arr = new Array();
for(let i = 0; i < length; i++) {
arr.push(Math.floor(Math.random()*10000)+1);
}
console.log(arr);
var sortedArr = insertionSort(arr);
console.log(sortedArr);
console.log("And with reverse \n");
var reverseSortedArr = reverseInsertionSort(arr);
console.log(reverseSortedArr);
//console.log(sortCheck(sortedArr));
Make sure you return the array from the function(s). Since you currently are not, assigning the function to a variable would not yield any particular value.
function insertionSort(arr) {
for(var i = 1; i < arr.length; i++) {
var val = arr[i];
var j;
for(j = i; j > 0 && arr[j-1] > val; j--) {
arr[j] = arr[j-1];
}
arr[j] = val;
}
return arr
}
The function is returning undefined why it's not returning the array length.even at the start of the code it's printing in the console but return is not working.
var resArr = [];
var p;
function persistence(num) {
resArr.push(num);
console.log(resArr);
console.log(resArr.length);
if (num > 10) {
var v = 1;
var x = num.toString();
var arr = [];
for (i = 0; i < x.length; i++) {
arr.push(x.charAt(i));
}
console.log(arr);
for (j = 0; j < arr.length; j++) {
var v = v * arr[j];
}
persistence(v);
} else {
return resArr.length - 1;
}
}
You're not returning in all cases.
Change
persistence(v);
to
return persistence(v);
Does anyone know a way to convert base 10 and base 255 strings in JavaScript exceeding the Number.MAX_SAFE_INTEGER value without using a big number library?
For something like:
var base10 = '23456786543234567876543234567876543267';
var base255 = base10ToBase255(base10);
To base-255 or from base-255 as:
var base255 = new Uint8Array(20);
for (var i = 0; i < 20; i++) base255[i] = 254 - i;
var base10 = base255ToBase10(base255);
EDITED: changed to allow for other bases (<=256)
It always boils down to using a big integer, sorry. But you do not need much, it's just about 100 lines of code for what you want (string to base 256 and back).
"use strict";
var COMMON_BASE = 255; // must be 256 at most!
function copyA(a){
var ret = new Uint8Array(a.length);
for(var i = 0;i<a.length;i++){
ret[i] = a[i];
}
return ret;
}
function isZero(a){
for(var i = 0;i<a.length;i++){
if(a[i] !== 0)
return false;
}
return true;
}
function clampA(a){
var alen = a.length;
var i=0;
while(a[alen - 1] === 0)alen--;
var ret = new Uint8Array(alen);
for(var i = 0;i<alen;i++){
ret[i] = a[i];
}
return ret;
}
function addD(a,d) {
var tlen = a.length;
var carry = 0;
var ret = new Uint8Array(tlen +1);
if(d === 0)
return copyA(a);
var i = 0;
var temp = carry;
temp += a[i] + d;
carry = Math.floor(temp / COMMON_BASE);
ret[i] = temp % COMMON_BASE;
for (i = 1; i < tlen; i++) {
temp = carry;
temp += a[i];
carry = Math.floor(temp / COMMON_BASE);
ret[i] = temp % COMMON_BASE;
}
if (carry) {
ret[i] = carry;
}
ret = clampA(ret);
return ret;
};
function mulD(a,d){
var tlen = a.length;
var carry = 0;
var ret = new Uint8Array(tlen + 1);
var k = 0;
var tmp;
if(isZero(a))
return copyA(a);
if(d === 0)
return new Uint8Array(tlen);
for (; k < tlen; k++) {
tmp = a[k] * d + carry;
ret[k] = tmp % COMMON_BASE;
carry = Math.floor(tmp / COMMON_BASE);
}
if (carry) {
ret[k] = carry;
}
ret = clampA(ret);
return ret;
}
function divRem(a,d){
var divrem = function(u, m, v, q, B) {
var k = 0,
t;
for (var j = m - 1; j >= 0; j--) {
k = (k * COMMON_BASE) ;
k += u[j];
if (k >= v) {
t = Math.floor(k / v);
k -= t * v;
} else {
t = 0;
}
q[j] = t;
}
return k;
};
var Q = new Uint8Array(a.length);
var R = divrem(a,a.length, d, Q, 8);
Q = clampA(Q);
return [Q,R];
}
// Assuming 's' being a string with decimal digits
function base10ToBase256(s){
var blen = 0;
// checks&balances omitted
var out = new Uint8Array(1);
for(var i=0;i<s.length;i++){
out = mulD(out,10);
out = addD(out,parseInt(s[i],10) );
}
return out;
}
// Assuming b being a Uint8Array
function base256ToBase10(a){
var s = "";
var t = copyA(a);
var qr = [];
var i = a.length;
while(!isZero(t)){
qr = divRem(t,10);
s = s + qr[1].toString(10);
t = qr[0];
}
return s.split("").reverse().join("");
}
var str = "8716418673416734167345634096788356249857";
//base10ToBase256(str).join(",");
base256ToBase10(base10ToBase256(str));
var str = "8716418673416734167345634096788356249857";
console.log(base10ToBase256(str).join(","));
console.log(base256ToBase10(base10ToBase256(str)));
Here the LSB is at position zero.
It's a rough hack (way too much copies etc.) but it'll do it.
Can anyone tell me why all the object.num's print as 1? This is driving me mad. Somehow after the for loop the values of the object.num = 1 no matter what, even though they are never set to 1. Please copy the entire segment to debug.
<script type="text/javascript">
window.addEventListener("load", main, false);
const n = 4;
function main()
{
var belt = new Array(4*n);
initArr(belt);
printIt(belt);
populateArr(belt);
printIt(belt);
reorder(belt);
printIt(belt);
}
function populateArr(arr)
{
var a = {name:"a", num:0};
var b = {name:"b", num:0};
var end = arr.length;
var i = end-1;
for(var temp = n; temp > 0; temp--)
{
a.num = temp;
arr[i] = a;
i-=2;
}
i = end-2;
for(var temp = n; temp > 0; temp--)
{
b.num = temp;
arr[i] = b;
i-=2;
}
return arr;
}
function printIt(arr)
{
var tempArr = new Array(arr.length);
for(var i=0; i < arr.length; i++)
{
tempArr[i] = arr[i].name + arr[i].num;
}
console.log(tempArr);
}
function initArr(arr)
{
var nothing = {name:null, num:0};
for(var i=0; i<arr.length; i++)
{
arr[i] = nothing;
}
return arr;
}
function reorder(arr)
{
var nothing = {name:null, num:0};
var counter = 0;
var aIndex = 0;
var bIndex = null;
for(var i=0; i < arr.length; i++)
{
if(arr[i].name === "b" && bIndex === null)//first b doesn't get moved
{
bIndex = i+1;
}
else if(arr[i].name === "a")
{
arr[aIndex] = arr[i];
arr[i] = nothing;
counter++;
aIndex++;
}
else if(arr[i].name ==="b")
{
arr[bIndex] = arr[i];
arr[i] = nothing;
counter++;
bIndex++;
}
}
console.log("count: " + counter);
console.log("n: " + n);
return arr;
}
</script>
Somehow after the for loop the values of the object.num = 1 no matter what, even though they are never set to 1.
Yes "they" are - "they're" set to 1 in the last iteration of this loop:
for(var temp = n; temp > 0; temp--)
{
a.num = temp;
arr[i] = a;
i-=2;
}
The last iteration of that loop is when temp is 1.
Now, you've only actually got one object - and you're setting every element of the array to be a reference to that object. That's why all the values in the array look the same. If you want to create a different object each time, you should use:
for(var temp = n; temp > 0; temp--)
{
arr[i] = { name: "a", num: temp };
i -= 2;
}