Using Modulus to loop through - javascript

I've been stuck on this last part of my assignment for the longest time. I'm trying to loop through the alphabet using modulus. delta is the number of letters you have to move forward or backwards to get the real letter. SO if given getchars("H",-2), the function is supposed to return F. A problem arises however if the chars.charAt(chars.getIndexOf(data.charAt(i))) ever equals a number less than 0. I want to be able to give my function ("A", -1) or any negative number and have it return "Z".
This is an assignment for class so if possible please keep it to just modulus. I've been working on this last part for like 2 hours now.
function getChars(data,delta)
{
var chars;
var i;
var foundAt;
var newString;
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
data = data.toUpperCase();
delta = Math.min(chars.length, delta);
i = 0;
newString = "";
while (i < data.length)
{
if(delta <= 0)
{
foundAt = (chars.indexOf(data.charAt(i)) + delta) ;window.alert(foundAt)
//newString = newString + chars.charAt(foundAt);
//i = i + 1;
}
else if((chars.indexOf(data.charAt(i)) < 0))
{
foundAt = data.charAt(i);
newString = newString + foundAt;
i = i + 1;
}
else
{
foundAt = ((chars.indexOf(data.charAt(0 + i)) + delta)) % chars.length;window.alert(foundAt);
newString = newString + chars.charAt(foundAt);window.alert(newString);
i = i + 1;
}
}
//return newString;
}

To be flexible, you can use i = chars.length - 1; and first after that do the found at.

You have to use you own modulus function :
function modulus(n,m) {
return ((n%m)+m)%m;
};
With your following code :
function getChars(data,delta)
{
var chars;
var i;
var foundAt;
var newString;
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
data = data.toUpperCase();
i = 0;
newString = "";
while (i < data.length)
{
newString += chars.charAt(modulus(chars.indexOf(data[i])+delta,26))
i++;
}
return newString;
}

Related

How do you iterate over an array every x spots and replace with letter?

