I built a function to calculate a price of an item each year. But my function won't read one of it's variable - dart

I created a function to calculate the selling price of an item. Each year, the price of the item will decrease by 3/4 of its original price. The problem with my function is it doesn't want to read the year variable regardless of its value. My function always returns 60000000. Can someone please tell me what's wrong with it?
int add(double year, double price) {
int i = 0;
while (i < year) {
double final_price = price * 3 / 4;
i++;
return final_price.round();
}
}
void main(List<String> arguments) {
double x = 3;
double y = 80000000;
int result = add(x, y);
print(result);
}

int add(double year, double price) {
int i = 0;
double final_price=price; // change 1
while (i < year) {
final_price = final_price* 3 / 4; // change 2
i++;
}
return final_price.round(); // change 3
}
void main(List<String> arguments) {
double x = 3;
double y = 80000000;
int result = add(x, y);
print(result);
}
Here you go. Returning a value from inside the while loop will stop the function execution on the first traversal only.
Also you need to make final price equal to price because final_price's value is not being changed as price remains same and i increases.

what actually are you to trying to do ?
I fixed your code
int add(double year, double price) {
int i = 0;
double final_price = 0 ;
while (i < year) {
double f = price * 3 / 4;
i++;
final_price = f ;
}
return final_price.round();
}
void main() // you try to pass an arguments that never used I remove it
{
double x = 3;
double y = 800000;
int result = add(x, y);
print(result);
}

Related

Dart store prime numbers in array

May I know how to store the N prime numbers, which I got from for loop in an array in dart?
import 'dart:io';
void main() {
// print('enter a start number');
// int a = int.parse(stdin.readLineSync()!);
print('enter a number');
int b = int.parse(stdin.readLineSync());
print('this are prime numbers');
primenum(b);
var z = '';
}
primenum(b) {
String string = "";
int a = 2;
outerLoop:
for (int i = a; i <= b; i++) {
for (int x = 2; x <= i / a; x++) {
if (i % x == 0) {
continue outerLoop;
}
}
var z = i.toString();
// print(z);
var h = z;
// String str = '';
string = string + h;
}
List d = string.split('');
print(d);
}
Using the above code, I am able to get those numbers in List. But the double-digit numbers are splitting.
May I know How to solve the above task? using dart.
The way you're doing string.split is splitting the string into a list of each individual character. Instead, you can add each prime number to a List directly without doing string manipulation.
primenum(b) {
List<String> d;
int a = 2;
outerLoop:
for (int i = a; i <= b; i++) {
for (int x = 2; x <= i / a; x++) {
if (i % x == 0) {
continue outerLoop;
}
}
d.add(i.toString());
}
print(d);
}

Network Delay Problem - Complexity Analysis

Below is a solution Network delay problem of leetcode. I have written a all test case success solution. But not able to analyse the time complexity. I believe its O(V^2 + E) where V is the number of nodes and E edges.
In this solution though I am adding all adjacents of each node every time, but not processing them further if there exists a min distance for that node already.
Leetcode question link https://leetcode.com/problems/network-delay-time
public int networkDelayTime(int[][] times, int n, int k) {
int[] distances = new int[n+1];
Arrays.fill(distances , -1);
if(n > 0){
List<List<int[]>> edges = new ArrayList<List<int[]>>();
for(int i = 0 ; i <= n ; i++){
edges.add(new ArrayList<int[]>());
}
for(int[] time : times){
edges.get(time[0]).add(new int[]{time[1] , time[2]});
}
Queue<Vertex> queue = new LinkedList<>();
queue.add(new Vertex(k , 0));
while(!queue.isEmpty()){
Vertex cx = queue.poll();
int index = cx.index;
int distance = cx.distance;
//process adjacents only if distance is updated
if(distances[index] == -1 || distances[index] > distance){
distances[index] = distance;
List<int[]> adjacents = edges.get(index);
for(int[] adjacent : adjacents){
queue.add(new Vertex(adjacent[0] , adjacent[1]+distance));
}
}
}
}
int sum = 0;
for(int i = 1 ; i <= n; i++){
int distance = distances[i];
if(distance == -1){
return -1;
}
sum = Math.max(sum , distance);
}
return sum;
}
public static class Vertex{
int index;
int distance;
public Vertex(int i , int d){
index = i;
distance = d;
}
}
You should use PriorityQueue instead of LinkedList

leetcode practice: can find the bug of returning a negative number from sum method

