JavaScript "alternating pattern"

When faced with this code test question, I decided to tackle it with the following approach:

    function createPattern(){
        var result = ''

        for (var row = 0; row < 10; row++){
            for (var col = 0; col < 10; col++){
                if ((row % 3 == 0 && col % 3 == 0) || (row % 3 == 1 && col % 3 == 1) || (row % 3 == 2 && col % 3 == 2)){
                    result += '1'      
                } else {
                    result += '0'
                }
                if (col == 9){
                    result += '\n'
                }
            }           
        }
        
        console.log(result)
    }

Here is the resulting pattern:

1001001001
0100100100
0010010010
1001001001
0100100100
0010010010
1001001001
0100100100
0010010010
1001001001

While this code works, I am interested in exploring more efficient ways to achieve the same output. Any suggestions?

Answer №1

This alternative method achieves the same outcome:

function generatePattern(){
    var result = '';
    for (var x = 0; x < 10; x++){
        var remainder = x % 3;
        for (var y = 0; y < 10; y++){
            if (y % 3 == remainder){
                result += '1'      
            } else {
                result += '0'
            }
        }
        result += '\n'
    }
    console.log(result)
}

Answer №2

Here is a straightforward approach that comes to mind:

for (let i=0;i<10;i++){
  let str = "1010101010101010101";
  console.log(str.substring(str.length-10-i, str.length-i));
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue encountered when attempting to connect an external script to a Vue single file component

Struggling to link an external script to a single file component in Vue. My project setup is as follows: https://i.sstatic.net/LWvNx.png I need to link the file components/Sshy to ../javascripts/ I have successfully linked other scripts using either of ...

The concept of inheriting directives/scopes

Just wondering if directives declared within a Component in Angular 2 automatically apply to its children Components. And when it comes to variables declared on the Component, do they get inherited by the children Components or must they be explicitly pa ...

When attempting to access /test.html, Node.js server returns a "Cannot GET"

Embarking on the journey of diving into Pro AngularJS, I have reached a point where setting up the development environment is crucial. This involves creating an 'angularjs' directory and placing a 'test.html' file in it. Additionally, o ...

Implementing a Button Click Event Listener on a Separate Component in React

Currently, my React application incorporates MapBox in which the navbar is its parent component. Within the navbar component, there is a button that collapses the navbar when clicked by changing its CSS class. I also want to trigger the following code snip ...

Display the input text line by line

How can I achieve the desired output for this input parameter? displayText("you and me"); expected output: ["you and me", "you and", "and me", "you", "and", "me"] I have attempted ...

Modify the initial header tag within the document to be <h1> instead of <h2>, <h3>, ... <h6>

In the event that the <h1> tag is not present, the script will search for the first header tag in the document (either <h2> through <h6>). If the text within this tag matches the title text, it will be converted to <h1 class="heading1" ...

What could be the reason for jQuery not functioning properly as needed?

function toggleDisplayingRooms(nameSelect){ if(nameSelect){ firstroom = document.getElementById("firstroom").value; secondroom = document.getElementById("secondroom").value; thirdroom = ...

Dynamically removing buttons with JQuery

I am trying to dynamically add buttons to a page based on an array, but I'm running into a problem. Whenever I add a new name to the array, it prints out all of the buttons instead of just the one I added. I need help figuring out how to erase all the ...

JavaScript - convert the values of an array within a JSON object into separate strings

I am receiving a JSON object from an API, and my next step involves some string analysis of each key value. This process works perfectly for 90% of the objects I receive because the key values are strings. { ID: '0012784', utm_source: 'webs ...

What steps should I take to solve this wheel-related issue in my Vue 3 application?

I have been developing a Single Page Application (SPA) using Vue 3, TypeScript, and The Movie Database (TMDB). Currently, I am tackling the implementation of a search feature and I've encountered a bug. The "search-box" component is located in src&b ...

AnimationHandler does not animate the Three.js Mesh

I've been struggling to animate the exported mesh from my blender. Even the included buffalo mesh that I see animated in the example is not working for me. I've been attempting to replicate it without success. Here's the code, and I think th ...

Emphasizing the text while making edits to an item within the dhtmlx tree

Whenever I need the user to rename an item on the tree, I trigger the editor for them: tree.editItem(tree.getSelectedItemId()); However, I want the text in the editor to be automatically selected (highlighted). Currently, the cursor is placed at the end ...

Identify the key name in an array of objects and combine the corresponding values

Here is an example of my array structure: array = [{ "name": "obj0_property0", "url": "picture1" }, { "name": "obj1_property0", "url": "picture1" }, { "name": "obj0_property1", "url": "picture2" }] I am looking to transform this array using J ...

Trigger a function in AngularJS when a div is scrolled to within a specific number of pixels from the bottom of the screen

I am experimenting with the AngularJS infinite-scroll directive. Below is the code snippet: angular.module('infiniteScroll', []) .directive('infiniteScroll', [ "$window", function ($window) { return { link:funct ...

Deciphering the significance behind the initial five lines of code in jQuery

Curiosity piqued, I delved into the jQuery code only to be met with this puzzling snippet: ! function(a, b) { "object" == typeof module && "object" == typeof module.exports ? module.exports = a.document ? b(a, !0) : function(a) { i ...

What is the best way to retrieve data from a JSON object?

Can the status variable be used as a JSON object? What is the method to access the values of action_success and newIndex within the status object? Server: [HttpPost] public ActionResult UploadFiles() { // save file.. return Json(new { action_suc ...

During the present module, retrieve the runtime list of all modules that are directly imported (Javascript/Typescript)

Imagine you have a set of modules imported in the current module: import {A1, A2, A3} from "./ModuleA"; import {B1, B2, B3} from "./ModuleB"; import {C1, C2, C3} from "./ModuleC"; function retrieveListOfImportedModules() { // ...

The JSON.parse function encounters issues when trying to parse due to a SyntaxError: Unexpected character found after JSON at position 2, causing it to be unable

I've encountered an issue with my JavaScript code when trying to retrieve the value of the details field from JSON data. While all other values are successfully passed to their respective fields, the details field generates the following error: "Unabl ...

Utilize PHP SVG images to trigger internal JavaScript code through the <img> tag

Here is a php function that generates an SVG image. public function actionJsTest() { header('Content-Type: image/svg+xml'); $svg = ''; $svg .= '<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/ ...

Utilizing CSS files to incorporate loading icons in a component by dynamically updating based on passed props

Is it possible to store icons in CSS files and dynamically load them based on props passed into a component? In the provided example found at this CodeSandbox Link, SVG icons are loaded from the library named '@progress/kendo-svg-icons'. Instea ...