Skip to content

Instantly share code, notes, and snippets.

@nyarlatotep
Last active May 28, 2022 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nyarlatotep/68252004b95054c2605dc72b5bd46247 to your computer and use it in GitHub Desktop.
Save nyarlatotep/68252004b95054c2605dc72b5bd46247 to your computer and use it in GitHub Desktop.
Some tips and steps to solve basic problems with "JavaScript"

Solving foundations in JavaScript 📃


📌 A small introduction...

In life, every profession, job, trade, knowledge, etc., requires understanding and knowledge of their foundations, to master and perfect their creation, use and maintenance; to thereby become capable of creating ever more complex and reliable things. In this way, programming 💻 is not the exception and, probably, that statement is, rather, the starting point and the most crucial of this journey.

Speaking more specifically and, regardless of the language of your taste, in Javascript, some of its fundamentals, probably, are algorithms, loops, conditionals, etc. Given this small introduction, I will go to the point and leave here some ways to solve certain operations or situations (these can be random, specific or circumstantial) in particular...

I'll add more different examples and ways to cover most situations, as I can

📣 Feel free to correct me if you find any errors or just want to share your feedback. I would appreciate 👍


⚠️ Note: ⚠️

These examples use the syntax of EcmaScript 6 and newer versions

Problem 1:

Segmenting a string 🔀

Suppose a situation where you need to split a string "S" and the result must be the same string segmented into "N" number of segments which contain "M" number of characters given a variable "V" ( string => S / V = (N * V:(M * V)) ):

var myString = "aaabbbcccdddeeefffggghhhiiijj";
var myNumber = 3; 

let length = myString.length, array = [];
var halfLength = (length / myNumber);

for ( let i = 0; i < length; i++ ) {
  arr.push( myString.charAt( i );
}

for ( let i = 0; i < halfLength; i++ ) {
  const t = ( myNumber * i );
  result = arr.slice( t, ( myNumber + t ) ).join( '' );
  array.push( result );
}


console.log( `"${ array.join( ' ' ).trim() }"` );

Problem 2

Find the most frequent number and its frequency

Let's suppose that a situation arises, in which the code you are working on contains an array of values of type number (or integers) and among these, there are some that are repeated and the order is random. What you need from the previous situation is to know what number is the most frequent and what is its frequency?

function mostFrequent ( arr, n ) {
	arr.sort();

	let max_count = 1, result = arr[ 0 ];
	let count = 1;
	for ( let i = 0; i < n; i++ ) {
		if ( arr[ i ] == arr[ i - 1 ] )
			count++;
		else
			count = 1;
		
		if ( count > max_count ) {
			max_count = count;
			result = arr[ i - 1 ];
		}
	}
	return result;
}

var arr = [ 1, 2, 2, 2, 5, 4, 6, 3, 2, 2, 4, 5, 6, 7, 8, 8, 8 ];
var n = arr.length;
var count = 0;
var freq = mostFrequent( arr, n );

for ( var i = 0; i < n; i++ ) {
	if ( arr[ i ] === freq )
		count++;
}

console.log( `
Number: ${ mostFrequent( arr, n ) }` +  
`Frequency: ${ count }`		         
);				        

Conclusion

In conclusion, this are only some ways to solve these problems; there are many other ways to do it, so use the method that is best for you and don't complicate yourself, just enjoy what you do. 😄

/*
Problem 2
Find the most frequent number and its frequency
Let's suppose that a situation arises, in which the code you are working on contains an array of values of type number (or integers) and among these, there are some that are repeated and the order is random.
What you need from the previous situation is to know what number is the most frequent and what is its frequency?
*/
// The function that give us the most frequent number. Also it's possible to get them without a function
function mostFrequent ( arr, n ) {
// First sort the values into the array, the index is the heart of this method
// It is the initial and most IMPORTANT step, since this will allow the comparison of the values and to obtain the necessary value.
arr.sort();
// Declare the necessary variables to work;
let max_count = 1, result = arr[ 0 ];
let count = 1;
// Inside this loop, the statement will be the one that executes the comparision task
for ( let i = 0; i < n; i++ ) {
// If the element in context is equal to the previous one, "count" adds one; otherwise, it returns to one
if ( arr[ i ] == arr[ i - 1 ] )
count++;
else
count = 1;
// now, if count is greater than "max_count" ( 1 ), then max_count becomes count, otherwise the loop continues or breaks,
// depending on how many iterations are left to finish..
/*
In other words, the comparison of the elements inside the loop, previously ordered, will allow "count" to add one and,
be greater than "max_count" , which at the same time increments the value of "max_count" indirectly
and allows to filter the current index to return the element that was repeated and
therefore increment one plus the value of "count"
*/
if ( count > max_count ) {
max_count = count;
result = arr[ i - 1 ];
}
}
return result;
}
// Finally the array in question and the variables to be passed to the function
var arr = [ 1, 2, 2, 2, 5, 4, 6, 3, 2, 2, 4, 5, 6, 7, 8, 8, 8 ];
var n = arr.length;
var count = 0;
var freq = mostFrequent( arr, n );
// in this additional step, it will be find the frequency of the number.
// It's simple, if the value that is in the current round of the loop is the same as the most frequent number,
// this adds one more to "current" (which starts at 1) as many times as it repeats, thus giving its frequency.
for ( var i = 0; i < n; i++ ) {
if ( arr[ i ] === freq )
count++;
}
console.log( `
Number: ${ mostFrequent( arr, n ) }` + // This expects:
`Frequency: ${ count }` // "Number: 2
); // Frequency: 5"
/*
Problem 1:
Segmenting a string:
Suppose a situation where you need to split a string ***"S"*** and the result must be the same string segmented into ***"N"*** number of segments which contain ***"M"*** number of characters given a variable ***"V"*** ( `string => S / V = (N * V:(M * V)) `):
*/
// The string to split and the variable with any number as a value
var myString = "aaabbbcccdddeeefffggghhhiiijj";
var myNumber = 3;
// First we declare some variables, necessary to work
let result = '', arr = [];
let length = myString.length, array = [];
// Now we need to know how many segments will be
var halfLength = (length / myNumber);
// In this step, we need to separate and store each character inside an array;
// to do this we modify the original string with a "for" loop.
for ( let i = 0; i < length; i++ ) {
arr.push( myString.charAt( i );
}
// Finally, we join the necessary number of characters in each segment and,
// we form the new string with each segment; For this we create another loop,
// but this time, the loop will be repeated as many times as the number of segments we need
for ( let i = 0; i < halfLength; i++ ) {
const t = ( myNumber * i );
result = arr.slice( t, ( myNumber + t ) ).join( '' );
array.push( result );
}
// And you have the result that you need
console.log( `"${ array.join( ' ' ).trim() }"` ); // output must be: "aaa bbb ccc ddd eee fff ggg hhh iii jj"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment