Finding subsetsums in Javascript

I'm facing an issue with my JavaScript code that seems to be causing it not to run properly.

 <p id="demo"></p>

Here is the JS code:

function isSubsetSum(arr, n, sum) {
  if (sum == 0) {
    return true;
  }
  if (n == 0 && sum != 0) {
    return false;
  }
  if (arr[n - 1] > sum) {
    return isSubsetSum(arr, n - 1, sum);
  }
  return isSubsetSum(arr, n - 1, sum) || isSubsetSum(arr, n - 1, sum - arr[n - 1]);
}

function findPartiion(arr, n) {
  var sum = 0;
  for (int i = 0; i < n; i++) {
    sum += arr[i];
  }
  if (sum % 2 != 0) {
    return false;
  }
  return isSubsetSum(arr, n, sum / 2);
}

var arr = {3,1,1,2,2,1};
var n = fruits.length;

if (findPartiion(arr, n) == true) {
  document.getElementById("demo").innerHTML = "Can be divided into two subsets of equal sum";
} else {
  document.getElementById("demo").innerHTML = "Cannot be divided into two subsets of equal sum";
}

Despite adding the HTML code as shown above, I am unable to get any output from my JavaScript. When I execute the code, nothing appears on the screen. Thank you for your assistance in this matter.

Answer №1

