Array Remove last 2 digits of a number - javascript

I would like to create a program that takes a number is input, such as: 12345 and then splits this number into 2 digit numbers and store it in a array. The array must look like this: [0]=45 [1]=23 [2]=1 . This means that the splitting of the numbers must start from the last digit of the number and not the first.
This is what I have until now:
var splitCount = []; // This is the array in which we store our split numbers
//Getting api results via jQuery's GET request
$.get("https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCJwchuXd_UWNxW-Z1Cg-liw&key=AIzaSyDUzfsMaYjn7dnGXy9ZEtQB_CuHyii4poc", function(result) {
//result is our api answer and contains the recieved data
//now we put the subscriber count into another variable (count); this is just for clarity
count = result.items[0].statistics.subscriberCount;
//While the subscriber count still has characters
while (count.length) {
splitCount.push(count.substr(0, 2)); //Push first two characters into the splitCount array from line 1
count = count.substr(2); //Remove first two characters from the count string
}
console.log(splitCount) //Output our splitCount array
});
but the problem with this is that if there are 5 digits for example: 12345 the the last digit will be in an array by itself like this: [0]=12 [1]=34 [2]=5 but I need the last array to have 2 digits and the first should be the one with one digit instead like this: [0]=1 [1]=23 [2]=45

very crude but this should work assuming the string is always numbers:
input = "12345"
def chop_it_up(input)
o = []
while input.length > 0
if input.length <= 2
o << input
else
o << input[-2..input.length]
end
input = input[0..-3]
chop_it_up(input)
end
return o
end

I probably do sth like this :
int[] fun(int x){
int xtmp = x;
int i = 0;
int len = String.valueOf(x).length();
// this is a function for java, but you can probably find
//an equivalent in whatever language you use
int tab[(len+1)/2];
while(xtmp > 1){
tab[i] = xtmp%100;
xtmp = int(xtmp/100); // here you take the integer part of your xtmp
++i;
}
return tab;
}

Related

Extracting certain substring from a string

I want to extract the last part of this string : "https://steamcommunity.com/profiles/76561198364464404".Just the numbers after '/profiles'.But the problem is the URL can change sometimes.
There are two types of url
1.First one is "https://steamcommunity.com/profiles/76561198364464404" with "/profiles" and then the "id"(id is the numbers after '/profiles').
2."https://steamcommunity.com/id/purotexnuk".Second is this type.Where "/profiles" doesn't exist.
I have come up this code :
let inc;
const index = 27;
const string = 'https://steamcommunity.com/id/purotexnuk';
if (string.includes('profiles')) {
inc = 9;
} else {
inc = 3;
}
console.log(string.slice(index + inc, -1));
The above code checks wheather the string "/profiles" is present.If the string contains "/profiles".inc will be 9.So that slice starts from the right side of the string(url) and ends at the first '/' from the right.inc is 9 becuase "profiles/" length is 9.Similar way if the string(url) contains "id".The slice will start from the end and stop at the first '/' from the right.inc will be 3 becuase "id/" length is 3.
The index is always constant because ,"/profiles" or "/id" only occurs after "https://steamcommunity.com" whose length is 27.Is there any better way i can extract only the profile id or profile name?
(profile id - 76561198364464404)
(profile name - purotexnuk )
You can use regex for this, it will also take care if your url ends with / or has query parameters example https://steamcommunity.com/id/purotexnuk?ref=abc
/.*(?:profiles|id)\/([a-z0-9]+)[\/?]?/i
example:
const regex = /.*(?:profiles|id)\/([a-z0-9]+)[\/?]?/i;
const matches = regex.exec('https://steamcommunity.com/id/purotexnuk');
console.log(matches[1]);
You can split the string with delimiter / and return the last value value from the array;
function getNum(str) {
const arr = str.split('/');
if (!isNaN(arr[arr.length - 1])) {
return arr[arr.length - 1];
}
return ' no number ';
}
const st1 = "https://steamcommunity.com/profiles/76561198364464404";
const st2 = "https://steamcommunity.com/profiles/76561198364464404";
const st3 = "https://steamcommunity.com/id/purotexnuk";
console.log(getNum(st1));
console.log(getNum(st2));
console.log(getNum(st3));
Or do it in one line:
const string = 'https://steamcommunity.com/id/purotexnuk';
console.log(string.slice(string.lastIndexOf("/") + 1, string.length));

