how to assign value using charCode? - javascript

I want to convert string to bytes it worked fine if i assign value to var str as $scope.event[0] it gives me bytes only for first index ,if i assign $scope.event[] it hrows error str.charCodeAt is not a function. How can i get total bytes of the array ?
ctrl.js
$scope.event = ["lorem ipsum", "lorem ipsum","lorem ipsum"]
function jsonToArray() {
var total = 0;
var str = $scope.event;
var bytes = []; // char codes
var bytesv2 = []; // char codes
for (var i = 0; i < str.length; ++i) {
var code = str.charCodeAt(i);
bytes = bytes.concat([code]);
bytesv2 = bytesv2.concat([code & 0xff, code / 256 >>> 0]);
}
var totalBytes = 0;
console.log('bytes', bytes.join(', '));
for ( var i = 0 ; i < bytes.length ; i++ ) {
totalBytes += bytes[i];
totalCurrentBytes.push(totalBytes);
}
console.log('Total bytes', totalBytes);
formatBytes(totalBytes);
}
jsonToArray();

You can map/reduce the array to convert the strings to char codes. Start by running map over your keywords (we want to convert one array into another), with each word, split the word into an array so you are working with each letter and reduce that array of characters into the sum of their charCodes:
$scope.event.map(word => word.split('').reduce((total,cur) => total + cur.charCodeAt(0), 0));
Non ES6
$scope.event.map(function(word) {
return word.split(' ').reduce(function(total, cur) {
return total + cur.charCodeAt(0);
}, 0);
});

Related

I have a string with counts and alphabets in ordered manner i have to print the alphabets according to their count

var input = `2
6
z2k1o2
6
m2v1p2`
var newInput = input.split("\n")
//console.log(newInput.length)
var input_arr = input.trim().split("\n")
var n = Number(input_arr[0])
//console.log(input_arr)
for (var i = 1; i < input_arr.length; i = i + 2) {
var length = Number(input_arr[i])
var string = input_arr[i + 1].trim()
}
//console.log(string)
var newstring = string
//console.log(newstring)
var alpha = []
var num = []
for (i = 1; i < string.length; i += 2) {
num.push(string[i])
}
var newnum = num.map(Number)
//console.log(newnum)
for (i = 0; i < string.length; i += 2) {
alpha.push(string[i])
}
var newalpha = (alpha)
//console.log(newalpha)
var answer = []
for (i = 0; i < newnum.length; i++) {
for (j = 0; j < newnum[i]; j++) {
answer.push(newalpha[i])
}
}
console.log(answer.join(""))
Here I'm getting only one output can you please explain why And do you like share any other approach for this problem.
This is the input z2k1o2 and the output should be zzkoo
The input will follow this patter of alphabets ans counts..
I'd do this with a regular expression that captures pairs of (character, number) and uses the function-replacement mode of .replace() to generate the replacement string.
> "a2b1c2".replace(/([a-z])([0-9]+)/ig, (_, a, b) => a.repeat(+b))
"aabcc"
>"pos2es2".replace(/([a-z])([0-9]+)/ig, (_, a, b) => a.repeat(+b))
"possess"
Here's where you're running into your error:
for (var i = 1; i < input_arr.length; i = i + 2) {
var length = Number(input_arr[i])
var string = input_arr[i + 1].trim()
}
You're going through the entire input array and saving each of the lengths and strings, but you're overwriting the length and the string each time you read it - only the last length and last string are saved, and so only the last length and last string are processed / printed.

How to repeat characters in a string in javascript by using slice function?

