Guide on executing j operations on an array

What is the most effective method for performing a series of j operations on an array of integers, where j can range from being fewer or equal to as long as the array itself?

I attempted the following approach...

function performJ(arr, j) {
  arr.sort((a, b) => b - a);
  let i = 0;
  while (j !== 0) {
   if (i < arr.length) {
     arr[i] = Math.ceil(arr[i] / 2)
   } else {
     // when i reaches arr.length, reset it to continue operations j
     i = 0;
     arr[i] = Math.ceil(arr[i] / 2)
   }
   // increment i, step through arr
   ++i;
   // decrement j as we perform operations on arr
   --j;
 }
 return arr.reduce((a, b) => a + b);
}

While this solution works for many cases, it seems that with larger inputs for both arr and j, the arithmetic calculations within the while loop go awry.

Thank you!

EDIT: Revised question for better understanding. I had a previous solution that functioned correctly but was too slow. Although the arithmetic in this revised solution may be inaccurate at times, it performs significantly faster.

Answer №1

Implementing modulo in order to loop through indexes [i % arr.length] from 0 to j:

function iterateJ(arr, j) {
  arr.someMethod(); // ?
  for (let i = 0; i < j; i++) {
    arr[i % arr.length] = /* operation */
  }
  return arr.someMethod(); // ?
}

Answer №2

Have you considered using a for loop in this way?

for(let i = 0; i <= count; i++) {
  const newIndex = i % itemsArray.length;
  itemsArray[newIndex] = performTask();
}

If the length of itemsArray is 7 but count is 4, then performTask() will only be executed on the first four elements. However, if the length of itemsArray is 4 and count is 7, then i will reach 3 and 3 % 4 === 3, so newIndex will loop back to the beginning. This implies that performTask() will operate on all four elements initially, and during the second cycle, it will act on only the first three elements.

Does this approach align with your intentions?

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

Is it feasible to maintain a variable as a reference across views while utilizing ng-view?

I am facing a unique challenge: I have a webpage with two tabs that need to utilize ng-view from AngularJS. The twist is that both tabs must share the same variable, similar to referencing a variable in C# using the "ref" keyword. If you want to see an ex ...

Improving Zen Coding to integrate with JavaScript files on Sublime Text2

Sublime Text2 is hands down my go-to editor, except for one minor hiccup - the Zen Coding plugin only works with CSS and HTML files. There are plenty of times where I'd love to use Zen Coding with JavaScript or other file types, like incorporating HTM ...

Update the getJSON filter to only include specific results and exclude the majority

In an effort to streamline my chart to only include data for "zelcash", I am currently faced with the issue of fluctuating values causing the line graph to be inconsistent. This is because the results show zelcash with 0 as the hashrate, along with actual ...

Saving JSON data into an HTML element using Handlebars templating

Is there a way to save the entire JSON object within an HTML element as a data attribute? let a = {name : "sample", age : "34"} $.find('#someDiv').data('adata', a); Is it possible to achieve the same result using Handlebars when creat ...

Encountering difficulties resolving my dynamic JSON data when compared to the static JSON data in the ng

I have a listbox and I am binding a list of items from a controller. $scope.AvailableListItems = [ [{Id:1,SupplierName: 'john.banks'}, {Id: 2,SupplierName: 'jim.chevy'}, {Id: 3,SupplierName: 'ralph.stocks'}] ]; ...

What could be causing my AJAX code to fail in retrieving information from an API?

Hey everyone, I'm new here and hoping to get some help with an issue I'm facing. I've written a code to fetch data from an API and display it on my HTML page, but for some reason the AJAX code isn't working. There's nothing showing ...

Activate a click on a div element to enable smooth scrolling when using the page down and page up keys

Whenever I directly click on my div, the pageUp and pageDown keys scroll the contents of the div. But when I trigger a click programmatically, the scrolling with pageUp and pageDown stops working. How can I enable scrolling with pageUp and pageDown without ...

The utilization of the jquery.form.js plugin is resulting in my form being submitted twice

In order to enable Ajax file uploads in my ASP.Net MVC project, I am utilizing the jquery plugin known as "jquery.form.js" (http://malsup.com/jquery/form/#getting-started). However, I am encountering an issue where the controller action responsible for han ...

What is the best way to display items from top to bottom in React?

Currently, I am working with a list of objects structured in this way: const items = [{name: 'some name', count: 'how many of that name'}, ...] My goal is to display them in the following format: {items.map((item) => ( ...

When the user clicks on the iframe, they will be redirected to the

My goal is to create a scenario where clicking on an iframe opens the same URL in a new browser tab, while ensuring that scroll and other mouse events within the iframe are not affected. I have experimented with various approaches but none have been succe ...

Utilizing CSS transitions in tandem with jQuery mousemove

Currently, I am developing a game that involves clicking and dragging using jQuery. Within the red game div, when you click an object appears that can be dragged around. To view a demonstration of this functionality, you can visit the following fiddle link ...

Having trouble figuring out why Ajax is sending Null to my .net core MVC controller

Learning Ajax and jQuery has been quite a challenge for me as a beginner. My current task involves passing an object with two string arrays - one for search parameters, the other for search values. The problem arises when I click the submit button and th ...

What is the best way to search for the smallest and largest values by utilizing Integer.MAX_VALUE?

I'm having trouble figuring out how to determine the maximum and minimum values in my array using Integer.MAX_Value and Integer.MIN_Value. public class AnnualFuelUseTester { public static void main(String [] args) { int sMiles1, eMiles1, dist; ...

Having trouble with localstorage.setitem function in Angular?

Check out the function below. I can see an object in the console.log using res: login2(){ console.log(this.user_form_value); console.log(this.password_form_value); this._loginService.login(this.user_form_value, this.password_form_value).subscr ...

Using operator [] to access elements in a custom array container wrapper

I've been working on creating my own array wrapper. I have overloaded the [] operators to return the address of an element in the array. However, when I dynamically allocate the ArrayWrapper class in the main function, it doesn't seem to be funct ...

Using the Petite-vue Initialization attribute within an HTML script tag

I came across a snippet of Vue.js code on Twitter from Evan You, but I'm confused about the purpose of the init attribute in the script tag. I've searched on MDN and other sites but couldn't find any information about it. However, I do unde ...

Leverage the capabilities of Node.js for parsing JSON arrays without any JSON objects within them

Can someone guide me on how to extract the value 3.25 from this object using node.js? Any help would be greatly appreciated. Thanks! "data": [["2020-05-04", 3.25],....] ...

Interacting with Rails controllers through AJAX to trigger a JavaScript function

After exploring numerous stack overflow posts without finding a working solution, I decided to seek help for a well-documented use case. I have a button that should perform the following tasks: When clicked, call a custom controller method to update th ...

Send all of the elements within an array as arguments to a function

My challenge involves working with an array of values: ['a', 'b', 'c', 'd'] I must pass these values as parameters to a function like this: window.myFunction('a', 'b', 'c', 'd&ap ...

Hide a span dynamically based on conditions in AngularJS

I need to conceal the <span ng-show="currencyObject.to != 'undefined'">=</span> until the currencyObject.to has a value of undefined. This should only occur until the user selects an option from the dropdown menu. I attempted to use n ...