why is class integer automately returned 1 - class

I have a problem with my code.
My code make for a value game.
There are 2 items, each have value and weight and a ship have max weight content.
When I input those value the console returns 1.
Can somebody tell me why integer class return 1 and how to fix it?
public class Sort {
static int knapsackLight(int value1, int weight1, int value2, int weight2, int maxW) {
if (weight1 + weight2 <= maxW) return value1 + value2;
else{
int d1 = maxW - weight1;
int d2 = maxW - weight2;
if (d1>=0 && d2>=0){
if (value1 >= value2) return value1;
else return value2;
}
else if (d1>=0 && d2<0) return d1;
else if (d2>=0 && d1<0) return d2;
}
return 0;
}
public static void main(String[] a){
int val1 = 5;
int val2 = 9;
int w1 = 10;
int w2 = 6;
int maxW = 7;
System.out.println(knapsackLight(val1,w1,val2,w2,maxW));
}
}

You will get different return values as per input values. You can add debug statements before return value to check which condition is holding true value. e.g.
System.out.println("value1");
return value1;
...
...
System.out.println("value2");
return value2;
...
...
System.out.println("d1");
return d1;
...
...
System.out.println("d2");
return d2;

1 is the correct answer for those values.
If (weight1 + weight2 <= maxW) is false (10 + 6 > 7)
(d1>=0 && d2>=0) is false because d2 is smaller than 0 (-3).
So your are returning d1 which is maxW(7) - weight1(6) = 1.

Related

Flutter find the sum of digits of int value

I want to find the sum of the digits of the number entered in Flutter. I want to encode this algorithm.
for example
x=1992
result=1+9+9+2=21
how can i do this with flutter
You can do in this way.
import 'dart:io';
void main() {
print('Enter X');
int X = int.parse(stdin.readLineSync()!);
int result = 0;
for (int i = X; i > 0; i = (i / 10).floor()) {
result += (i % 10);
}
print('Sum of digits\n$result');
}
Output
Enter X
123456
Sum of digits
21
transform the number into an String using String stringValue = x.toString();
create an array from each char using List<String> result = stringValue.split('');
sum each number transforming back using int.parse(result)
void main(){
int x = 1992;
String stringValue = x.toString();
List<String> result = stringValue.split('');
int sum = 0;
for(int i = 0 ; i < result.length; i++) {
int value = int.parse(result[i]);
sum = sum + value;
}
print(sum);
}
Result: 21

I want to divide adynamic List int five equal parts

