Javascript: Rows of string characters - javascript

So I am trying to create a function that takes the first input as a number and the second input as a string. the function should then change the innerHTML of the div with the characters of the second input. For example. if the first input was number 2 and second input was hello the innerHTML should change to:
h
ee
if the first was number 5 all else being the same:
h
ee
lll
llll
ooooo
I know I must use str.charAT and possibly a for loop (probably any loop) but just cant seem to piece it together in my head. I have been stuck on this for 6 hours now and I have no idea how to do it. So here I am asking for help XD, help my please! If any hints are out there I would gladly take them, this is just a random exercise to help me get used to js. If you would rather like to give the entire that is fine too, I mean it helps alot more than a hint considering i can learn from it.
the number cannot go past the amount of characters within the string. So far here is the html and javascript that I made.
<html>
<head>
<script src="q2.js" type="text/javascript"></script>
</head>
<body>
<div> Input1<input id="input1" type="text"></div>
<div> Input2<input id="input2" type="text"></div>
<div> Result<div id="result"></div></div>
<button onclick="compute()">Compute</button>
</body>
<html>
JAVASCRIPT:
function compute(){
var n = Number(document.getElementById("input1").value);
var v = document.getElementById("input2").value;
var answer = document.getElementById("result");
var i,j;
answer.innerHTML = "";
if(n){
}else{
alert("whatever is in input 1 is not a number ya fookin cheeky buggah");
}
if(n>v.length){
alert("number 1 bigger than word 2");
}
for(i=0;i<n;i++){
for(j=0;)
}
}

This does what you need, however it may be using some array functions you're not familiar with
function compute() {
var n = Number(document.getElementById("input1").value);
var v = document.getElementById("input2").value;
var answer = document.getElementById("result");
if (!n) {
alert("whatever is in input 1 is not a number ya fookin cheeky buggah");
}
if (n > v.length) {
alert("number 1 bigger than word 2");
}
answer.innerHTML = [].slice.call(v, 0, n).map(function(letter, index) {
return new Array(index+2).join(letter);
}).join('<br />');
}
slice - we only want the first n characters
map - for each character, run the callback function
the callback function creates an Empty array which is 2 larger than the current index (0 based index)
joins this array on the letter - which produces index + 1 letters
the mapped array is joined by <br />
the result of this is output to answer.innerHTML
the answer.innerHTML code in ES2015 (ES6) would be
answer.innerHTML = [].slice.call(v, 0, n).map((letter, index) => letter.repeat(index+1)).join('<br />')

The answer using nested for loops and charAt
function compute() {
var n = Number(document.getElementById("input1").value);
var v = document.getElementById("input2").value;
var answer = document.getElementById("result");
var i, j, c, s = "";
if (n) {
}
else {
alert("whatever is in input 1 is not a number ya fookin cheeky buggah");
}
if (n > v.length) {
alert("number 1 bigger than word 2");
}
for (i = 0; i < n; i++) {
c = v.charAt(i);
if (i > 0) {
s += "<br />";
}
for (j = 0; j <= i; j++) {
s += c;
}
}
answer.innerHTML = s;
}

function compute() {
var n = Number(document.getElementById("input1").value);
var v = document.getElementById("input2").value;
var answer = document.getElementById("result");
if (!n) {
alert("whatever is in input 1 is not a number ya fookin cheeky buggah");
}
if (n > v.length) {
alert("number 1 bigger than word 2");
}
var res ="";
for(var i=1; i<=v.length; i++){
res = res +"\n"+ Array(i+1).join(v.charAt(i));
}
answer.innerHTML = res;
}
Whoever finds this answer to be useful or valid or wrong, please post ur comments or click the up/down arrow. Just to improve myself further.

Related

function that randomly sorts through letters and changes them not working