/Write a function called weave that accepts an input string and number. The function should return the string with every xth character replaced with an 'x'./
function weave(word,numSkip) {
let myString = word.split("");
numSkip -= 1;
for(let i = 0; i < myString.length; i++)
{
numSkip += numSkip;
myString[numSkip] = "x";
}
let newString = myString.join();
console.log(newString);
}
weave("weave",2);
I keep getting an infinite loop. I believe the answer I am looking for is "wxaxe".
Here's another solution, incrementing the for loop by the numToSkip parameter.
function weave(word, numToSkip) {
let letters = word.split("");
for (let i=numToSkip - 1; i < letters.length; i = i + numToSkip) {
letters[i] = "x"
}
return letters.join("");
}
Well you need to test each loop to check if it's a skip or not. Something as simple as the following will do:
function weave(word,numSkip) {
var arr = word.split("");
for(var i = 0; i < arr.length; i++)
{
if((i+1) % numSkip == 0) {
arr[i] = "x";
}
}
return arr.join("");
}
Here is a working example
Alternatively, you could use the map function:
function weave(word, numSkip) {
var arr = word.split("");
arr = arr.map(function(letter, index) {
return (index + 1) % numSkip ? letter : 'x';
});
return arr.join("");
}
Here is a working example
Here is a more re-usable function that allows specifying the character used for substitution:
function weave(input, skip, substitute) {
return input.split("").map(function(letter, index) {
return (index + 1) % skip ? letter : substitute;
}).join("");
}
Called like:
var result = weave('weave', 2, 'x');
Here is a working example
You dont need an array, string concatenation will do it, as well as the modulo operator:
function weave(str,x){
var result = "";
for(var i = 0; i < str.length; i++){
result += (i && (i+1)%x === 0)?"x":str[i];
}
return result;
}
With arrays:
const weave = (str,x) => str.split("").map((c,i)=>(i&&!((i+1)%x))?"x":c).join("");
You're getting your word greater in your loop every time, so your loop is infinite.
Try something like this :
for(let k = 1; k <= myString.length; k++)
{
if(k % numSkip == 0){
myString[k-1]='x';
}
}
Looking at what you have, I believe the reason you are getting an error is because the way you update numSkip, it eventually becomes larger than
myString.length. In my code snippet, I make i increment by numSkip which prevents the loop from ever executing when i is greater than myString.length. Please feel free to ask questions, and I will do my best to clarify!
JSFiddle of my solution (view the developer console to see the output.
function weave(word,numSkip) {
let myString = word.split("");
for(let i = numSkip - 1; i < myString.length; i += numSkip)
{
myString[i] = "x";
}
let newString = myString.join();
console.log(newString);
}
weave("weave",2);
Strings are immutable, you need a new string for the result and concat the actual character or the replacement.
function weave(word, numSkip) {
var i, result = '';
for (i = 0; i < word.length; i++) {
result += (i + 1) % numSkip ? word[i] : 'x';
}
return result;
}
console.log(weave("weave", 2));
console.log(weave("abcd efgh ijkl m", 5));
You can do this with fewer lines of code:
function weave(word, numSkip) {
word = word.split("");
for (i = 0; i < word.length; i++) {
word[i] = ((i + 1) % numSkip == 0) ? "x" : word[i];
}
return word.join("");
}
var result = weave("weave", 2);
console.log(result);

Identify palindromes in a sentence

A lot of solutions I found here are giving true or false after checking if a string is a palindrome. I have a function that checks if a string is a palindrome or not:
function palindrome(myString){
/* remove special characters, spaces and make lowercase*/
var removeChar = myString.replace(/[^A-Z0-9]/ig, "").toLowerCase();
/* reverse removeChar for comparison*/
var checkPalindrome = removeChar.split('').reverse().join('');
/* Check to see if myString is a Palindrome*/
if(removeChar === checkPalindrome){
document.write("<div>"+ myString + " is a Palindrome <div>");
}else{
document.write("<div>" + myString + " is not a Palindrome </div>");
}
}
palindrome("Oh who was it I saw, oh who?")
palindrome("Madam")
palindrome("Star Wars")
But this is not quite what I want. It's just checking if the string is a palindrome or not. I want to update the function so that it identifies all of the palindromes in a sentence instead of giving it true or false. So if there's a sentence like this - "Madam and John went out at noon" It will list the palindromes in that sentence - "Madam, noon"
Any help in this would be appreciated!
function findPalindromes(str, min) {
min = min || 3;
var result = [];
var reg = str.toLowerCase();
var reg = reg.replace(/[^a-z]/g, ''); // remove if you want spaces
var rev = reg.split("").reverse().join("");
var l = reg.length;
for (var i = 0; i < l; i++) {
for (var j = i + min; j <= l; j++) {
var regs = reg.substring(i, j);
var revs = rev.substring(l - j, l - i);
if (regs == revs) {
result.push(regs);
}
}
}
return result;
}
var str1 = "Madam and John went out at noon";
console.log(str1, findPalindromes(str1));
var str2 = "\"Amore, Roma\" and \"There's no 'x' in Nixon\" are palindromes.";
console.log(str2, findPalindromes(str2));
function findPalindromes(sentence) {
const words = sentence.replace(/[^\w\s]/gi, '').split(' ');
const palindromes = words.filter(isPalindrome);
return palindromes;
}
function isPalindrome(word) {
if (word.length <= 0) return false;
word = word.toLowerCase();
for (let i = 0; i < word.length / 2; i++) {
if (word[i] !== word[word.length - 1 - i]) return false;
}
return true;
}
https://jsfiddle.net/ewezbz22/1/

how to increment the value of a char in Javascript

How do I increment a string "A" to get "B" in Javascript?
function incrementChar(c)
{
}
You could try
var yourChar = 'A'
var newChar = String.fromCharCode(yourChar.charCodeAt(0) + 1) // 'B'
So, in a function:
function incrementChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1)
}
Note that this goes in ASCII order, for example 'Z' -> '['. If you want Z to go back to A, try something slightly more complicated:
var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
function incrementChar(c) {
var index = alphabet.indexOf(c)
if (index == -1) return -1 // or whatever error value you want
return alphabet[index + 1 % alphabet.length]
}
var incrementString = function(string, count){
var newString = [];
for(var i = 0; i < string.length; i++){
newString[i] = String.fromCharCode(string[i].charCodeAt() + count);
}
newString = newString.join('');
console.log(newString);
return newString;
}
this function also can help you if you have a loop to go through

Insert dashes into a number

