I am developing a program where I need to find out index/position of given excel column's index.
if I passed A it should return 1
if I passed AA it should return 27
if I passed AB it should return 28
if I passed AAA it should return 26*26*26 (not sure but want to get actual position)
what I did so far
var str = "AB";
var d = 0;
for (var i = 1, m = 26; i < string.length ; i++) {
if(string.length === 1) {
var d = parseInt(string.charCodeAt(i) - index);
} else if (string.length === 2){
var d = parseInt(((string.charCodeAt(i) - index) * m ) + (i));
} else {
var d = parseInt(((string.charCodeAt(i) - index) * m ) + (i));
}
}
var str = "MM19";
var number_regex = /[+-]?\d+(\.\d+)?/g;
var matches = [];
str.replace(number_regex, function (match) {
matches.push(match);
});
str = str.replace(/[0-9]/g, '');
matches.push(str);
console.log(matches[1]);
var index = 64;
var string = matches[1];
var columnIndex = 0;
var counter = 0;
var baseValue;
var m = 26;
console.log("length is:", string.length);
for (var i = string.length-1; i >= 0; i--) {
columnIndex = columnIndex + (string.charCodeAt(i) - index) * Math.pow(m, counter);
counter++;
}
console.log("index value", columnIndex);
Related
I want to produce an output from a string like this:
str = "1.000;74.85;10.000;62.13;9999;74.85;15000";
To:
1-10 : 74.85
10-9999 : 62.13
9999-15000 : 74.85
So that the indexes end up like this:
1-3 : 2
3-5 : 4
5-7 : 6
And the odd indexes get converted to integers
I wrote some script but the result is not expected and I think that it is too much code. There is probably some other shorter way.
My code:
var str = "1.000;74.85;10.000;62.13;9999;74.85;15000";
var delimiter = ';';
function splitString(stringToSplit, separator) {
return stringToSplit.split(separator);
}
var arr = splitString(str, delimiter);
var oddElement = [];
var evenElement = [];
for (var i = 0; i < arr.length; i++) {
if ((i % 2) === 0) {
oddElement.push(parseInt(arr[i]))
} else if ((i % 2) != 0) {
evenElement.push(arr[i]);
}
}
function duplicateElements(array, times) {
return array.slice(1,-1).reduce((res, current) => {
return res.concat(Array(times).fill(current));
}, []);
}
oddElement = duplicateElements(oddElement, 2);
oddElement.unshift(parseInt(arr[0]));
oddElement.push(parseInt(arr[arr.length - 1]));
temp = [];
for (var i = 0; i < oddElement.length; i ++) {
temp.push(oddElement[i] + '-' + oddElement[++i]);
}
evenElement.forEach(function(el) {
for (var i = 0; i < temp.length; i++) {
console.log(temp[i] + ":" + el);
}
})
console.log(temp);
console.log(evenElement);
var str = "1.000;74.85;10.000;62.13;9999;74.85;15000";
var arr = str.split(';');
var len = arr.length;
var data = [];
for (i = 1; i < arr.length - 1; i+=2) {
data.push(arr[i - 1] + '-' + arr[i + 1] + ' : ' + arr[i]);
}
This would be a functional way to do it:
Split
Parse each value
create objects containing start(s), end(e) and value(v) for each range
(optional) map over objects to make strings
const str = "1.000;74.85;10.000;62.13;9999;74.85;15000";
function format1(s, d = ';') {
return s
.split(d)
.map(n => parseFloat(n))
.reduce((r, n, i, a) => {
if (i > 1 && i % 2 === 0)
r.push({
s: a[i - 2],
v: a[i - 1],
e: n
});
return r;
}, []);
}
const formatted1 = format1(str);
const formatted2 = formatted1.map(({
s,
v,
e
}) => `${s}-${e} : ${v}`);
console.log(formatted1);
console.log(formatted2);
You can just use a single loop and append your answer to a string one line at a time. An easy way to design this type of logic is to look at your desired result by index in the split array:
parseInt(splitStr[1]) + "-" + parseInt(splitStr[3]) + " : " + splitStr[2]
Then just figure out how to get that same result on each iteration of the loop:
str = "1.000;74.85;10.000;62.13;9999;74.85;15000";
splitStr = str.split(";");
outputStr = "";
for (let i = 0 ; i < splitStr.length - 2 ; i += 2) {
outputStr += parseInt(splitStr[i]) + "-" + parseInt(splitStr[i + 2]) + " : " + splitStr[i + 1] + "\n";
}
console.log(outputStr);
My HW assignment requires me to have a user enter integers and for it to come out on the HTML in sorted array without the sort method. I have this code and it asks the users input but the integers do not come up on page.
<script type="text/javascript">
var arr = [];
function addNum() {
var n = prompt("How many integrs?", "0");
var num = parseInt(n);
for (var i = 0; i < num; i++) {
arr[i] = parseInt(prompt("Enter next integer: ","0"));
}
var outputSorted = document.getElementById('outputSorted');
outputSorted = "";
outputSorted.append("Input array : ");
for (var i = 0; i < num; i++) {
outputSorted.append(arr[i]+" ");
}
bubbleSort(arr);
outputSorted.append("Sorted array : ");
for (var i = 0; i < num; i++) {
outputSorted.append(arr[i]+" ");
}
}
function bubbleSort(a) {
var swapped;
do {
swapped = false;
for (var i=0; i < a.length - 1; i++) {
if (a[i] > a[i+1]) {
var temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
swapped = true;
}
}
} while (swapped);
}
function searchNum() {
var m = parseInt(prompt("Enter num to be searched: ","0"));
var found = binarySearch(arr, m);
var outputSearch = document.getElementById('outputSearch');
if (found == -1) {
outputSearch.append("Number not found");
} else {
outputSearch.append("Number found at index : " + (found + 1));
}
}
function binarySearch(array, targetValue) {
var min = 0;
var max = array.length - 1;
var guess;
while (min <= max) {
guess = Math.floor((max + min) / 2);
if (array[guess] === targetValue) {
return guess;
}
else if (array[guess] < targetValue) {
min = guess + 1;
}
else {
max = guess - 1;
}
}
return -1;
}
</script>
outputSorted is a DOM element, and append() is not a function of that element. Rather than that, use innerHTML += for each bit you want to add. See below. And note, those are the ONLY changes I made. So your ugly rendered HTML is what it is.
var arr = [];
addNum = function addNum() {
var n = prompt("How many integrs?", "0");
var num = parseInt(n);
for (var i = 0; i < num; i++) {
arr[i] = parseInt(prompt("Enter next integer: ", "0"));
}
var outputSorted = document.getElementById('outputSorted');
outputSorted.innerHTML += "Input array : "
for (var i = 0; i < num; i++) {
outputSorted.innerHTML += arr[i] + " ";
}
bubbleSort(arr);
outputSorted.innerHTML += "Sorted array : ";
for (var i = 0; i < num; i++) {
outputSorted.innerHTML += arr[i] + " ";
}
}
function bubbleSort(a) {
var swapped;
do {
swapped = false;
for (var i = 0; i < a.length - 1; i++) {
if (a[i] > a[i + 1]) {
var temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
swapped = true;
}
}
} while (swapped);
}
function searchNum() {
var m = parseInt(prompt("Enter num to be searched: ", "0"));
var found = binarySearch(arr, m);
var outputSearch = document.getElementById('outputSearch');
if (found == -1) {
outputSearch.innerHTML += ("Number not found");
} else {
outputSearch.innerHTML += ("Number found at index : " + (found + 1));
}
}
function binarySearch(array, targetValue) {
var min = 0;
var max = array.length - 1;
var guess;
while (min <= max) {
guess = Math.floor((max + min) / 2);
if (array[guess] === targetValue) {
return guess;
} else if (array[guess] < targetValue) {
min = guess + 1;
} else {
max = guess - 1;
}
}
return -1;
}
<button onclick="addNum()">
Add some!
</button>
<div id="outputSorted">
</div>
<div id="outputSearch">
</div>
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.
How can I split the below string into a 2dimensional-array:
Customer::Europe|UK|Scotland|Product::Drinks|Water|
array:
[Customer][Europe]
[Customer][UK]
[Customer][Scotland]
[Product][Drinks]
[Product][Water]
Not sure how to create the array. Haven't coded in years, so be kind
hArray= [];
vArray= [];
var i = j = 0;
var count = hierarchy.search(/[:|]+/);
write(hierarchy);
while (count > 0) {
if (hierarchy.indexOf(":") < hierarchy.indexOf("|") || (hierarchy.indexOf(":") > 0 && hierarchy.indexOf("|") == -1) ) {
hArray[j] = hierarchy.substr(0,hierarchy.indexOf(":"));
hierarchy = hierarchy.slice(hierarchy.indexOf(":")+2);
count = hierarchy.search(/[:|]+/);
j++;
} else
if (hierarchy.indexOf("|") < hierarchy.indexOf(":") {
vArray[i] = hierarchy.substr(0,count);
hierarchy = hierarchy.slice(count+1);
count = hierarchy.search(/[:|]+/);
i++;
}
if (count == -1) break;
//create multiArray ?
}
var source = "Customer::Europe|UK|Scotland|Product::Drinks|Water|";
var parts = source.split(/(\w+::)/);
var result = [];
for (var i = 1; i < parts.length; i += 2) {
var key = parts[i].replace("::", "");
var values = parts[i + 1].split("|");
for (var j = 0; j < values.length - 1; ++j) {
var line = new Array(2);
line[0] = key;
line[1] = values[j];
result.push(line);
}
}
console.log(result);
You can use Array.reduce like this. First, we split on | that is behind any owrd followed by ::. Then we reduce it, by using an array as memo and push an array into the memo, which we finally return.
var arr = input.split(/\|(?=\w+::)/).reduce(function(arr, str){
var array = str.split('::');
return arr.push(str.split('::')[1].split('|').filter(String).map(function(s){
return [array[0], s]
})), arr;
}, []);
I want to sort four dimensional array based on 1 column by using following method,
var main_arr = [
[]
];
var hdnFromValues = [11,16,12,17,14,18,15];
var hdnToValues = [12,17,13,18,15,19,16];
var hdnSPIDs = [11,12,13,14,0,0,0];
var hdnFlag = [D,E,E,D,A,A,A];
for (var j = 0; j < hdnFromValues.length; j++) {
var temp_arr = [];
var HdnToValue;
temp_arr.push(hdnFromValues[j]);
temp_arr.push(hdnToValues[j]);
temp_arr.push(hdnSPIDs[j]);
temp_arr.push(hdnFlag[j]);
main_arr.push(temp_arr);
temp_arr = null;
}
main_arr.sort(sort_by_col);
hdnFrom = "";
hdnTo = "";
spid = "";
flags = "";
for (var i = 1; i < main_arr.length; i++) {
hdnFrom = hdnFrom.concat(main_arr[i][0], ",");
hdnTo = hdnTo.concat(main_arr[i][1], ",");
spid = spid.concat(main_arr[i][2], ",");
flags = flags.concat(main_arr[i][3], ",");
}
hdnFrom = hdnFrom.substring(0, hdnFrom.length - 1);
hdnTo = hdnTo.substring(0, hdnTo.length - 1);
spid = spid.substring(0, spid.length - 1);
flags = flags.substring(0, flags.length - 1);
alert(hdnFrom);
alert(hdnTo);
alert(spid);
alert(flags);
function sort_by_col(a, b) {
return a[0] - b[0];
}
Sometimes, 3 & 4th column not arranging correctly as per 1st column.
Will someone help me?
JSFilddle
Change,
function sort_by_col(a, b) {
return a[0] - b[0];
}
to
function sort_by_col(a, b) {
return a[0] - b[0] || a[1] - b[1];
}