How do I log some tests for javascript? - javascript

I was hoping to get your assistance with this "Is Unique" algorithm in Javascript.
var allUniqueChars = function(string) {
// O(n^2) approach, no additional data structures used
// for each character, check remaining characters for duplicates
for (var i = 0; i < string.length; i++) {
console.log(i);
for (var j = i + 1; j < string.length; j++) {
if (string[i] === string[j]) {
return false; // if match, return false
}
}
}
return true; // if no match, return true
};
/* TESTS */
// log some tests here
allUniqueChars('er412344');
I am looking to log some tests, to see it display in the console. How do I call the function with unique strings to test it?
John

You can always create an Array with your strings and test like:
var allUniqueChars = function(string) {
// O(n^2) approach, no additional data structures used
// for each character, check remaining characters for duplicates
for (var i = 0; i < string.length; i++) {
for (var j = i + 1; j < string.length; j++) {
if (string[i] === string[j]) {
return false; // if match, return false
}
}
}
return true; // if no match, return true
};
/* TESTS */
// log some tests here
[
'er412344',
'ghtu',
'1234',
'abba'
].forEach(v => console.log(allUniqueChars(v)));
MDN Array.prototype.foreach

Run the snippet multiple times to generate unique random strings and display results:
var allUniqueChars = function(string) {
for (var i = 0; i < string.length; i++)
for (var j = i + 1; j < string.length; j++)
if (string[i] === string[j])
return false;
return true;
};
var getUniqueStr = () => Math.random().toString(36).substr(2, 9);
let myStringArray = [];
for(var i =0 ; i<8; i++) // 8 test cases in this example
myStringArray.push(getUniqueStr());
console.log(myStringArray.map(e=>e + " : " + allUniqueChars(e)));

You can use this function found here to generate random strings for testing (not mine!):
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));

Related

I want to print a square using the hash characters, javascript

I am trying to print a square using the hash character
function square(num){
for(i = 0; i < num; i++){
for(j = 0; j < num; j++){
console.log("#");
}
console.log(" ");
}
}square(2);
/* my output is:
"#"
"#"
"#"
"#"
instead of:
"##"
"##"
*/
Every time you console.log(), the console will print a new line. You need to add each row to one line like this:
function square(num){
for(i = 0; i < num; i++){
let row = ''
for(j = 0; j < num; j++){
row+='#'
}
console.log(row+" ");
}
}
square(4);
Creating a function named square to return a square pattern.Using squareArray as the solution array and result string to store the value for each inner loop.Finally, using join to convert array to string.
function square(num) {
const squareArray = [];
let result;
for (let i = 0; i < num; i++) {
result = "";
for (let j = 0; j < num; j++) {
result += "#";
}
squareArray.push(result);
}
return squareArray.join("\n");
}
console.log(square(2));
console.log(square(4));
console.log(square(6));

Code works in console but not in Hackerank