I want to divide a dynamic list into five equal parts and take out one random number from each part. In doing so, I want to avoid duplicate numbers. Here is my code and it was not good at all.
List document;
int value1 = Random().nextInt((document.length / 5).round());
int value2 = Random().nextInt((document.length / 5).round()) +
((document.length / 5).round()) + 1;
int value3 = Random().nextInt((document.length / 5).round()) +
((document.length / 5).round() * 2) + 1;
int value4 = Random().nextInt((document.length / 5).round()) +
((document.length / 5).round() * 3) + 1;
int value5 = Random().nextInt((document.length / 5).round()) +
((document.length / 5).round() * 4) + 1;`
If you have a better way, I would appreciate it.
You can get this with a simple while loop and check if the element exists in the list already like the following
import "dart:math";
void main() {
List<int> intList = [];
List<int> randomList = [];
for (int i = 0; i < 100; i++) {
intList.add(i);
}
while(randomList.length < 5){
int _randomNum = Random().nextInt(intList.length);
if(randomList.contains(_randomNum) == false)
{
randomList.add(_randomNum);
}
}
print(randomList);
}

Validating Israeli ID number

I'm looking for a clean and efficient way to validate an Israeli ID number.
It's basically an implementation of the Luhn algorithm on a 9 digits number.
Note:
This question is here for the community because it wasn't on stack overflow yet.
You can add answers in different coding languages.
Here's an efficient way to implement it in C# (link):
public static bool IsValidIsraeliID(string israeliID)
{
if (israeliID.Length != 9)
return false;
long sum = 0;
for (int i = 0; i < israeliID.Length; i++)
{
var digit = israeliID[israeliID.Length - 1 - i] - '0';
sum += (i % 2 != 0) ? GetDouble(digit) : digit;
}
return sum % 10 == 0;
int GetDouble(long i)
{
switch (i)
{
case 0: return 0;
case 1: return 2;
case 2: return 4;
case 3: return 6;
case 4: return 8;
case 5: return 1;
case 6: return 3;
case 7: return 5;
case 8: return 7;
case 9: return 9;
default: return 0;
}
}
}
JS example code like it appears in Wikipedia:
https://he.wikipedia.org/wiki/ספרת_ביקורת
function IDValidator(id)
{
if (id.length !== 9 || isNaN(id)) { // Make sure ID is formatted properly
return false;
}
let sum = 0, incNum;
for (let i = 0; i < id.length; i++) {
incNum = Number(id[i]) * ((i % 2) + 1); // Multiply number by 1 or 2
sum += (incNum > 9) ? incNum - 9 : incNum; // Sum the digits up and add to total
}
return (sum % 10 === 0);
}

How to convert a binary number into a decimal fraction in dart?

Hi i have been wondering if there is a way in which to convert binary numbers into decimal fractions.
I know how to change base as an example through this code
String binary = "11110010";
//I'd like to change this line so it produces a decimal value
String denary = int.parse(binary, radix: 2).toRadixString(10);
If anyone still wondering how to convert decimal to binary and the inverse:
print(55.toRadixString(2)); // Outputs 110111
print(int.parse("110111", radix: 2)); Outputs 55
int binaryToDecimal(int n)
{
int num = n;
int dec_value = 0;
// Initializing base value to 1, i.e 2^0
int base = 1;
int temp = num;
while (temp) {
int last_digit = temp % 10;
temp = temp / 10;
dec_value += last_digit * base;
base = base * 2;
}
return dec_value;
}
int main()
{
int num = 10101001;
cout << binaryToDecimal(num) << endl;
}
This is my c++ solution but you can implement any language

Solving Twitter Puddle with Zipper

This is a follow-up to my previous question. Consider the following puzzle
I would like to generate a waterLevel array, so that the i-th item is the water level at the i-th point and then sum them up to solve the puzzle.
waterLevel[i] =
max(0, min(max of left neighbors, max of right neighbors) - height[i])
I would probably try to code it with Zipper
waterLevels = heights.toZipper.cobind {z =>
max(0, min(max(z.left), max(z.right)) - z.focus
}.toList
Does it make sense ?
My solution with java, it comes with tests with expected solution:
package com.company;
import java.util.*;
enum Orientation {DOWN, UP};
class Walls{
public static void main(String []args){
HashMap<String, Integer> tests = new HashMap<String,Integer>();
tests.put("2 5 1 2 3 4 7 7 6", 10);
tests.put("2 2 5 1 3 1 2 1 7 7 6", 17);
tests.put("2 7 2 7 4 7 1 7 3 7", 18);
tests.put("4 6 7 7 4 3 2 1 5 2", 10);
tests.put("5 2 5 1 2 3 4 7 7 6 2 7 1 2 3 4 5 5 4", 26);
Iterator it = tests.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
it.remove();
String[] strings = ((String)pairs.getKey()).split(" ");
int[] walls = new int[strings.length];
for (int i = 0; i < walls.length; i++){
walls[i] = Integer.parseInt(strings[i].trim());
}
System.out.println(pairs.getKey()+" result="+accumulatedWater(walls)+" expected= " +pairs.getValue());
}
}
static int accumulatedWater(int []wall){
int MAX = 0;
int start = 0;
for(int i=0;i < wall.length;i++){ //let's go to the first peak
if(wall[i] >= MAX){
MAX = wall[i];
start = i;
}else{
break;
}
}
int []accumulate_max = new int[MAX+1]; // sums up to certain height
int []accumulate_max_step = new int[MAX+1]; // steps up to certain height
Orientation going = Orientation.DOWN;
int prev = MAX;
int local_sum=0;
int total_sum=0;
int PREVPEAK = MAX;
for(int i=start+1; i< wall.length; i++){
if( i == wall.length -1 ||
wall[i] < prev && going == Orientation.UP ){
going = Orientation.DOWN;
if(wall[i-1] >= MAX){
total_sum += accumulate_max_step[MAX-1] * MAX - accumulate_max[MAX-1];
MAX = wall[i-1];
PREVPEAK = MAX;
accumulate_max = new int[MAX+1];
accumulate_max_step = new int[MAX+1];
local_sum = 0;
}else{
int indexNewPeak = (i == wall.length -1 && wall[i]> wall[i-1]) ? i : i-1;
int water = accumulate_max_step[wall[indexNewPeak]-1] * wall[indexNewPeak] - accumulate_max[wall[indexNewPeak]-1];
if(wall[indexNewPeak] > PREVPEAK){
local_sum = water;
PREVPEAK = wall[indexNewPeak];
}else{
local_sum += water;
}
}
}else if(wall[i]>prev){
going = Orientation.UP;
}
for(int j=wall[i];j <= MAX;j++){
accumulate_max[j] += wall[i];
accumulate_max_step[j] += 1;
}
prev = wall[i];
}
return total_sum + local_sum;
}
}