There seems to be some errors (check the console), but here are a few corrections:

  • for (int i = 0; i < n; i++){ is not valid JavaScript syntax, replace int with var
  • An array should be defined using brackets [] and not curly braces {} (which define objects)
  • var n = fruits.length - 'fruits' is not defined, it probably should be 'arr'

Please refer to the following working code snippets:

function isSubsetSum(arr,n,sum)
{
  if (sum == 0){
    return true;
  }
  if (n == 0 && sum != 0){
   return false;
  }
  if (arr[n-1] > sum){
    return isSubsetSum (arr, n-1, sum);
  }
  return isSubsetSum (arr, n-1, sum) || isSubsetSum (arr, n-1, sum-arr[n-1]);

}

function findPartiion (arr, n)
{
  var sum = 0;
  for (var i = 0; i < n; i++){
    sum += arr[i];
  }
  if (sum%2 != 0){
    return false;
  }
  return isSubsetSum (arr, n, sum/2);
}

var arr = [3,1,1,2,2,1];
var n = arr.length;

if (findPartiion(arr, n) == true){
  document.getElementById("demo").innerHTML = "Can be divided into two subsets of equal sum";
}
else{
  document.getElementById("demo").innerHTML = "Cannot be divided into two subsets of equal sum";
}
 <p id="demo"></p>

I hope this explanation helps. Goodbye.

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

The module could not be found because there was an error: Unable to locate '@mui/icons-material/AddCircle', despite the fact that @mui/icons-material has been installed

When working with the IR compiler in Kotlin JS, I encountered an issue. The error message reads: Module not found: Error: Can't resolve '@mui/icons-material/AddCircle' Even though @mui/icons-material is already installed, the error persist ...

react native is not updating the view even though the state has been changed

Upon opening my component, I am looking to retrieve Assets from a Media Folder (which is currently functional) and then pass them along to another component. However, the issue arises when launching the app for the first time, as the "listOfAssets" state a ...

Unable to execute JavaScript within a partial view called through an AJAX request in MVC

In my partial view, I have written JavaScript code that retrieves the Geo-location of a client. <h1>Map</h1> <style type="text/css"> #map-canvas { height: 500px; } </style> <script type="text/javascript" ...

What is the best method for consolidating all parameter types of an object comprised of a collection of functions?

Can you analyze this typescript code snippet for me? type params1 = {p:number} ; type params2 = {p:boolean}; type params3 = {p:string}; type res = {r:string}; const fObject = { a:(a:params1):res=>{return {r:`${a.p}`}}, b:(a:params2):res=>{return {r: ...

Has Next.js incorporated a maximum cache size feature along with an invalidation algorithm like LRU?

Currently, I have a Next.js site that utilizes getServerSideProps for data fetching. However, I am interested in switching to getStaticProps and implementing incremental static regeneration (ISR) for improved performance. Currently, my memory usage is ap ...

What is the best way to organize an Express application that handles both API requests and views?

Currently, I am in the process of developing a small application that will function as both a website and its API. To achieve this, I am utilizing Node, Express, and Webpack. The structure of my directory is organized as follows: >client |>dist ...

Learn how to effectively transfer data from $.getjson to PHP, specifically through the use of Laravel's @foreach loop

$.getJSON( 'http://localhost/media_books/index.php/new_books.json?provider_id=1&limit=99&offset=1') .done(function( json ) { $(tar).closest('.accordion').children('div').text(json); }); I have successfully obtaine ...

How can I send an item to a dialog in a different VueJS component?

Having multiple smaller components instead of one big component is the goal for my project. Currently, I have a component with a <v-data-table> that displays various items. Each row includes a button that, when clicked, opens a <v-dialog> showi ...

How can a controller configure an AngularJS provider by passing options?

How can I pass configuration options to a provider from a controller? Below is an example of how to pass options/configurations to a provider from the controller: provider.js file: app.provider('contactProvider', function() { this.name ...

Axis incorporating additional padding for extensive domains

Encountering a peculiar issue with d3 axis generation. When creating a bottom x axis using d3.axisBottom() for ordinal domain values, extra padding is being added at the starting and ending points of ticks on the axis. This happens when the d3.scaleBand() ...

The scheduled job on Firebase Pubsub failed to execute due to an authentication error, returning the message: "UNAUTHENTICATED"

I've been attempting to create a leaderboard feature for my App that updates every 24 hours, but I'm running into issues... The job doesn't seem to be triggering at all. After researching, this is the only information I could find about sch ...

Utilizing Vue Store Methods within an Array or Object

Imagine we have 5 identical buttons. Instead of duplicating them, I decided to make use of v-for. methods: { a() {}, b() {}, ... } Replacing the individual buttons with: <v-btn block color="primary" class="my-1" @click="a">A</v-btn ...

javascript ajax is not executing correctly

With the help of Ajax, I have developed a console that allows me to dynamically execute PHP functions. This is how it appears https://i.sstatic.net/Wj2Ww.png The issue arises when the console gets filled with numerous commands, making it difficult to rea ...

The functionality of ngSubmit and ngDisabled seems to be malfunctioning, although ngModel is successfully linked to the

Despite following the usual process of creating a form in AngularJS, the ngSubmit function is not working as expected and the ngDisabled feature is failing to disable the button when the fields are empty. I even tried isolating the section in a new project ...

Measuring the rendering time of an AngularJS directive

Is there a way to measure the rendering time of a directive (element)? If not, is it possible to identify which directive takes the longest time to render? PS. I have tried using Batarang, but it only displays watch-expressions that consume the most time. ...

Datatables stands out by emphasizing rows across all paginated pages

Encountering an issue with the Datatables plugin when attempting to highlight rows on paginated pages beyond the first one. In the JavaScript code below, you can see where I have commented out adding the class info to all rows. When this is done and you n ...

PHP script effectively eliminates duplicates from multi-level nested arrays

I have a .txt file with unique data entries like this: Test = 10849831 = August 6, 2013: 56cake = 0 = August 6, 2013: Wwe = 812986192 = August 6, 2013: Test = 346192 = August 9, 2013: In order to convert this text into a multidimensional array, I impleme ...

javascript challenge with inheritance

I am encountering an issue with two objects where one inherits from the other. The parent object is sending an ajax request to send some contact email. However, when I use the child object to send the request, all data is empty for some reason. The ajax r ...

Upon page reload in Nuxt.js middleware, Firebase authentication is returning as null

Just started with nuxtjs and using the Nuxt firebase library for firebase integration. After a successful login, I'm redirecting the user to the "/member/desk" route. However, if I refresh the page on that particular route, it redirects me back to "/a ...

What is the best way to trigger a function following the blur event on an input field

My form includes a jquery-ui datepicker as one of the inputs. When a user moves away from an input field, I want to show a specific message (e.g. "This field is required"). The jQuery code below accomplishes this for basic <select> and <input type ...