Any ideas on the following? I want to input a number into a function and insert dashes "-" between the odd digits. So 4567897 would become "456789-7". What I have so far is to convert the number into a string and then an array, then look for two odd numbers in a row and use the .splice() method to add the dashes where appropriate. It does not work and I figure I may not be on the right track anyway, and that there has to be a simpler solution.
function DashInsert(num) {
var numArr = num.toString().split('');
for (var i = 0; i < numArr.length; i++){
if (numArr[i]%2 != 0){
if (numArr[i+1]%2 != 0) {
numArr.splice(i, 0, "-");
}
}
}
return numArr;
}
The problem is you're changing the thing you're iterating over. If instead you maintain a separate output and input...
function insertDashes(num) {
var inStr = String(num);
var outStr = inStr[0], ii;
for (ii = 1; ii < inStr.length; ii++) {
if (inStr[ii-1] % 2 !== 0 && inStr[ii] % 2 !== 0) {
outStr += '-';
}
outStr += inStr[ii];
}
return outStr;
}
You can try using regular expressions
'4567897'.replace(/([13579])(?=[13579])/g, '$1-')
Regex Explained
So, we find an odd number (([13579]) is a capturing group meaning we can use it as a reference in the replacement $1) ensure that it is followed by another odd number in the non-capturing positive lookahead ((?=[13579])) and replace the matched odd number adding the - prefix
Here is the function to do it:
function dashes(number){
var numString = '';
var numArr = number.toString().split('');
console.log(numArr);
for(i = 0; i < numArr.length; i++){
if(numArr[i] % 2 === 1 && numArr[i+1] % 2 === 1){
numString += numArr[i] + '-';
}else{
numString += numArr[i];
}
}
console.log(numString);
}
dashes(456379);
Tested and everything.
Edit: OrangeDog's answer was posted earlier (by nearly a full half hour), I just wanted to make an answer which uses your code since you're almost there.
Using another array instead of splicing into one you were looping through (this happens to return a string using join):
var num = 4567897;
function DashInsert(num) {
var numArr = num.toString().split('');
var len = numArr.length;
var final = [];
for (var i = 0; i < len; i++){
final.push(numArr[i]);
if (numArr[i]%2 != 0){
if (i+1 < len && numArr[i+1]%2 != 0) {
final.push("-")
}
}
}
return final.join("");
}
alert(DashInsert(num));
function dashInsert(str) {
var arrayNumbers = str.split("");
var newString = "";
for (var i = 0; i < arrayNumbers.length; i++){
if(arrayNumbers[i] % 2 === 1 && arrayNumbers[i + 1] % 2 === 1){
newString = newString + arrayNumbers[i] + "-";
} else {
newString = newString + arrayNumbers[i];
}
}
return newString;
}
var result = dashInsert("3453246");
console.log(result);

formatMoney function in Javascript doesn't work

I need a function which can transform the number 10000 to this number: 10.000.
So I tried the following:
function formatMoney(money){
var value = money.toString();
var l = value.length;
var new_value = 0;
new_value = new_value.toString();
if(l > 3){
var moneyarray = value.split('');
var u = 0;
for(i = l;i >= 0;i--){
if(u > 3){
u = 0;
new_value = "."+new_value;
}
new_value = moneyarray[i]+new_value;
u++;
}
}
return new_value;
}
And then call this:
formatMoney("10000");
But the result is
10.000undefined0"
What did I do wrong?
You're assigning the index counter to the length of the string;
var l = value.length;
...
for(i = l;i >= 0;i--){
And the down count starts with the length-index, which isn't present since arrays are zero-based. Subtract beforehand instead;
for(i = l;i >= 0;--i){
EDIT: Disregard this, I wasn't paying enough attention to the question.
If all you're looking to do is take numbers that are 4 digits or greater and put a dot in three digits from the right, you could give this a shot:
function formatMoney(money) {
var moneyString = money.toString();
var moneyLength = moneyString.length;
if(moneyLength < 4) {
return 0;
}
var dotIndex = moneyLength - 3;
return moneyString.substr(0, dotIndex) + "." + moneyString.substr(dotIndex);
}
Also, formatting your code in the post is good stuff. Indent it all by four spaces.
function formatMoney(money){
var value = money.toString();
var l = value.length;
var new_value = 0;
new_value = new_value.toString();
if(l > 3){
var moneyarray = value.split('');
for(var i = l-1;i >= 0;i--){
if((l-i)%3 === 0){
new_value = "."+new_value;
}
new_value = moneyarray[i]+new_value;
}
} else {
new_value = value;
}
return new_value;
}
A couple of things:
You were counting down with the wrong index (you were starting at l, instead of l-1)
You were not handling any value less than 1000
You don't need to use a counter variable u, you can just use modulo math to keep track of threes.
I cut off some parts:
function formatMoney(money) {
var value = money.toString();
var l = value.length;
var new_value = "";
if (l > 3) {
var u = 0;
for (i = l-1;i >= 0;i--) {
if (u == 3) {
u = 0;
new_value = "." + new_value;
}
new_value = value[i]+new_value;
u++;
}
}
return new_value;
}
You could do it like this:
function money(m) {
m = m.toString().split('');
for (var i = m.length - 3; i > 0; i -= 3)
m.splice(i,0,".");
return m.join('');
}
console.log(money(1000000)); // "1.000.000
See this JsBin

Categories

Resources