My code works in console but gives the wrong result in hackerank
Problem: Print count of all substrings that are palindromes from a string
function isPalindrome(str) {
var len = str.length;
var mid = Math.floor(len / 2);
for (var i = 0; i < mid; i++) {
if (str[i] !== str[len - 1 - i]) {
return false;
}
}
//Had to use this lengthy function because in
//str == str.split('').reverse().join('');
//I was getting error that split is not a function
return true;
}
function scatterPalindrome(str) {
var result = [],
c = 0;
for (let i = 0; i < str.length; i++) {
for (let j = i + 1; j < str.length + 1; j++) {
result.push(str.slice(i, j));
}
}
for (let i = 0; i < result.length; i++) {
let k = result[i];
if (isPalindrome(k))
c++;
}
return c; // the answer was always 1
}
console.log(scatterPalindrome("abc"));
input: "abc"
expected output: 3
actual output:1
As I can't comment, so answering here, I will say you should check if they have mentioned there are many test cases, and in each test case you have to do the query then this is reasonable that your output and their output will not match
take no.of testcases input
while(testcases counter doesn't reach 0 )
take string input
call your function for answer for input and print
decrement testcases counter

javascript matrix manipulation is not working

This is a bad coded solution to a problem in "advent of code": link to problem
I don't know the reason because my code is not working properly, I had an error related to regular expressions cause I didn't reset the pointer of the regexp object, now that error is fixed I think, but something is escaping to my knowledge in what I've done bad.
The problem is that the solution that my code displays is not correct, you can submit a solution on the link I've provided and get feedback of your solutions.
Correct solution: 543903
Given solution: 418954
// day 6 of advent of code
var input = "removed, take from problem";
function processInput(input, matrix) {
var linesOfInput = input.split("\n");
var matches;
var turnOnRE = /turn on (\d+),(\d+).*?(\d+),(\d+)/g;
var turnOffRE = /turn off (\d+),(\d+).*?(\d+),(\d+)/g;
var toggleRE = /toggle (\d+),(\d+).*?(\d+),(\d+)/g;
// regular expression objects lastIndex property must be 'reseted' in order to work well
for (var i = 0 ; i < linesOfInput.length; i++) {
turnOnRE.lastIndex = 0;
turnOffRE.lastIndex = 0;
toggleRE.lastIndex = 0;
matches = turnOnRE.exec(linesOfInput[i]);
if (matches != null) {
manipulateLights(matrix, matches[1], matches[2], matches[3], matches[4], true);
continue;
}
matches = turnOffRE.exec(linesOfInput[i]);
if (matches != null) {
manipulateLights(matrix, matches[1], matches[2], matches[3], matches[4], false);
continue;
}
matches = toggleRE.exec(linesOfInput[i]);
manipulateLights(matrix, matches[1], matches[2], matches[3], matches[4]);
}
}
function manipulateLights(matrix, startI, startJ, endI, endJ, newValue) {
if (newValue == undefined) { // toogle
for (var i = startI ; i <= endI; i++) {
for (var j = startJ ; j <= endJ; j++) {
matrix[i][j] = !matrix[i][j];
}
}
console.log(startI, startJ, endI, endJ, newValue);
} else {
for (var i = startI ; i <= endI; i++) {
for (var j = startJ ; j <= endJ; j++) {
matrix[i][j] = newValue;
}
}
console.log(startI, startJ, endI, endJ, newValue);
}
console.log(countTurnedOnLights(matrix));
}
function countTurnedOnLights(matrix) {
var turnedOn = 0;
for (var i = 0 ; i < matrixWidth; i++) {
for (var j = 0 ; j < matrixHeigth; j++) {
if (matrix[i][j] == true) {
turnedOn++;
}
}
}
return turnedOn;
}
var matrixHeigth = 1000;
var matrixWidth = 1000;
// define a bidimensional array, is almost like in C++
var lightMatrix = new Array(matrixWidth);
for (var i = 0 ; i < matrixWidth; i++) {
lightMatrix[i] = new Array(matrixHeigth);
}
// turn off all lights
for (var i = 0 ; i < matrixWidth; i++) {
for (var j = 0 ; j < matrixHeigth; j++) {
lightMatrix[i][j] = false;
}
}
processInput(input, lightMatrix);
console.log(countTurnedOnLights(lightMatrix));
OK I figured out the error - your regular expression matches are being treated as strings when you first create your for loops.
for (var i = startI ; i <= endI; i++) {
for (var j = startJ ; j <= endJ; j++) {
When you hit a combo like 756,53 through 923,339, it thinks 53 > 339 and it exits the loop immediately. Either wrap each "start" variable with Number() in your for loops, or do so when passing the parameters.

removing characters from a string - javascript algorithm

I'm practicing algorithm problems and am trying to remove given letters from a string in o(n) time.
My attempt below is wrong in a couple of ways:
the last index in the outputString array is "undefined" and I'm not sure why.
my output is the right letter, but it's being returned for the length of the original string.
How can I fix these and why are these errors occurring?
function removeChars(lettersToDelete, string) {
var flags = {}; // a hash of letters to delete.
var outputString = string.split("");
var lettersToDelete = lettersToDelete.split("");
var i, j;
for (i = 0; i < lettersToDelete.length; i++) {
flags[lettersToDelete[i]] = true;
}
console.log(flags);
for (var j = 0; j < string.length; j++) {
if (flags[string[j]]) {
outputString[j++] = string[j];
}
}
console.log(outputString); //[ 'a', 'a', 'a', 'a', undefined ]
return outputString.join(""); // 'aaaa'
}
function removeChars(lettersToDelete, string) {
var flags = {}; // a hash of letters to delete.
var outputString = []; //string.split("");
var lettersToDelete = lettersToDelete.split("");
var i, j;
for (i = 0; i < lettersToDelete.length; i++) {
flags[lettersToDelete[i]] = true;
}
for (var j = 0; j < string.length; j++) {
if (!flags[string[j]]) {
outputString.push( string[j] );
}
}
console.log(outputString);
return outputString.join(""); // 'aaaa'
}
removeChars("itu", "mitul");

Find first longest word in a string, excluding symbols

function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i < str.length; i++) {
var checkedLetters = "";
for (var j = 0; j < str[j].length; j++) {
if (j == /[^a-zA-Z]/) {
checkedLetters += j;
}
if (longest < checkedLetters.length) {
longest = checkedLetters.length;
word = checkedLetters;
}
}
}
return word;
}
Is there something wrong with my use of regex? When I call longestWord("Hello, I am here") I want it to return "Hello" (without the comma), but it returns null.
Just wrote this little snippet, might help you out:
function longestWord(string){
return string.match(/[a-zA-Z]+/g)
.reduce(function(a,b){
return a.length>=b.length?a:b;
})
}
/[a-zA-Z]+/g matches all words in the string, and returns an array of them. Your test string above ("Hello, I am here") will become ["Hello","I","am","here"] when this RegEx is run on it.
Once I have this array, it is simply a matter of looping through it to find the longest word. I accomplished this by using .reduce.
There are some mistake in your code:
for (var j = 0; j < str[j].length; j++) {
should be
for (var j = 0; j < str[i].length; j++) {
And
if (j == /[^a-zA-Z]/) {
Should be:
if (/[a-zA-Z]/.test(str[i][j])) {
Your final code should be:
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i < str.length; i++) {
var checkedLetters = "";
for (var j = 0; j < str[i].length; j++) {
if (/[a-zA-Z]/.test(str[i][j])) {
checkedLetters += str[i][j];
}
}
if (longest < checkedLetters.length) {
longest = checkedLetters.length;
word = checkedLetters;
}
}
return word;
}
Check demo
The big (non-typo) problem with how you’re using regular expressions is that the method is .test; == will test whether the string is equal to the string representation of the regular expression.
Just use .match and a little bit of sort magic!
function longestWord(string){
var words = string.match(/\w+/g);
words.sort(function(a, b) { return b.length - a.length; });
// Firefox 22.0 promotion:
// words.sort((a, b) => a.length - b.length);
return words[0];
}
You don't need to use Regex, you can just use .length to search for the longest string.
i.e.
function longestWord(string) {
var str = string.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"").split(" ");
longest = str[0].length;
longestWord = str[0];
for (var i = 1; i < str.length; i++) {
if (longest < str[i].length) {
longest = str[i].length;
longestWord= str[i];
}
}
return longestWord;
}
EDIT: You do have to use some Regex...

Categories

Resources