I'm trying to rearrange an input number using a function so that a single number is rearranged into descending order.
For example, 234892 would result in 984322.
This is what I have come up with.
function descendingOrder(n){
var num = '';
for(var i = 0; i <= n.length + 1; i++){ // iterates through the number
for(var j = 9; j >= 0; j--){ // starts at 9 and checks numbers descending
if (j == n[i]){
num.push(n[i]); // checks if j == n[i] and if so, pushes to num
}
i = 0; // sets i back to 0 to rescan the number again
}
}
return num;
}
You can convert number to string, split each character, sort it and join it again:
+(234892 + '').split('').sort((a, b) => a < b).join('');
var ordered = +(234892 + '').split('').sort((a, b) => a < b).join('');
document.getElementById('output').appendChild(document.createTextNode(ordered));
234892 → <span id="output"></span>
Detailed explanation:
var str = 234892 + ''; // convert to string
var parts = str.split(''); // convert to array of characters
// sort
parts.sort(function(a, b) {
return a < b;
});
var finalStr = parts.join(''); // join characters to string
var finalNumber = +finalStr; // convert back to number
console.log(finalNumber); // 984322
Related
Trying to return the highest 5 digit number out of any given number i.e 34858299999234
will return 99999
I think I have it narrowed down to the for loop not iterating the array properly OR the values for 'hold1' and 'hold2' are not updating.
function solution(digits){
//Convert string to array to iterate through
let arr = digits.split("");
let final = 0;
//iterate through the array in 5 sequence steps
for(let i = 0; i < arr.length-1; i++){
let hold1 = arr[i] + arr[i+1] + arr[i+2] + arr[i+3] + arr[i+4];
hold1 = parseInt(hold1,10); //converting string to int so if statement functions correctly
let hold2 = arr[i+1] + arr[i+2]+ arr[i+3] + arr[i+4] + arr[i+5];
hold2 = parseInt(hold2,10);
if(hold1 >= hold2){
final = hold1;
}else{
final = hold2;
}
return final;
}
}
if you need a five digits result you need to change the for loop in something like this:
for (let i = 0; i < arr.length - 5; i++) {
Otherwise you will generate results shorter than 5 digits.
Also, I think you are missing the Math.max method that will compare two numbers to return the bigger one.
I rewrote your function this way:
function solution(digits) {
let op = 0;
let length = 5;
let stringDigits = String(digits); /// <-- I use string instead of array
if (stringDigits.length <= length) {
return digits; /// <-- If input is shorter than 5 digits
}
for (let i = 0; i < stringDigits.length - length; i++) {
const fiveDigitsValue = stringDigits.substr(i, length);
op = Math.max(op, Number(fiveDigitsValue));
}
return op;
}
examples:
testing("xyzy**") should be true.
testing("xyzy*") should be false.
Reasoning:
In the first case, it is true because one * can behave as a x and the other a z, so all characteres would of the same amount of y.
In the second case there wouldn't be the same amount of characters repeating itself, cause there is only one *, so it is false.
Here is what I have up until now:
const testing = string => {
var array = []; //array with each character without repeating
var array_R = []; //array with the value the value that each character repeats itself
var array_C = 0; //counter for the size of "array"
//getting the character without repeating
for (var i = 0; i < string.length; i++) {
if (!array.includes(string.charAt(i))) {
array[array_C] = string.charAt(i);
array_R[array_C] = 0;
array_C++;
}
}
//how many each character repeats itself
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < string.length; j++) {
if(array[i] == string.charAt(j)){
array_R[i] = array_R[i] + 1;
}
}
}
}
I really don't know how I can proceed from here.
First count up the number of occurrences of each non-* character into an object or Map. Find the maximum value in that collection, then find the sum of all differences between the maximum value and each value. If the number of asterisks is the same as the sum of differences, the repeat conditions are fulfilled.
You'll also have to consider the case where there are more asterisks left over after all holes are filled in to make the values equal - figure out how many are left over, and see if that evenly divides the number of separate characters.
const testing = (str) => {
const grouped = {};
for (const char of str) {
if (char !== '*') grouped[char] = (grouped[char] || 0) + 1;
}
const values = Object.values(grouped);
const numOfSeparateChars = values.length;
const max = Math.max(...values);
const sum = values.reduce((a, b) => a + b, 0);
const sumOfDifferencesFromMax = max * numOfSeparateChars - sum;
const numberAsterisks = (str.match(/\*/g) || []).length;
const remainingAsterisks = sumOfDifferencesFromMax - numberAsterisks;
// Now all characters have been filled in to make the values even
// eg: 'abcc**' -> 'abccab'
// But there may be more asterisks
// eg: 'abcc*****' -> 'abccaabbc'
return remainingAsterisks % numOfSeparateChars === 0;
};
console.log(testing("xyzy**"));
console.log(testing("xyzy*"));
Im given the task of storing 10 elements in an Array, then I have to add all of those elements.
My problem comes at the time of storing each individual element in the array.
When I set the length of the for loop as numbers.length it fills the array with the first number that was inputted, and if I set the length to 10, it only places the value in the index[0] and leaves the others as undefined.
var numbers = new Array();
function addnew() {
var un = document.getElementById('userNumber').value;
for (var i = 0; i < 10; i++) {
numbers.push(" " + un[i]);
}
console.log(numbers);
document.getElementById('elements').innerHTML = numbers;
The output that is expected is a list that shows the values entered by the user inputs into the array (length of 10) and the sum of those values.
What it's actually showing is the first number inputted followed by undefined till it reaches the maximum length which is 10.
it's because un string length is 1 as it not saved completely
var numbers = new Array();
function addnew() {
var un = '123';
for (var i = 0; i < Math.min(10,un.length); i++) {
numbers.push(" " + un[i]);
}
console.log(numbers);
document.getElementById('elements').innerHTML = numbers;
}
}
If your user is entering a space inbetween each number, you can just split that one string into an array.
numbers = un.split(" ");
numbers now contains an array of strings.
Then convert the strings to numbers, so you can get the sum.
for (var i = 0; i < numbers.length; i++) {
numbers[i] = Number(numbers[i]);
}
And then this will give you the sum.
sumOfNumbers = numbers.reduce((a, b) => a + b, 0);
console.log(sumOfNumbers);
un = "1 2 3 12";
numbers = un.split(" ");
console.log(numbers);
for (var i = 0; i < numbers.length; i++) {
numbers[i] = Number(numbers[i]);
}
console.log(numbers);
sumOfNumbers = numbers.reduce((a, b) => a + b, 0);
console.log("sum is " + sumOfNumbers);
At beginning your numbers.length is 0. I think you should do un.length
function addnew() {
var numbers = [];
var un = document.getElementById('userNumber').value;
for (var i = 0; i < un.length; i++) {
numbers.push(" " + un[i]);
}
console.log(numbers);
document.getElementById('elements').innerHTML = numbers;
}
<input type="text" id="userNumber" onChange="addnew()"/>
<span id="elements"></span>
I am trying to display an output like this a3b2c4d3 for a string aaabbccccddd.
I tried the code below but didn't get the desired result.
var countLetters = "aaabbccccddd";
console.log("countLetters.length --->" + countLetters.length);
var countNumberLetter = 0;
var i;
var a;
for (i = 0; i < countLetters.length; i++) {
if (countLetters[i] == countLetters[i + 1]) {
countNumberLetter = countNumberLetter + 1;
}
}
console.log("countNumberLetter--------->" + countLetters[i] + countNumberLetter);
Use two loops. Use an outer while to loop the string. Whenever a new letter is encountered, use the for loop to increment count as the long as the letters belong to the same sequence. When done increment the outer counter (i) to get to the next letter:
var countLetters = "aaabbccccddd";
var result = '';
var i = 0;
while (i < countLetters.length) {
// iterate until current letter, and counted letter are not equal, increment count
for (var count = 1; countLetters[i] === countLetters[i + count]; count++) {}
// add current letter and count to string
result += countLetters[i] + count;
i += count; // increment outer counter - i
}
console.log(result);
Another solution that uses a String.match() with a regex to get an array of letter sequences. Then maps each sequence to letter + count, and joins them back to a string:
var countLetters = "aaabbccccddd";
var result = countLetters.match(/(\w)\1+/g) // match sequences of the same letter
.map((s) => s[0] + s.length) // map each sequence to letter with count
.join(''); // join back to a string
console.log(result);
var hashMap = {};
var countLetters = "aaabbccccddd";
countLetters.split("").forEach((letter) => {
if(!hashMap[letter]) {
hashMap[letter] = 0;
}
hashMap[letter] = hashMap[letter]+1;
})
var string ='';
for(var i in hashMap) {
var val = hashMap[i];
string += i + val;
}
console.log("countNumberLetter--------->",string);
const object = {};
const string = "aaabbccccddd";
// To iterate over string
for(let i = 0; i < string.length; i++){
// if the object has that alphabet just increment it
if(object.hasOwnProperty(string.charAt(i))){
++object[string.charAt(i)];
}else{
// else create a key to the new alphabet and give it a value 1
object[string.charAt(i)] = 1;
}
}
let finalString = "";
// To iterate over the object
for(let key in object){
finalString += key; // concatenate the key
finalString += object[key]; // concatenate the value
}
console.log(finalString);
My solution has two loops one to iterate over the string and store the alphabet and there count in an object ( you can use hashmap as well ).
The 2nd loop is to iterate over object so that we can make the desired string.
I have a function that returns the sum of all its digits For both POSITIVE and NEGATIVE numbers.
I used split method and converted it to string first and then used reduce to add them all. If the number is negative, the first digit should count as negative.
function sumDigits(num) {
var output = [],
sNum = num.toString();
for (var i = 0; i < sNum.length; i++) {
output.push(sNum[i]);
}
return output.reduce(function(total, item){
return Number(total) + Number(item);
});
}
var output = sumDigits(1148);
console.log(output); // --> MUST RETURN 14
var output2 = sumDigits(-316);
console.log(output2); // --> MUST RETURN 4
Instead of returning the sum, it returned 4592 -1264
Am I doing it right or do I need to use split function? Or is there any better way to do this?
Sorry newbie here.
I think you'll have to treat it as a string and check iterate over the string checking for a '-' and when you find one grab two characters and convert to an integer to push onto the array. Then loop over the array and sum them. Of course you could do that as you go and not bother pushing them on the array at all.
function sumDigits(num) {
num = num + '';
var output = [];
var tempNum;
var sum = 0;
for (var i = 0; i < num.length; i++) {
if (num[i] === '-') {
tempNum = num[i] + num[i + 1];
i++;
} else {
tempNum = num[i];
}
output.push(parseInt(tempNum, 10));
}
for (var j = 0; j < output.length; j++) {
sum = sum + output[j];
}
return sum;
}
var output = sumDigits(1148);
console.log(output); // --> MUST RETURN 14
var output2 = sumDigits(-316);
console.log(output2); // --> MUST RETURN 4