Can anyone shed light on how to frame a javascript function with two parameters: string and character, and only by using the slice method, return the number of times "a" appears in "lava"?
without slice method
var fruits= "lavaaagg";
var count=0;
for(var i=0;i<fruits.length;i++){
if(fruits[i]!='a')
count++;
}
console.log(fruits.length-count);
I'm not sure why you need the slice method. The slice method isn't for searching substrings (or characters in your case), it extracts a substring.
This should work fine:
function howManyCharInStr(str, char) {
return str.split(char).length - 1;
}
Step-by-step explanation:
str.split(char)
Creates an array of str substrings, using char as a separator. For example:
'fooXbazXbar'.split('X')
// Evaluates to ['foo', 'baz', 'bar']
'lorem ipsum dolor'.split('m')
// Evaluates to ['lore', ' ipsu', ' dolor']
Notice how the array returned has a length of n+1 where n is the number of separators there were. So use
str.split(char).length - 1;
to get the desired result.
For getting number of charecters count
<script type="text/javascript">
function FindResults() {
var firstvariable= document.getElementById('v1');
var secondvariable = document.getElementById('v2');
var rslt = GetCharecterCount(firstvariable, secondvariable );
}
function GetCharecterCount(var yourstring,var charecter){
var matchesCount = yourstring.split(charecter).length - 1;
}
</script>
using slice method
var arr = yourstring.split(charecter);
for( var i = 0, len = arr.length; i < len; i++ ) {
var idx = yourstring.indexOf( arr[i] );
arr[i] = pos = (pos + idx);
str = str.slice(idx);
}
var x= arr.length-1;
example http://jsfiddle.net/rWJ5x/2/
Using slice method
function logic(str,char){
var count = 0;
for(var i = 0; i < str.length; i++){
if(str.slice(i,i+1) == char){
count++;
}
}
return count;
};
console.log( "count : " + logic("lava","a") );
repeat last character of sting n number of times..
function modifyLast(str, n) {
var newstr = str.slice(-1)
var newlaststr = newstr.repeat(n-1)
var concatstring = str.concat(newlaststr);
return concatstring;
}
//modifyLast();
console.log(modifyLast("Hellodsdsds", 3))

How can I make my output appear all on one line with no spaces?

I have a simple Javascript problem that I'm working on, where the point is to...
Take an input, like 123
Separate the input as single digits, then square those single digits, thus getting 149.
Display that "149" (in this case) as an output.
I don't know how to display it as 149. I can only show it as
1
4
9
Sure, I might try adding it to an array then for looping the results... something tells me that this is the slow solution, and that there is a faster one. Here's my code.
function squareDigits(num) {
//Convert input to string
num = num + "";
var newnum;
var len = num.length;
//Split into digits, and square that result baby
for (i = 0; i < len; i++) {
var digit = num.substr(i, 1);
newnum = Math.pow(digit, 2);
console.log(newnum);
}
}
squareDigits(123);
Create empty array outside of the loop
Add squares of the each digit in the array
Join the array after loop finishes
function squareDigits(num) {
num = '' + num;
var len = num.length;
var squares = []; // Define empty array
//Split into digits, and square that result baby
for (i = 0; i < len; i++) {
var digit = num.substr(i, 1);
squares.push(Math.pow(digit, 2)); // Push the square of the digit at the end of array
}
return squares.join(''); // Join the array elements with empty string as glue
}
var squares = squareDigits(123);
console.log(squares);
document.write(squares);
By string concatenation
Declare a empty string before the for loop
Concatenate the square of the digit to the string by first casting the number to string
function squareDigits(num) {
//Convert input to string
num = num + "";
var newnum = ''; // Decalare variable with Empty string
var len = num.length;
//Split into digits, and square that result baby
for (i = 0; i < len; i++) {
var digit = num.substr(i, 1);
newnum += '' + Math.pow(digit, 2); // Cast the square to string and then concatenate to the string
}
return newnum; // Return the string
}
var squares = squareDigits(123);
document.write(squares);
Try utilizing String.prototype.split() , Array.prototype.map() , Array.prototype.join()
function squareDigits(num) {
return String(num).split("")
.map(function(n) {
return Math.pow(n, 2);
}).join("");
}
console.log(squareDigits(123));
What about this?
function squareDigits(num) {
//Convert input to string
num = num + "";
var newnum;
var len = num.length;
var digits = '';
//Split into digits, and square that result baby
for (i = 0; i < len; i++) {
var digit = num.substr(i, 1);
newnum = Math.pow(digit, 2);
digits += '' + newnum
}
console.log(digits);
}
try process.stdout.write, as in
process.stdout.write(newnum);

Take random letters out from a string

