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));
Related
I need to create a string like this: 01-2--3---4----5-----6------7------- for a let n=7, using a loop.
I've created something like this so far:
let numbers = '';
n = 7;
for(i=0; i<=n; i++) {
numbers += i;
if (i>0) {
numbers += ('-')
}}
which gives me: "01-2-3-4-5-6-7-". Don't know how to change the code so that it could multiply the number of '-' equal n in every loop.
What you need is a nested loop, to iterate over the value of i in the outer loop.
const n = 7
let result=''
for (let i = 0; i <= n; i++) {
let dashes=''
for(let j=0; j < i; j++){
dashes+='-'
}
result+= `${i}${dashes}`
}
console.log(result)
You could use String#repeat for the wanted dash.
Do not forget to declare any variable.
let numbers = '',
n = 7;
for (let i = 0; i <= n; i++) numbers += i + '-'.repeat(i);
console.log(numbers);
This the solution for your problem:
var numbers = '';
var n = 7;
for(var i = 0; i <= n; i++) {
numbers += i;
for(var j = 0; j < i; j++) {
numbers += "-";
}
}
const animal = "cat";
for (let i = 0; i < animal.length; i++) {
console.log(animal[i]);
for (let j = 1; j < 4; j++) {
console.log(j);
}
}
How do I output the answer going straight rather than going down.
Each console.log print in a new line
You can create a variable, assign what you want to display to it then, display it once.
Or
You can use multiple values in one console.log separateb by comma ,
const animal = "cat";
let result = ""
for (let i = 0; i < animal.length; i++) {
result += animal[i]
for (let j = 1; j < 4; j++) {
result += " " + j + " "
console.log(animal[i], j)
}
}
console.log(result)
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));
I have the following function to get all of the substrings from a string in JavaScript. I know it's not correct but I feel like I am going about it the right way. Any advice would be great.
var theString = 'somerandomword',
allSubstrings = [];
getAllSubstrings(theString);
function getAllSubstrings(str) {
var start = 1;
for ( var i = 0; i < str.length; i++ ) {
allSubstrings.push( str.substring(start,i) );
}
}
console.log(allSubstrings)
Edit: Apologies if my question is unclear. By substring I mean all combinations of letters from the string (do not have to be actual words) So if the string was 'abc' you could have [a, ab, abc, b, ba, bac etc...] Thank you for all the responses.
You need two nested loop for the sub strings.
function getAllSubstrings(str) {
var i, j, result = [];
for (i = 0; i < str.length; i++) {
for (j = i + 1; j < str.length + 1; j++) {
result.push(str.slice(i, j));
}
}
return result;
}
var theString = 'somerandomword';
console.log(getAllSubstrings(theString));
.as-console-wrapper { max-height: 100% !important; top: 0; }
A modified version of Accepted Answer. In order to give the minimum string length for permutation
function getAllSubstrings(str, size) {
var i, j, result = [];
size = (size || 0);
for (i = 0; i < str.length; i++) {
for (j = str.length; j - i >= size; j--) {
result.push(str.slice(i, j));
}
}
return result;
}
var theString = 'somerandomword';
console.log(getAllSubstrings(theString, 6));
Below is a recursive solution to the problem
let result = [];
function subsetsOfString(str, curr = '', index = 0) {
if (index == str.length) {
result.push(curr);
return result;
}
subsetsOfString(str, curr, index + 1);
subsetsOfString(str, curr + str[index], index + 1);
}
subsetsOfString("somerandomword");
console.log(result);
An answer with the use of substring function.
function getAllSubstrings(str) {
var res = [];
for (let i = 0; i < str.length; i++) {
for (let j = i + 1; j <= str.length; j++) {
res.push(str.substring(i, j));
}
}
return res;
}
var word = "randomword";
console.log(getAllSubstrings(word));
function generateALlSubstrings(N,str){
for(let i=0; i<N; i++){
for(let j=i+1; j<=N; j++){
console.log(str.substring(i, j));
}
}
}
Below is a simple approach to find all substrings
var arr = "abcde";
for(let i=0; i < arr.length; i++){
for(let j=i; j < arr.length; j++){
let bag ="";
for(let k=i; k<j; k++){
bag = bag + arr[k]
}
console.log(bag)
}
}
function getSubstrings(s){
//if string passed is null or undefined or empty string
if(!s) return [];
let substrings = [];
for(let length = 1 ; length <= s.length; length++){
for(let i = 0 ; (i + length) <= s.length ; i++){
substrings.push(s.substr(i, length));
}
}
return substrings;
}
var howM = prompt("How many cards?")
var arr = [];
for(var i = 0; i < howM; i++)
arr.push(prompt("Enter a card:"));
console.log(arr)
for(var i = 0; i <= howM; i++)
var sum = 0;
var eXt = arr[i]
eXt = eXt.replace (/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1)); }
console.log(sum);
It tells me this "TypeError: Cannot read property 'replace' of undefined
at eval:13:11" which makes no sense to me because its right above it.
The intetended body of the loop for(var i = 0; i <= howM; i++) is not enclosed in braces {..}. As a result, only the statement var sum = 0; will be executed in the loop. Also, you probably meant to say i < howM. So you want something like this for the loop:
for(var i = 0; i < howM; i++) {
var sum = 0;
var eXt = arr[i]
eXt = eXt.replace (/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
}
console.log(sum);
Check the comments:
var howM = prompt("How many cards?")
var arr = [];
for(var i = 0; i < parseInt(howM); i++)
arr.push(prompt("Enter a card:")); //No curly braces is fine when its a single line. When there's no braces, JS just runs the next line x amount of times
console.log(arr)
var sum = 0; //Create sum out here. Setting it to zero every loop defeats the purpose
for(var i = 0; i < arr.length; i++)//You said "i <= howM". Better to use the length of the array that is being looped through
{ //Use curly braces to show what code to execute repeatedly
var eXt = arr[i]; //Set eXt to the current number
eXt = eXt.replace("-", ""); //No need for regex
sum += parseInt(eXt); //Convert the input to a number, then add it to sum
}
console.log(sum);
The second for loop doesn't have brackets around it. You can MUST use brackets UNLESS it is a one line loop. For example:
This is fine:
for (var i=0;i<100;i++)
console.log(i);
This is NOT:
for (var i=0;i<100;i++)
var x = i;
x++;
console.log(x);
So the second for loop should be this:
for(var i = 0; i <= howM; i++) {
var sum = 0;
var eXt = arr[i]
eXt = eXt.replace (/-/g, "");
for (i = 0; i < eXt.length; i++) {
sum += parseInt(eXt.substr(i, 1));
}
console.log(sum);
}
Also in the first for loop I would use arr[i] = value instead.