Dart store prime numbers in array - dart

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);
}

Related

Quick sort throws a 'not in inclusive range' error but sometimes it works. (Dart)

I have implemented a quick sort algorithm in Dart which sorts a list of random integers in the range from 0 to 100. Most of the times, it throws a 'not in inclusive range' exception. Other times, it works. I don't understand what is wrong with my code or logic here.
import 'dart:math';
List<int> list = [];
void main() {
randomize();
quickSort(0, list.length - 1);
print(list);
}
void randomize() {
for (int i = 0; i < 100; ++i) {
list.add(Random().nextInt(100));
}
}
void quickSort(int l, int h) {
if (l < h) {
int mid = partition(l, h);
quickSort(l, mid - 1);
quickSort(mid + 1, h);
}
}
int partition(int l, int h) {
int pivot = l;
int i = l;
int j = h;
while (i < j) {
while (list[i] <= list[pivot]) {
++i;
}
while (list[j] > list[pivot]) {
--j;
}
if (i < j) {
int temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
int temp = list[pivot];
list[pivot] = list[j];
list[j] = temp;
return j;
}

How I can solve this problem? "The argument type 'int?' can't be assigned to the parameter type 'num'." (Dart)

I'm trying to write a code which print the sum of odd and even numbers from a group of inputs, but it doesn't work and I think it's a null safety issue.
This is the code
void main() {
List numbers = [1, 2, 3, 4];
List odd = [];
List even = [];
for (int i = 0; i < numbers.length; i++) {
var z = numbers[i] % 2;
if (z == 0) {
even.add(numbers[i]);
} //end if
else {
odd.add(numbers[i]);
} //end else
} //end for loop
int sumOdd = 0;
int sumEven = 0;
for (int i = 0; i < odd.length; i++) {
sumOdd = sumOdd + odd[i];
}//end for
for (int i = 0; i < even.length; i++) {
sumEven = sumEven + even[i];
}//end for
print("sum of odds numbers = $sumOdd");
print("sum of even numbers = $sumEven");
} //end main
i think its because you not specify the type of list.
by default it will define as a list of number.
but int sumOdd = 0; you define as integer.
thats why you got error when run here : sumOdd = sumOdd + odd[i];
sumOdd is integer
odd[i] is number .
solution:
List<int> numbers = [1, 2, 3, 4];
List <int> even =[];
List<int> odd =[];
second solution
you can parse odd[i] to integer

How to create ArrayAddition function using dart

What is the right syntax in dart for the below js code:
I am trying to create a function ArrayAddition(arr) take the array
of numbers stored in arr and return the string true if any combination of numbers
in the array can be added up to equal the largest number in the array, otherwise
return the string false. For example: if arr contains [4, 6, 23, 10, 1, 3] the
output should return true because 4 + 6 + 10 + 3 = 23.
function ArrayAddition(arr) {
arr.sort(function(a,b){return a - b});
var maxNum = arr.pop();
var tot = 0;
for (var i = 0; i < arr.length; i++){
tot += arr[i];
for (var j = 0; j < arr.length; j++){
if (i != j) {
tot += arr[j];
if (tot == maxNum) {
return true;
}
}
}
for (var k = 0; k < arr.length; k++) {
if (i != k) {
tot -= arr[k];
if (tot == maxNum) {
return true;
}
}
}
tot = 0;
}
return false;
}
So what is the rightt syntax for this in dart language?
It's almost the exact same code, just change the following lines:
function ArrayAddition(arr) {
to
bool ArrayAddition(List<int> arr) {
arr.sort(function(a,b){return a - b});
to
arr.sort((a, b) => a - b);
var maxNum = arr.pop();
to
var maxNum = arr.removeLast();

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();

Resources