Why doesn't this add? - dart

I've been having difficulty replicating a piece of code that runs in Pascal into dart. The program asks for the scores of two teams to be entered, added and the totals displayed in the end. I managed to get all inputs and outputs, but the addition within the for loop outputs 0 or null. Any advice?
import "dart:io";
import "dart:math";
import "dart:convert";
void main() {
double pscore1 = 0;
double Totscore1 = 0;
print('Enter enter team 1 name');
String? Team_one_Name = stdin.readLineSync();
print('Enter enter team 2 name');
String? Team_two_Name = stdin.readLineSync();
for (int i = 0; i < 5; i++) {
print('Enter team 1 player score');
double pscore1 = double.parse(stdin.readLineSync()!);
double Totscore1 = (Totscore1 + pscore1);
}
print(' The total score is ${Totscore1}');
}
This is only for one score. Thanks in advance.

You are declaring new variables in your for loop instead of using the variables defined in your main() method. Since your new variables is named the same, they will "shadow" your other variables since Dart's scoping rules means that when we refer to something, we start searching from current scope and then get up one level at a time until we hit global scope:
Instead, try do the following:
import "dart:io";
import "dart:math";
import "dart:convert";
void main() {
double pscore1 = 0;
double totscore1 = 0;
print('Enter enter team 1 name');
String? Team_one_Name = stdin.readLineSync();
print('Enter enter team 2 name');
String? Team_two_Name = stdin.readLineSync();
for (int i = 0; i < 5; i++) {
print('Enter team 1 player score');
pscore1 = double.parse(stdin.readLineSync()!);
totscore1 = totscore1 + pscore1;
}
print(' The total score is ${totscore1}');
}
(I renamed your Totscore1 to totscore1 since variables should NEVER start with a cased letter in Dart if we follow the normal naming conventions)

Related

How to remove previous printed line from Console in Dart

How I can remove previously printed line in console with print() in Dart?
I am willing to display a progress indicator such as:
int n = 0;
for (var item in list) {
n++;
print('${(n / list.length * 100).toStringAsFixed(0)}%');
// do something
}
Currently it prints:
1%
2%
3%
...
But I would like to delete the previous line and replace it with the newly calculated percent.
print always adds a newline, but you can write directly to stdout to avoid that.
To overwrite the previous line, you can place a carriage return ('\r') character at the start of your string, which tells the cursor to return to the beginning of the line. You may also want to pad the end of your string with some spaces to overwrite any text which might still be remaining from the previous write, although that's not necessary in this case.
It may look something like this in the end:
// At top of file
import 'dart:io';
int n = 0;
for (var item in list) {
n++;
stdout.write('\r${(n / list.length * 100).toStringAsFixed(0)}%');
// do something
}
You can use dart:io and a carriage return (\r):
import "dart:io";
void main() {
for (int i = 0; i < 5; i++) {
stdout.write("\r $i");
}
}

dynamically assigning number after looping through list of names in dart

I was practicing for loop and lists and I was having a little problem assigning dynamic
number after looping through a list of names.
example: i have a list of names:
final list = ['liam','james','jerry','owen'];
and i was trying to achieve this output below:
1.liam
2.james
3.jerry
4.owen
but i keep getting this:
1. liam
1. james
1. jerry
1. owen
2. liam
2. james
2. jerry
2. owen
3. liam
3. james
3. jerry
3. owen
4. liam
4. james
4. jerry
4. owen
this is my code below:
void main() {
final list = ['liam','james','jerry','owen'];
if(list.isNotEmpty){
for(var i =1;i<=list.length;i++){
final count =i;
for(var name in list){
print('$count. $name');
}
}
}
}
You have two loops in your code, thus making the names repeat.
You only need to use one loop, and access the names using list[i]:
void main() {
final list = ['liam', 'james', 'jerry', 'owen'];
if (list.isNotEmpty) {
for (var i = 0; i < list.length; i++) {
print('${i + 1}. ${list[i]}');
}
}
}
Simply, it's just like that
void main() {
final list = ['liam','james','jerry','owen'];
if(list.isNotEmpty){
for(var i = 0; i <= list.length; i++){
print(((i+1).toString()) + '.'+ list[i]);
}
}
}

How can I ask the user of any program for a value in Swift?