I am making a javascript function that will input a string, and output a "spongebob mocking text"
basically, you input "Hello, this is a message to the world" and you would get "HeLlO, ThIS iS a MeSsAGe tO tHE wORlD"
basically, randomly decide wheather to capitalize a letter or not. I made a function which i thought would do that, but it didn't work. here is the code that I tested in the js console:
function memify(input) { // function called memify()
var il = input.length; // gets the length of the input
var newinput = input; // creates a new variable that will be changed from input.
for (var i=0;i>il;i++) {
var rng = Math.floor((Math.random()*2)); // random number between 0 and 1. 0 = upper 1 = lower
if (rng === 0) {
newinput.charAt(i).toUpperCase();
}
else {
newinput.charAt(i).toLowerCase();
}
}
return newinput;
}
var text = prompt();
var textmeme = memify(text);
alert(textmeme);
Why is this not working? Do I have an error in my code? Any help will be greatly appreciated.
When you do
newinput.charAt(i).toUpperCase();
you're creating a new uppercase character, but you aren't doing anything with it; it's just an unused expression, so there's no visible change. Primitives (including strings) are immutable - you should explicitly reassign a string to something else (eg newString += newinput.charAt(i).toUpperCase();) to see an effect.
You also need to use
for (var i = 0; i < il; i++) {
// ^
instead of
for (var i = 0; i > il; i++) {
// ^
else, no iterations will run at all.
function memify(input) { // function called memify()
var il = input.length; // gets the length of the input
let changedStr = '';
for (var i = 0; i < il; i++) {
var rng = Math.floor((Math.random() * 2)); // random number between 0 and 1. 0 = upper 1 = lower
if (rng === 0) {
changedStr += input.charAt(i).toUpperCase();
} else {
changedStr += input.charAt(i).toLowerCase();
}
}
return changedStr;
}
var text = prompt();
var textmeme = memify(text);
console.log(textmeme);
Another option, using .map, which looks much cleaner IMO:
const memify = input => [...input]
.map(char => Math.random() < 0.5 ? char.toUpperCase() : char.toLowerCase())
.join('');
console.log(memify(prompt()));
Or more concise, safer and generally better solution :). It does not require for loop, checking length of string and other error prone stuff.
function memify(input) {
var rng = () => Math.random() > 0.5;
var res = input.split('').map( letter =>
rng() ? letter.toUpperCase() : letter.toLowerCase()
).join('');
return res;
}
var textmeme = memify("Hello World");
console.log(textmeme);
Please up-vote if it was helpful :)

How to format number to currency?

I currently doing formatting of number to currency but is not working on a collection of an array. I used javascript to use the Math.round function. I would like to know how properly use this function. I appreciate your suggestion. Thank you.
Array:
{
"data": [
[
"9812355000",
"23397000",
"13976000"
]
]
}
for (var x = 0; x < data.data.length; x++) {
for (var i0 = 0; i0 < data.data[x].length; i0++) {
dynamicColumn += `<td>${data.data[x][i0] === null || data.data[x][i0] === ""
? 0
: Math.round(data.data[x][i0])}</td>`;
}
}
Need to achieve:
9,812,355,000
23,397,000
13,976,000
To achieve the output you specified using your array, you can iterate though the digits backwards (meaning, starting from the last number and moving to the first number) and then inserting a comma after 3 digits. Some sample code could look like this:
for(let i = numberString.length - 1; i >= 0; i--) {
if (i % 3 === 0)
array.insert(i, ','); // this is not a real function. I leave it up to you to implement this. first param is index and second is what to insert
}
var thousandSeparationRegexp = /\B(?=(\d{3})+(?!\d))/g;
// iterate through numbers
var numberString = number.toString();
var formatted = numberString.replace(thousandSeparationRegexp, ',');
Or inline:
var formatted = number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
You can use an Intl.NumberFormat().format(x):
function myFunction() {
var x = document.getElementById("value_unformated").value
var a = Intl.NumberFormat().format(x)
var text = "Currency format: " + a + "<br>";
document.getElementById("value_formated").innerHTML = text;
}
<input type="number" id="value_unformated" value="13528468">
<button onclick="myFunction()">Format</button>
<p id="value_formated"></p>

project euler #1 , hacker rank

