Exploring arrays through nested for loops to draw comparisons

Issue: I have two arrays, one representing Alice's scores and the other Bob's scores. The task is to compare the scores at each index for both players and award a point to the player with the higher score (no points if the scores are equal).

INPUT:

x = [4,1,6]
y = [1,1,5]

EXPECTED OUTPUT:

{Alice:2, Bob: 0}

MY CODE:

x = [4,1,6]
y = [1,1,5]

results = {'Alice':0, 'Bob': 0}

for (var i = 0; i < x.length; i++){
  for (var j = 0; j < y.length; j++){
    if (x[i] > y[j]){
      results['Alice'] += 1
    }else if (x[i] < y[j]){
      results['Bob'] += 1
    }
  }
}

console.log(results)

ACTUAL OUTPUT:

{Alice: 5, Bob: 2}

QUESTION:

What mistake did I make in my code?

Answer №1

The mistake lies in the approach of comparing all possible pairs with the first value from one array and the second from another. Instead, the comparison should be made between values at the same position in both arrays. This only requires one loop as shown below:

x = [3,7,9]
y = [1,7,6]

results = {'Alice':0, 'Bob': 0}

for i in range(len(x)):
    if x[i] > y[i]:
        results['Alice'] += 1
    elif x[i] < y[i]:
        results['Bob'] += 1

print(results)

Answer №2

The major issue lies in the utilization of a nested loop. The current implementation involves comparing each result from Alice against every result from Bob, following this sequence:

  • Alice[0] vs. Bob[0] - 1 point for Alice
  • Alice[0] vs. Bob[1] - 1 point for Alice
  • Alice[0] vs. Bob[2] - 1 point for Bob
  • Alice[1] vs. Bob[0] - Tie
  • Alice[1] vs. Bob[1] - Tie
  • Alice[1] vs. Bob[2] - 1 point for Bob
  • Alice[2] vs. Bob[0] - 1 point for Alice
  • Alice[2] vs. Bob[1] - 1 point for Alice
  • Alice[2] vs. Bob[2] - 1 point for Alice

To rectify this, eliminate the inner loop and variable j, opting to solely use i.

var x = [4, 1, 6]
var y = [1, 1, 5]

var results = {
  'Alice': 0,
  'Bob': 0
}

for (var i = 0; i < x.length; i++) {
  if (x[i] > y[i]) {
    results['Alice'] += 1
  } else if (x[i] < y[i]) {
    results['Bob'] += 1
  }
}

console.log(results)

Answer №3

To achieve the desired output, you must compare each element in array x to the corresponding element in array y. This means comparing the first element of x with the first element of y, the second with the second, and so on.

I trust this explanation clarifies things for you!

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

What is the best way to handle waiting for an API call in JavaScript export?

In my Vue app, I've set up my firestore app initialization code as shown below: if (firebase.apps.length) { firebase.app() } else { firebase.initializeApp(config) } export const Firestore = firebase.firestore() export const Auth = firebase.auth() ...

Image carousel with variable height

I'm attempting to implement a slide show of images with previous and next functionality. When the user clicks "previous," I want the images to slide to the left, and when they click "next," I want the images to slide to the right with a 0.5 second del ...

What is the best way to showcase my Angular modules' views as the main page in my MEAN.JS project?

After some investigation, I discovered that the index page is actually named index.server.view.html. However, the file only consists of the following code: {% extends 'layout.server.view.html' %} {% block content %} <section data-ui-view ...

What is the most graceful method to calculate the average date from an array containing moment.js dates?

I have been using the reduce method along with the dayOfYear function to calculate the average date from an array of dates. While my current solution functions well for dates within the same year, it unfortunately overlooks the discrepancy in years betwee ...

Connecting two tables in an express API

Currently, I am in the process of developing an API using Express.js. At this stage, my initial tests are functioning correctly. My goal now is to retrieve values from two separate tables. For example, consider the following 2 tables: Table_A Id: 1, Name: ...