In JS it is called "prompt", but it is obviously not the same keyword in Swift. So my problem actually is that I want to ask the user of any program for a value. So how do I ask him and how do I safe that answer into a variable?
So this is how I would write it in Javascript for example when I want to use the input as a value for my calculations:
var n1 = prompt("give me a value");
var n2 = 3;
var i = 0;
var sum = 0;
while(i < n1){
sum = sum + n2;
i += 1;
}
document.write(sum)
And now I don't really know how to write the same in swift. I just want to ask the user for a value in "n1".
var n1 = 9;
var n2 = 5;
var i = 0;
var sum = 0;
while(i < n1){
sum = sum + n2;
i += 1;
}
print(sum)
How shall I write this in "var n1" ?
You can do it in Command Line Tool.
Create New project - mac os tab - Command Line Tools.
You can ask user for input using readLine().
let a = readLine()
if let input = a {
print(input)
}

How to do BigInt arithmetic in Dart 2.x, specifically division?

Dart documentation says that BigInt division returns a value of type 'double'. This is a problem. To illustrate, here are two implementations of an algorithm involving division. The first is in Kotlin, the second is in Dart. The Dart version runs accurately for small numbers but loses precision for larger numbers.
Kotlin
import java.math.BigInteger
fun height(n: BigInteger, m: BigInteger): BigInteger {
var m1 = m
var s = BigInteger("1")
var b = BigInteger("1")
var ans = BigInteger("0")
var i = 0
while (i < n.toInt()) {
s *= m1--
s /= b++
ans += s
i++
}
return ans
}
Dart
BigInt height(int n, int m) {
var m1 = m; // new BigInt.from(m);
var s = 1.0; // new BigInt.from(1);
var b = 1.0; // new BigInt.from(1);
var ans = new BigInt.from(0);
var i = 0;
while (i < n) {
s *= m1--;
s /= b++;
ans += BigInt.from(s);
i++;
}
return ans;
}
As you can see from the commented out Dart code, I have tried various ways to use BigInt.
Here is an example input with answer. The erroneous Dart answer is given below.
height(13, 550),
equals(BigInt.parse('60113767426276772744951355')));
The erroneous Dart answer is --> 60113767426276764034189615
Can someone show me the best way to do the job in Dart v2.x?
The following code works.
BigInt height(int n, int m) {
var m1 = new BigInt.from(m);
var s = new BigInt.from(1);
var b = new BigInt.from(1);
var ans = new BigInt.from(0);
var i = 0;
while (i < n) {
s *= m1;
m1 -= new BigInt.from(1);
s = s ~/ b;
b += new BigInt.from(1);
ans += s;
i++;
}
return ans;
}
Changes:
x++ and x-- are equivalent to x = x + 1 and x = x - 1 but BigInt.+ and BigInt.- only accept BigInt values... so there's a compiler error.
BigInt./ returns a double and this is not what you want here. You need to use the BigInt.~/ operator instead.

flutter how to generate random numbers without duplication

Is there any way to generate random numbers without duplication?
For instance I want to generate 50 random numbers from 1 to 100 no duplication, any way to do this or do I have to check every time incoming number is already created or not?
you can use shuffle as following code.
import 'dart:math';
var list = new List<int>.generate(10, (int index) => index); // [0, 1, 4]
list.shuffle();
print(list);
You can use Set. Each object can occur only once when using it. Just try this:
Set<int> setOfInts = Set();
while (setOfInts.length < 50) {
setOfInts.add(Random().nextInt(range) + 1);
}
You can read the documentation here: Set Doc
Here is an alternative that avoids creating an array of all the possible values, and avoids repeatedly looping until no collision occurs. It may be useful when there is a large range to select from.
import 'dart:math';
class RandomList {
static final _random = new Random();
static List<int> uniqueSample({int limit, int n}) {
final List<int> sortedResult = [];
final List<int> result = [];
for (int i = 0; i < n; i++) {
int rn = _random.nextInt(limit - i); // We select from a smaller list of available numbers each time
// Increment the number so that it picks from the remaining list of available numbers
int j = 0;
for (; j < sortedResult.length && sortedResult[j] <= rn; j++) rn++;
sortedResult.insert(j, rn);
result.add(rn);
}
return result;
}
}
I haven't tested it exhaustively but it seems to work.

Resources