I want to remove 3 RANDOM letters from a string.
I can use something like substr() or slice() function but it won't let me take the random letters out.
Here is the demo of what I have right now.
http://jsfiddle.net/euuhyfr4/
Any help would be appreciated!
var str = "hello world";
for(var i = 0; i < 3; i++) {
str = removeRandomLetter(str);
}
alert(str);
function removeRandomLetter(str) {
var pos = Math.floor(Math.random()*str.length);
return str.substring(0, pos)+str.substring(pos+1);
}
If you want to replace 3 random charc with other random chars, you can use 3 times this function:
function substitute(str) {
var pos = Math.floor(Math.random()*str.length);
return str.substring(0, pos) + getRandomLetter() + str.substring(pos+1);
}
function getRandomLetter() {
var letters="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var pos = Math.floor(Math.random()*letters.length);
return letters.charAt(pos);
}
You can split the string to an array, splice random items, and join back to a string:
var arr = str.split('');
for(var i=0; i<3; ++i)
arr.splice(Math.floor(Math.random() * arr.length), 1);
str = arr.join('');
var str = "cat123",
amountLetters = 3,
randomString = "";
for(var i=0; i < amountLetters; i++) {
randomString += str.substr(Math.floor(Math.random()*str.length), 1);
}
alert(randomString);
fiddle:
http://jsfiddle.net/euuhyfr4/7/
This answer states that
It is faster to slice the string twice [...] than using a split followed by a join [...]
Therefore, while Oriol's answer works perfectly fine, I believe a faster implementation would be:
function removeRandom(str, amount)
{
for(var i = 0; i < amount; i++)
{
var max = str.length - 1;
var pos = Math.round(Math.random() * max);
str = str.slice(0, pos) + str.slice(pos + 1);
}
return str;
}
See also this fiddle.
you can shuffle characters in your string then remove first 3 characters
var str = 'congratulations';
String.prototype.removeItems = function (num) {
var a = this.split(""),
n = a.length;
for(var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return a.join("").substring(num);
}
alert(str.removeItems(3));
You can use split method without any args.
This would return all chars as a array.
Then you can use any randomiser function as described in Generating random whole numbers in JavaScript in a specific range? , then use that position to get the character at that position.
Have a look # my implementation here
var str = "cat123";
var strArray = str.split("");
function getRandomizer(bottom, top) {
return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
}
alert("Total length " + strArray.length);
var nrand = getRandomizer(1, strArray.length);
alert("Randon number between range 1 - length of string " + nrand);
alert("Character # random position " + strArray[nrand]);
Code # here https://jsfiddle.net/1ryjedq6/

How to generate every bitmask of X length in javascript

I am wanting to create an array of bitmasks of X length and am looking for an efficient function.
For length 3 I would like it to generate:
000, 001, 010, 011, 100, 101, 110, 111
I am looking for a solution that uses bit math to do so - right now I am just using regular for loops as my bit operations is rudimentary.
Did you try the following:
function range(til) {
var x = 0, xs = [];
while (x < til) xs.push(x++);
return xs;
}
function generate(n) {
return range(Math.pow(2, n));
}
Now you can generate all the numbers from 0 to 7 as follows:
var xs = generate(3);
If you want it in string format then use the following function instead:
function replicate(n, x) {
var i = 0, xs = [];
while(i++ < n) xs.push(x);
return xs;
}
function generateBitmasks(n) {
var padding = replicate(n, '0').join('');
return range(Math.pow(2, n)).map(function (x) {
return (padding + x.toString(2)).slice(-n);
});
}
Now you can get the list of bitmasks for 0 to 7 as follows:
var bitmasks = generateBitmasks(3);
I hope that helped.
It's just this:
var length = 3,
limit = 1 << length; //Shift length bytes to the left
for(mask=0; mask < limit; mask++){
console.log(mask); //This will log in decimal, but the bin value is correct
}
They're basically the binary representations of all numbers from 0 to 2^n-1
Hope this helps. Cheers
This is the same idea from Aadit M Shah, merged with Edgar Villegas Alvardo's.
// Pad with left 0's
function pad(val, width) {
val = val + '';
return val.length >= width ? val : new Array(width - n.length + 1).join('0') + val;
}
// Get a list of decimal numbers representing all the bitmasks up to the given length
function getBitmapDecimalList(length) {
var bitmaskMax = 1 << length;
var bitmaskList = [];
for (var i = 0; i < bitmaskMax; i++) {
bitmaskList.push(i);
}
return bitmaskList;
}
// Get a list of strings representing all the bitmasks up to the given length
function getBitmapBinaryList(length) {
var bitmaskMax = 1 << length; // Shift operator, equivalent to Math.pow(2,length)
var bitmaskList = [];
for (var i = 0; i < bitmaskMax; i++) {
// the `.toString(2)` is what transforms the number into a binary string
var bitmaskBinary = Number(i).toString(2);
var paddedBitmask = pad(bitmaskBinary, length);
bitmaskList.push(paddedBitmask);
}
return bitmaskList;
}

Categories

Resources