I am trying to solve 445. Add Two Numbers II from LeetCode where it is asked:
Given two non-empty linked lists representing two non-negative integers, add the two numbers and return it as a linked list. The most significant digit comes first and each of their nodes contain a single digit.
For some test cases, I am getting negative number from the sum method that I have implemented. I think it is impossible to get any negative digit in my code. Can you help me finding the bug?
Below is the code that I tried:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//ListNode previous = null;
int len1 = 0;
int len2 = 0;
ListNode head1 = l1;
ListNode head2 = l2;
while(l1!=null){
len1++;
l1=l1.next;
}
while(l2!=null){
len2++;
l2=l2.next;
}
int sum=0;
if (len1 >= len2){
sum= sum(head1,head2,len1,len2);
}else{
sum= sum(head2,head1,len2,len1);
}
String sumString = "" + sum;
ListNode extraHead = new ListNode(1);
ListNode copy = extraHead;
for(int i = 0;i<sumString.length();i++){
ListNode bit = new ListNode(Integer.parseInt(String.valueOf(sumString.charAt(i))));//Integer.parseInt(String.valueOf(sumString.charAt(i)))
extraHead.next = bit;
extraHead = extraHead.next;
}
return copy.next;
}
public int sum(ListNode l1, ListNode l2, int len1, int len2){
int diff = 0;
int resLen = 0;
diff = len1 - len2;
resLen = len1;
int[] res = new int[resLen];
ListNode fast = l1;
ListNode slow = l2;
for(int count = 0; count<diff; count++){
res[count] = fast.val;
fast = fast.next;
}
for(int count = diff;count < res.length;count++){
res[count] = fast.val + slow.val;
fast=fast.next;
slow=slow.next;
}
int sum = 0;
for(int i = len1;i>0;i-- ){
sum = sum + res[len1-i] * (int)Math.pow(10,i-1);
}
return sum;
}
}
Here is the error message that I get:
Error Details
java.lang.NumberFormatException: For input string: "-"
at line 68, java.base/java.lang.NumberFormatException.forInputString
at line 648, java.base/java.lang.Integer.parseInt
at line 776, java.base/java.lang.Integer.parseInt
at line 41, Solution.addTwoNumbers
at line 54, __DriverSolution__.__helper__
at line 87, __Driver__.main
Here is the input causing the error:
[3,9,9,9,9,9,9,9,9,9]
[7]

How to generate 6 digit random number

I want to generate a random six-digit number. I tried to use the Random class, but new Random().nextInt(999999) generates some numbers with less than six digits.
So you want just the numbers 100000 to (and including) 999999.
you can get a random number in this range (900000) and add 100000 to the random number you get:
var rng = new Random();
var code = rng.nextInt(900000) + 100000;
This will always give you a random number with 6 digits.
void main() {
var rnd = new math.Random();
var next = rnd.nextDouble() * 1000000;
while (next < 100000) {
next *= 10;
}
print(next.toInt());
}
you can also generate 6 different numbers and then concatenate them in one string and convert it to integer if you want
import 'dart:math';
main(){
var rndnumber="";
var rnd= new Random();
for (var i = 0; i < 6; i++) {
rndnumber = rndnumber + rnd.nextInt(9).toString();
}
print(rndnumber);
}
Here is a Dart extension method that will generate a non-negative random integer with a specified number of digits:
extension RandomOfDigits on Random {
/// Generates a non-negative random integer with a specified number of digits.
///
/// Supports [digitCount] values between 1 and 9 inclusive.
int nextIntOfDigits(int digitCount) {
assert(1 <= digitCount && digitCount <= 9);
int min = digitCount == 1 ? 0 : pow(10, digitCount - 1);
int max = pow(10, digitCount);
return min + nextInt(max - min);
}
}
In your case use it like this:
final random = Random();
print(random.nextIntOfDigits(6));
The following class will generate an integer with 'n' digits, or a string with 'n' digits.
The numeric method will be much faster, but is limited in the number of digits.
import 'dart:math';
class RandomDigits {
static const MaxNumericDigits = 17;
static final _random = Random();
static int getInteger(int digitCount) {
if (digitCount > MaxNumericDigits || digitCount < 1) throw new RangeError.range(0, 1, MaxNumericDigits, "Digit Count");
var digit = _random.nextInt(9) + 1; // first digit must not be a zero
int n = digit;
for (var i = 0; i < digitCount - 1; i++) {
digit = _random.nextInt(10);
n *= 10;
n += digit;
}
return n;
}
static String getString(int digitCount) {
String s = "";
for (var i = 0; i < digitCount; i++) {
s += _random.nextInt(10).toString();
}
return s;
}
}
void main() {
print(RandomDigits.getInteger(6));
print(RandomDigits.getString(36));
}
Output:
995723
198815207332880163668637448423456900
If you want to get 6 digit value from 0 to 999999, you can add leading 0 if the number is less than 6 digits.
String r = Random().nextInt(999999).toString().padLeft(6, '0');
// example output: 025328
i had the same problem.although there are 3-4 ways to tackle it but i find the below one simple and sorted.
simply check for the number of length match. find below code
Integer otp = new Random().nextInt(999999);
int noOfOtpDigit=6;
while(Integer.toString(otp).length()!=noOfOtpDigit) {
otp = new Random().nextInt(999999);
}
String otpString = String.valueOf(otp);
import 'dart:math';
void main() {
print(get6DigitNumber());
}
String get6DigitNumber(){
Random random = Random();
String number = '';
for(int i = 0; i < 6; i++){
number = number + random.nextInt(9).toString();
}
return number;
}
Here is your unlimited supply of six-digit random numbers
String getRandomNumber(){
final r = Random();
return List<int>.generate(6, (index) => r.nextInt(10)).fold<String>("", (prev, i) => prev += i.toString());
}
This is working for me in C#.
Random random = new Random();
string elementIndex = random.Next(100000, 999999).ToString();