i am trying to do project euler # 1 with Javascript in HackerRank. Can someone give me a hints in what's wrong with my code. the result is always zero.
I run my function in my google chrome console, then i input processData(10), it gives me 23. I input processData(100), it gives me 2318.
When i try to use my code in the console from Hacker rank, it output the result as zero, like it didn't pass the first test which is 0.
Did anyone tried to solve some problem in hackerrank in javascript?
function processData(input) {
var result = []
var total=0
function findMultipleThreeAndFive(n){
var i = 0;
for(i ; i < n ;i++){
if(i%3 == 0 || i%5 == 0){
result.push(i);
}
}
}
findMultipleThreeAndFive(input)
function sum(){
for(var j = 0; j< result.length ;j++){
total += result[j]
}
return total;
}
sum()
console.log(total)
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
First off all, your code works: http://jsfiddle.net/azggks5a/ , but I thought I would show you how I would solve it:
I suggest you use ES6 sets, because they handle the uniqueness of your values.
I began by iterating through the multiples I wanted. I then multiplied the iterated multiple by every number upto belowThis. If the result was lower than belowThis I added the result to the set, otherwise I didn't.
Here's the code:
var multiplesOf = [3,5];
var belowThis = 10;
var multiples = new Set();
var totalOfMultiples = 0;
multiplesOf.forEach(function(element, index){
for(var i=0;i<belowThis;i++) {
if(multiplesOf[index]*i<belowThis) {
multiples.add(multiplesOf[index]*i);
}
}
});
multiples.forEach(function(element, index){
totalOfMultiples+=element;
});
console.log(totalOfMultiples);
You can change the multiples you wish to check, and to solve the question you would increase belowThis to 1000, and get a result of 233168.

Find a number of characters/letters in a string in javascript

I want to find a number of "a" characters in a string. Ideally, I want to get an output as an array that would print out in the console something like: c - 15, b - 5, a - 4 etc.
<!DOCTYPE html>
<html>
<body>
<script>
function findStrings() {
mainString="Mazher Mahmood is a clever, canny and creative reporter who generates his own stories. It's important to place that on record because, before we delve into his use of the darker journalistic arts, there should not be any illusion about his reporting skills. "
result=(mainString.split("a").length - 1);
console.log(result);
}
</script>
</body>
</html>
You would just need to loop through each letter, making the check as you go and perhaps append it to an object:
function findStrings() {
var letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
ret = {};
for(i=0; i<letters.length; i++){
ret[letters[i]]=(mainString.split(letters[i]).length - 1);
}
console.log(ret);
}
findStrings();
Should you want to explicitly check for any other characters, just add them on to the end of the letters string.
JSFiddle
You can count like this:
mainString="Your Big String";
function count(str) {
var chars = {};
var astr = str.split("");
for (var i = 0, len = astr.length; i < len; i++) {
var letter = astr[i];
chars[letter] = chars.hasOwnProperty(letter) && chars[letter] + 1 || 1;
}
return chars;
}
console.log(count(mainString));
Note that, this way, you will count the occurrence of every character, including spaces, commas, etc.
Try this:
function getCharAppearences(str) {
var character,result = {};
for(var i = 0; i < str.length; i++) {
character = str.charAt(i);
result[character] = result[character] + 1 || 1;
}
return result;
}
Fiddle
If you only want to count the occurrences of letters/characters, you just have to loop through the string:
function findStrings() {
var mainString="Mazher Mahmood is a clever, canny and creative reporter who generates his own stories. It's important to place that on record because, before we delve into his use of the darker journalistic arts, there should not be any illusion about his reporting skills. "
var findings = {};
for(var i=0; i<mainString.length; i++){
if(typeof( findings[mainString[i]] ) == "undefined"){
findings[mainString[i]] = 0;
}
findings[mainString[i]]++;
}
for(var sym in findings){
console.log("The character "+sym+" has been found "+findings[sym]+" times");
}
}
findStrings();
Note:
oGeez`s answer only counts the occurrence of specific characters, while my answer counts the occurrence of all appearing characters. Your question isn't clear enough on what you actually want to achieve.
JSFiddle: http://jsfiddle.net/A4WWN/

How to sum up distinct value using javascript

I want to try and sum up distinct value from a list.. currently i am able to do so if theres only 2 similar record. If theres more than 2 i am not able to do the checking. Following is the javascript code:
function validateData(){
var total = document.frm.size.value;
var msg="";
var tbxA;
var tbxB;
var tbxA2;
var tbxB2;
var tbxC;
var totalValue =0;
var repeatedValue= 0;
var row = 0;
var row2 = 0;
for(var i=0; i<parseInt(total); i++){
tbxA = document.getElementById('tbx_A'+i).value;
tbxB = document.getElementById('tbx_B'+i).value-0;
tbxC = document.getElementById('tbx_C'+i).value;
for(var j=i+1; j<parseInt(total); j++){
tbxA2 = document.getElementById('tbx_A'+j).value;
tbxB2 = document.getElementById('tbx_B'+j).value-0;
if (tbxA==tbxA2) {
totalValue = tbxB + tbxB2;
}
if (totalValue != tbxC) {
repeatedValue= 1;
row = i;
row2 = j;
msg+="*total value does not add up at row " +(row2+1);
break;
}
}
if(repeatedValue== 1){
break;
}
}
return msg;
}
For example A:type of fruit, B: total of each fruit, C: how many bought at a time
total of C should be equal to B. i.e Apple: 3+3+4 = 10. So if the total is not equals to 10 it should prompt me an error.
A B C
Apple 10 3
Orange 10 10
Apple - 3
Apple - 4
My code above will prompt error bt it doesnt go beyond 2nd occurence of Apple.
So yes, how should i go about to ensure it loop through the whole list to sum up all similar values?
Thanks in advance for any possible help!
Try this:
var total = +document.frm.size.value,
data = {};
for(var i=0; i<total; ++i) {
var key = document.getElementById('tbx_A'+i).value;
data[key] = data[key] || {B:0, C:0};
data[key].B += +document.getElementById('tbx_B'+i).value || 0;
data[key].C += +document.getElementById('tbx_C'+i).value || 0;
}
for(var i in data) {
if(data.hasOwnProperty(i) && data[i].B != data[i].C) {
return "total value does not add up";
}
}
return "";
Some comments:
parseInt (and parseFloat) is very slow. + operator before string converts it to a number much faster. But if you really want to make sure the numbers are integers, use Math.floor(), Math.round(), Math.ceil() or the faster but illegible |0.
In case you really want parseInt (e.g. you want to convert '123foobar' into 123), always use a radix. For example: parseInt('123', 10)
Avoid doing calculations at the condition of a loop, because they run at each iteration. Just do the calculation once before the loop and save the result in a variable.

Categories