Looping over an array of strings with an arbitrary time between each loop (JS)

I want to create an animation of strings being looped over and over again one character at a time. I have two arrays in my string:
let stringArray = ['TestOne', 'TestTwo'];
I want to loop over said array repeatedly (string one -> string two -> back to string one -> string two -> ... continuously). I want to print the characters of string one one character at a time. After print all its characters, I will clear the printed string and proceed with the character of string two. Illustration:
T
Te (250 ms after the first char)
Tes (250 ms after the second char)
Test (All characters are printed 250ms after the previous char)
TestO
TestOn
TestOne
T
Te
Tes
Test
TestT
TestTw
TestTwo
... (continue with TestOne again)
The problem is, I want each character to be printed only 250ms after a previously printed character. How can I achieve this?
You could take an array with the indices and an interval for the display.
The array indices contaisn two values at start, [0, 0] which means the first item of stringArray and from this string the first character.
For every loopm, the caracter index gets an increment and this value is checked against the lenght of the string. If greater, then the index of the string gets an increment and the string index is resetted to zero.
To prevent the string index is greater than the actual count of strings, the value is resetted by taking a remainder assignment.
The pattern
(indices => () => {
// ...
})([0, 0])
is an IIFE (immediately-invoked function expression), which takes the array as value for the first parameter. It is a closure over the array and allows to use the resturnd function as callback for the interval.
Tha advantage is to have a data set which is not changable from the outside and is avilable for any call of the callback.
let stringArray = ['TestOne', 'TestTwo'];
setInterval((indices => () => {
document.getElementById('out').innerHTML = stringArray[indices[0]].slice(0, indices[1]);
indices[1]++;
if (indices[1] > stringArray[indices[0]].length) {
indices[0]++;
indices[1] = 0;
}
indices[0] %= stringArray.length;
})([0, 0]), 250)
<pre id="out"></pre>
Well, as long as people are posting solutions, I'll post the obvious, simple one, see comments:
{ // A scoping block so the variables aren't globals
// (unnecessary if you're using modules)
let stringArray = ['TestOne', 'TestTwo'];
let arrayIndex = 0;
let stringIndex = 1;
// Start a timer that will call the callback every 250ms (or so)
setInterval(() => {
// Get the relevant string
const str = stringArray[arrayIndex];
// Output the substring
console.log(str.substring(0, stringIndex));
// Move to the next character
++stringIndex;
// Need to move to next string?
if (stringIndex > str.length) {
// Yes, go back to the beginning of the string and
// move to the next entry in the array, wrapping
// around if we reach the end
stringIndex = 1;
arrayIndex = (arrayIndex + 1) % stringArray.length;
}
}, 250);
}
This part:
arrayIndex = (arrayIndex + 1) % stringArray.length;
is a handy trick for when you have an index (0...n-1) and want to increment it and loop around. Say you have 3 entries, so the indexes are 0, 1, and 2. When you're at 2, (2 + 1) is 3 and 3 % 3 is 0, so it wraps around.
One way you could do this is without using a loop, but instead using a function which takes some parameters so you know how far or long you are in a word, and which word you are currently printing in your array.
Once you are printing with a function, simply add a setTimeout() in the function and then you can control the delay. See https://www.w3schools.com/jsref/met_win_settimeout.asp for more info on timeouts in javascript.
strings = [];
for (var i = 1; i <= "TestOne".length; i++)
strings.push ("TestOne".substring (0, i));
for (var i = 1; i <= "TestTwo".length; i++)
strings.push ("TestTwo".substring (0, i));
var position = 0;
setInterval (() => {
console.log (strings [position++]);
if (position == strings.length) position = 0;
}, 250);

Function behaves strangely after first onclick