How to get a random number from range in dart?

How does one get a random number within a range similar to c# Random.Next(int min, int max);
import 'dart:math';
final _random = new Random();
/**
* Generates a positive random integer uniformly distributed on the range
* from [min], inclusive, to [max], exclusive.
*/
int next(int min, int max) => min + _random.nextInt(max - min);
Range can be found with a simple formula as follows
Random rnd;
int min = 5;
int max = 10;
rnd = new Random();
r = min + rnd.nextInt(max - min);
print("$r is in the range of $min and $max");
You can achieve it via Random class object random.nextInt(max) . The nextInt() method requires a max limit. The random number starts from 0 and the max limit itself is exclusive.
import 'dart:math';
Random random = new Random();
int randomNumber = random.nextInt(100); // from 0 upto 99 included
If you want to add the min limit, add the min limit to the result
int randomNumber = random.nextInt(90) + 10; // from 10 upto 99 included
This is really late, but this for anyone who still has the question.
The easiest way to get a random number between a min and a max is the following :
import 'dart:math';
int max = 10;
int randomNumber = Random().nextInt(max) + 1;
The math module in dart has a function called nextInt. This will return an integer from 0 (including 0 ) to max - 1 ( exluding max ). I want a number 1 to 10, hence I add 1 to the nextInt result.
Generates a random integer uniformly distributed in the
range from [min] to [max], both inclusive.
int nextInt(int min, int max) => min + _random.nextInt((max + 1) - min);
It can be achieved exactly as you intended by creating extension on int to get random int value. For example:
import 'dart:math';
import 'package:flutter/foundation.dart';
extension RandomInt on int {
static int generate({int min = 0, #required int max}) {
final _random = Random();
return min + _random.nextInt(max - min);
}
}
And you can use this in your code like so:
List<int> rands = [];
for (int j = 0; j < 19; j++) {
rands.add(RandomInt.generate(max: 50));
}
Note that static extension methods can't be called on type itself (e.g. int.generate(min:10, max:20)), but instead you have to use extension name itself, in this example RandomInt. For detailed discussion, read here.
import 'dart:math';
Random rnd = new Random();
// Define min and max value
int min = 1, max = 10;
//Getting range
int num = min + rnd.nextInt(max - min);
print("$num is in the range of $min and $max");
To generate a random double within a range, multiply a random int with a random double.
import 'dart:math';
Random random = new Random();
int min = 1, max = 10;
double num = (min + random.nextInt(max - min)) * random.nextDouble();
To Generate a random positive integer between a given range:
final _random = new Random();
// from MIN(inclusive), to MAX(exclusive).
int randomBetween(int min, int max) => min + _random.nextInt(max - min);
// from MIN(inclusive), to MAX(inclusive).
int randomBetween(int min, int max) => min + _random.nextInt((max+1) - min);
// from MIN(exclusive), to MAX(exclusive).
int randomBetween(int min, int max) => (min+1) + _random.nextInt(max - (min+1));
When I was making a Tetris game, I had to rotate the x-axis. For this, I wrote the following codes.
I hope it will be useful for you too:
Random rnd = Random();
int min = 0;
int max = 23;
class Block {
int x = min + rnd.nextInt(max - min);
}
A simpler way of doing this is to use the nextInt method within Random:
// Random 50 to 100:
int min = 50;
int max = 100;
int selection = min + (Random(1).nextInt(max-min));
https://api.dartlang.org/stable/2.0.0/dart-math/Random-class.html

Resources