Problem in Swift - Array containing arrays within a dictionary

I'm currently troubleshooting my code as XCode is refusing to run it. Any thoughts on what could be causing the issue? var dictionary = [String: [[String]]]() var array = [[AnyObject]]() dictionary["1"] = [["A", "A"], ["A1", "A2"]] dictionary["2"] = ...

Utilizing the power of HTML datalist and *ngFor to present one value while sending another

I am currently working on a project that involves creating an autocomplete text box using the <datalist> tag with *ngFor functionality. However, the code I am using is showing both the value declared with [value] and the input between the <option& ...

Modify a Google Docs script for use in Google Sheets

I created a function called "myFunk()" that works flawlessly in Google Docs. It essentially looks for fields marked with ## in a sheet and replaces them with user input. However, when I attempt to run it in Sheets after making some changes to the functions ...

Convert the TXT file into an array

Before asking for help, I made sure to search for similar questions on SOF such as this one or this one However, none of the solutions provided solved my problem. So here's the code I've been working on: const file = './PAGE1.txt'; con ...

Retrieve the maximum value from a JSON object using JavaScript

This question seems straightforward, but I'm struggling to solve it. Could someone help me with a JavaScript solution to retrieve the largest value from this JSON object? {"data":{"one":21,"two":35,"three":24,"four":2,"five":18},"meta":{"title":"Ha ...

How to efficiently eliminate duplicates from an array list using React framework

Keeping the array name constant while duplicating and repeating this process only clutters the list. Appreciate your help. setListItems(contents.data); console.log(contents.data); ...

Selenium Python Slider Button Element Visibility Issue

Currently, I am developing a parser to automate the process of clicking buttons on a website. However, I am encountering difficulties in clicking two specific buttons. The buttons I am aiming to click are "Elija el imports a financiar" and "Elija la mensu ...

Using JQuery to manipulate `this`, its children, its siblings, and more

Can anyone help me determine the most effective way to send data from a get request to a specific div? My challenge is to send it only to a div that is related to the one triggering the action. For example, when I click on the message_tab, I want to send t ...

Best practices for using parent and child methods in Vue applications

I'm exploring the most effective approach to creating a modal component that incorporates hide and show methods accessible from both the parent and the component itself. One option is to store the status on the child. Utilize ref on the child compo ...

Unable to set two image layers on HTML canvas to display in different colors as anticipated

I am facing a challenge with stacking 3 images: an outline, a white base, and a pattern that is also white. My goal is to layer these images where the base is at the bottom with one color assigned to it, the pattern is stacked on top with a different color ...

What is the solution to the error message "TypeError: Cannot read property 'firstname' of undefined" when working with Firebase and Cloud Functions?

I'm having some trouble creating a new Document in my Firestore database using Cloud Functions. I am also using Postman to send a POST request with the following data: { "firstname": "TestFirst2", "lastname": "TestLast2", "email": "< ...

File upload tool for CKEditor 5 with Angular integration

Looking to develop a versatile file upload plugin for various document types (pdf, docx, etc.) that can upload to a server and generate links within the document. I've been researching potential solutions over the past couple of weeks, but many of th ...

Guidelines for accessing a specific object or index from a dropdown list filled with objects stored in an array

Here is a question for beginners. Please be kind. I have created a select field in an HTML component using Angular, populated from an array of objects. My goal is to retrieve the selection using a method. However, I am facing an issue where I cannot use ...

Encountering an error in React js where it is unable to read property "0" when making an API call

I am facing an issue with accessing data from the fetch function in my project. The goal is to pass the data from the action to the reducer. The API is being called using a fetch function, which returns a promise. So, the API call is made separately and th ...

Recognizing a component through various page loads

The title of this question may not be the best, but I hope my explanation clarifies what I'm trying to achieve. It's 4AM, so please forgive any confusion in my message. What I want to do is identify if a user-selected element appears on any page ...