I have the following HTML:
<input type = "text" id = "pick"> <input type = "submit" value = "Submit" onclick = "guessWord()">
That runs my js function which works fine (with unrelated hiccups) on the first call. But if I change my text and submit it again without reloading my initial if/else statement behaves incorrectly. Specifically, the if/else is supposed to check if the user inputted word is in an array. It works properly on the first call, but after that it jumps to the else block even when it shouldn't.
Here is the js (apologies in advance for including the whole function, I'm just usually asked to include more code than I initially do):
function guessWord() {
var comWords, match, compWord = "";
var possWords = dictFive;
var firstFive = ["vibex", "fjord", "nymph", "waltz", "gucks"]; // note: right now choosing any of these words results in unexpected behavior -- either it doesn't accept them or it freezes.
var inputWord = document.getElementById("pick").value.toLowerCase().replace(/\s+/g, '');
if (possWords.includes(inputWord)) { // checks to see if the user inputted word is in our dictionary.i f not, requests a different word.
// start game loop:
// in order to try and get as much information as possible in the first few turns I start by guessing the five words in firstFive[]: vibex, fjord, nymph, waltz, gucks. together, these words give us information about 25 letters.
for (let d = 0; d < inputWord.length; d++) { // this loop will run for the length of the inputted word, making it scaleable so in the future the program could accept shorter or longer words. within the current scope it will always be 5.
compWord = firstFive[d]; // the computers word will loop through each word in firstFive[].
if (inputWord === compWord) { // if the word matches the user inputted word:
document.getElementById("otpt").innerHTML = "Your word was: " + firstFive[d] + ". I guessed it in " + (d + 1) + " turns.";
return;
} else { // if the word is not the user inputted word, then:
comWords = (inputWord + compWord).split('').sort().join(''); // we combine the users word with the comps word and sort them by character.
match = comWords.length - comWords.replace(/(\w)\1+/g, '$1').length; // match produces a numerical value for how many letters matched between both words.
for (let e = 0; e < possWords.length; e++) { // loop to cycle through our dictionary.
for (let f = 0; f < inputWord.length; f++) { // loop to cycle through all the different match options.
if (match === 0) { // if there are no matches we can:
if (possWords[e].includes(firstFive[f])) { // go through the dict and get rid of every word that has letters in common with the word.
possWords.splice(e, 1);
}
} else if (match === f) { // if there's at least one letter in common:
comWords = (possWords[e] + compWord).split('').sort().join(''); // as we cycle through the dict, pick each available word, combine and sort with the chosen word,
var matchFive = comWords.length - comWords.replace(/(\w)\1+/g, '$1').length; // and then find how many letters match.
if (matchFive != match) { // any words in dict that have a different match value can be deleted.
possWords.splice(e, 1);
}
}
}
}
}
}
// once we've worked through the words in firstFive[] we start guessing randomly.
for (let a = 0; a < possWords.length; a++) { // the loop max is set to the length of the array because that's the maximum amount of time the guessing can take.
compWord = possWords[Math.floor(Math.random() * possWords.length)]; // choose a random word.
if (compWord === inputWord) { // check if the random word is the inputted word. if it is:
document.getElementById("otpt").innerHTML = "Your word was: " + compWord + ". I guessed it in " + (a + 5) + " turns. I had " + possWords.length + " remaining words that were possible matches.";
return;
} else { // while the word still isn't correct:
comWords = (compWord + inputWord).split('').sort().join(''); // again, we join and sort it.
match = comWords.length - comWords.replace(/(\w)\1+/g, '$1'); // find its match value.
for (let c = 0; c < inputWord.length; c++) { // loop through inputted word's length to check all letters.
if (match === 0) { // again, no matches we can safely delete all words with those letters.
if (possWords.includes(compWord[c])) {
possWords.splice(c, 1);
}
} else if (match === c) { // if match is higher than 0:
for (let g = 0; g < possWords.length; g++) {
comWords = (possWords[g]+ compWord).split('').sort().join('');
matchAll = comWords.length - comWords.replace(/(\w)\1+/g, '$1');
if (match != matchAll) {
possWords.splice(g, 1);
}
}
}
}
}
}
} else { // If the user inputted word was not in our dictionary, requests a different word:
document.getElementById("otpt").innerHTML = "Please choose a different word.";
}
}
(For context, dictFive is an array located on a separate file.) The code is trying to guess the user inputted word by checking how many letters match and then splicing out words from the master array if they can't match, so the array possWords starts with about 2500 words and gets narrowed down to a few hundred by the end of the function. As far as I can tell, the function should be resetting the vars properly every time it's called, though, but I'm guessing it isn't for some reason?
Your dictFive array is being spliced each time the function is called.
When you set possWords = dictFive, and then splice possWords later, you're also splicing dictFive because both variables refer to the same array. Then, the second time the function is run, dictFive is still in its spliced state. Instead of setting possWords = dictFive, try making a copy of the array. That way, you'll splice the copy without affecting the original, dictFive. You can clone an array by possWords = dictFive.slice().
var dictFive = [0,1,2,3,4]; // Just an example of whatever dictFive might be
var possWords = dictFive; // This makes possWords refer to the same thing as dictFive
possWords.splice(0, 1); // Splicing the array at whatever point
possWords // [1,2,3,4] because the 0th element was spliced out
dictFive // also [1,2,3,4] because both dictFive and possWords are the same array
compare that to
var dictFive = [0,1,2,3,4];
var possWords = dictFive.slice(); // This makes a copy of the array instead of referencing the original dictFive
possWords.splice(0, 1);
possWords // [1,2,3,4];
dictFive // Now, this array is still [0,1,2,3,4] because only the possWords array was spliced. dictFive wasn't affected.

What am I missing doing bitwise operations in javascript?

Trying to bitwise OR a group of values and wrote a some test code that doesn't return what I would expect ( old C programmer ). My test code:
// take 3 values from string ( 1,2,3 ) and OR them together
var values="012345678"; // sample characters
var val=0; // int to place single ascii value
var bin=0; // binary value after offset
var total=0; // cumulative total
var pos=1; //where to start pulling characters
// take 3 values from string ( 1,2,3 ) and OR them together
for(let i=0;i<3;i++){
var singleVal=values[pos++];
val=Number(singleVal.charCodeAt(0));
bin=val-48; // position offset by ascii "0" = 48
total|=bin;
}
// Result should be 7 but always returns the last singleVal
console.log("total: "+total);
Result should be 7 but always returns the last singleVal
with bitwise or the result of 1|2|3 is 3, not 7 (01|10|11 = 11).
If you loop until 7 then the result would be 7:
for(let i=0;i<7;i++){

trying to understand this function pattern

So im trying to write a function pattern which creates the following pattern upto n number of rows. If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string.
123456
23456
3456
456
56
6
I am trying to understand the solution of this question as below:
function pattern(n){
var output="";
for(i=1;i<n+1;i++){
for(j=i;j<n+1;j++){ //what is the purpose of this j loop?
output += j;
}
if(i!=n) output +="\n"; //I know \n can jump to next line, but what does this if statement mean? why I!=n?
}
return output;
}
// function definition
function pattern(n){
// declare a variable to collect the lines
var output="";
// there are n lines
for(i=1;i<n+1;i++){
// each line starts with the linenumber and ends with n
// so take a loop from i to n
for(j=i;j<n+1;j++){
// collect the numbers of each line as a string in the declared variable
output += j;
}
// if i!=n means: not the last line
if(i!=n) output +="\n";
}
// return the result of this function
return output;
}
UPDATE
But please let me point out, that the given solution is not very smart. Take a look at the following code:
Array.range = function(start, end) {
return Array.apply(null, Array(end+1)).map(function (_, i) {return i;}).slice(start);
}
function pattern(n){
var startValues = Array.range(1,n);
return startValues.map(function(i) { return Array.range(i,n); }).join('\n');
}
http://jsfiddle.net/afmchdwp/
First we define the static Method Array.range which helps us to define number ranges in javascript.
The pattern function can now use this ranges to create the numbers you need.
The first line of the function create a range from 1..n (the startnumbers of the lines).
The second line walks throu this array and transform every value 1..n into a range from the linenumber to n. With .join(), you can combine the characters of each line and combine the lines itself.
UPDATE 2
Here a updated fiddle without comma separated numbers (using join inside the closure): http://jsfiddle.net/afmchdwp/1/

Categories

Resources