I'm trying to generate two different random numbers and add those together, but Flutter doesn't seem to like my math. I keep getting the message that '+' isn't defined for the class Random.
import 'package:flutter/material.dart';
import 'dart:math';
void main() => runApp(MaterialApp(
title: 'Random Numbers',
theme: ThemeData(primarySwatch: Colors.orange),
home: MyHome(),
));
class MyHome extends StatefulWidget {
#override
_MyHomeState createState() => _MyHomeState();
}
class _MyHomeState extends State<MyHome> {
#override
Widget build(BuildContext context) {
var num1 = new Random();
for (var i = 0; i < 10; i++) {
print(num1.nextInt(10));
}
var num2 = new Random();
for (var i = 0; i < 10; i++) {
print(num2.nextInt(10));
}
//var sum = num1 + num2;
return Container();
}
}
My goal is to display it something like this: "2 + 5 = "
where the user will fill in the answer. If correct do this else do that.
The error is telling you that you're trying to add two Random objects, and not two numbers. You're printing them correctly, using nextInt() on your loops, but when you try to sum them, you're using the original variable of the type Random.
Try this:
class _MyHomeState extends State<MyHome> {
#override
Widget build(BuildContext context) {
// Instantiate a Random class object
var numGenerator = new Random();
//You don't need a second loop because it was the same exact code,
//only with a different variable name.
for (var i = 0; i < 10; i++) {
print(numGenerator.nextInt(10));
}
// Save the numbers you generated. Each call to nextInt returns a new one
var num1 = numGenerator.nextInt(10);
var num2 = numGenerator.nextInt(10);
var sum = num1 + num2;
//use num1, num2 and sum as you like
return Container();
}
}
Thank you very much Gerorge and Sorry for my abscense.
I got some help to solve this through dart
Random seed = Random();
const int MAX_VALUE = 10;
int val1 = seed.nextInt(MAX_VALUE);
int val2 = seed.nextInt(MAX_VALUE);
int sum = val1 + val2;
print('$val1 + $val2 = $sum');
Related
ArrayList List;
String FileName;
static void Main(string[] args)
{
List<int> Integers = new List<int>();
Console.WriteLine("Please pick desired list size");
Console.WriteLine("Use the respective number (1)Small, (2)Medium, (3)Large, or (4)XLarge");
int size = int.Parse(Console.ReadLine());
Randomgen(List);
}
static void Randomgen(int Size, ArrayList List)
{
StreamWriter SW = new StreamWriter(FileName); ;
switch (Size)
{
case 1:
Random random = new Random();
for (int i = 0; i < 101; i++)
{
List.Add(new Integers(random.Next(1, int.MaxValue)));
}
break;
case 2:
Random randomM = new Random();
for (int i = 0; i < 2001; i++)
{
List.Add(new Integers(randomM.Next(1, int.MaxValue)));
}
break;
case 3:
Random randomL = new Random();
for (int i = 0; i < 20001; i++)
{
List.Add(new Integers(randomL.Next(1, int.MaxValue)));
}
break;
case 4:
Random randomXL = new Random();
for (int i = 0; i < 200001; i++)
{
List.Add(new Integers(randomXL.Next(1, int.MaxValue)));
}
break;
}
}
static void populateListFromFile(string FileName, ArrayList List)
{
StreamReader Input = new StreamReader(FileName);
while (!Input.EndOfStream)
{
List.Add(new Integers(int.Parse(Input.ReadLine())));
}
Console.WriteLine("File has been successfully imported");
}
}
****Im trying to create 1 of 4 different text files based of the user selection using the switch case, with an arraylist of unsorted integers and then I want to Streamread back into an arraylist usign my populate listfrom file method, so that I may proceed to sort them later using 3 other sorting methods. the whole point is to measure the efficiency of the algorithms over different amounts of data or list sizes. the main method is giving me trouble though. Most of my knowledge is self studied so please bare with me.
So what exactly is the problem you are facing, from what I can see, your Randomgen function accepts 2 parameters which is int Size and ArrayList List. However in your call to it in Main you are only providing it with 1 parameters Randomgen(List);, therefore the whole switch case inside of that function won't work.
so i have a list of predefined numbers where each number consists of 6 numbers like this {1,2,3,4,5,6 ; 34,52,3,76,12,4 ; 53,1,4,76,23,5 ; .... }
each individual number in the group of numbers range from 1 to 99,
import 'dart:math';
main() {
var rng = new Random();
var l = new List.generate(12, (_) => rng.nextInt(100));
}
i want to generate an array of 6 different random numbers using dart in a way that it is not already present in the list of numbers i already have.
import 'dart:math';
void main() {
var listOfSets = List<Set<int>>();
final int nElementsWithMax = 99;
final int kTaken = 6;
final int requiredResults = 3;
for (int i = 0; i < requiredResults; i++) {
bool isInList = false;
Set<int> anewSet;
do {
anewSet = Set.of(listRandom(nElementsWithMax, kTaken));
isInList = listOfSets.firstWhere(
(setInList) => anewSet.intersection(setInList).length == anewSet.length,
orElse: () => null)
!= null;
} while (isInList);
listOfSets.add(anewSet);
}
print(listOfSets);
}
List<int> listRandom(int maxNumber, int numberOfGenerations) {
final random = Random();
var currentOptions = List<int>.generate(maxNumber, (i) => i);
var list = List.generate(numberOfGenerations, (_) {
final index = random.nextInt(currentOptions.length);
final result = currentOptions[index];
currentOptions.removeAt(index);
return result;
});
return list;
}
Keep in mind that you cannot exceed the combination limit defined here.
In your case, requiredResults cannot exceed (100!)/((6! * (100 - 6)!) ... some huge number
I've made the following program to simulate the classic card game "War". But when I try to run it, it experiences stack overflow. Why? I thought my algorithm was as effective as it could be. Another weird thing that happens is that 1 out of 10 times the program will finish, returning a VERY low vale for the round count (around 26). The code is as follows:
Firstly, I have a class named Card.
package {
public class Card {
public var cardName:String;
public var suit:String;
public var number:int;
public function Card() {
}
}
}
Then I have the following code:
import flash.utils.getDefinitionByName;
var cardDeck:Array = new Array();
var suits:Array = new Array();
suits = ["Hearts", "Clubs", "Spades", "Diamonds"];
for each (var suit in suits)
{
for (var a = 1; a <= 13; a++)
{
var card:Card = new Card();
card.cardName = suit + a;
card.number = a;
card.suit = suit;
cardDeck.push(card);
}
}
var shuffledCardDeck:Array = new Array();
var randomPos:int = 0;
for (var b = 0; b < 52; b++) {
randomPos = Math.random()*cardDeck.length;
shuffledCardDeck[b] = cardDeck[randomPos];
cardDeck.splice(randomPos, 1);
}
var handOne:Array = new Array();
var handTwo:Array = new Array();
for (var c = 0; c < 26; c++) {
handOne.push(shuffledCardDeck[c]);
}
for (var d = 26; d < 52; d++) {
handTwo.push(shuffledCardDeck[d]);
}
var roundCount:int;
round();
function round() {
roundCount+=1;
var cardOne:Card = handOne[0];
var cardTwo:Card = handTwo[0];
if (cardOne.number < cardTwo.number) {
// Player two wins
handTwo.push(cardOne);
handOne.splice(0, 1);
} else if (cardOne.number > cardTwo.number) {
// Player one wins
handOne.push(cardTwo);
handTwo.splice(0, 1);
} else {
// Draw
handOne.splice(0,1)
handOne.push(cardOne);
handTwo.splice(0,1)
handTwo.push(cardTwo);
}
if (handOne.length == 0 || handTwo.length == 0) {
trace("Good game")
} else {
round();
}
}
trace(roundCount);
Flash runtime’s maximum recursion limit is default 1000, but can be set via the compiler argument default-script-limits. Instead of just recursion, call the function in an interval to prevent such stack overflow. It will be helpful even when you decide to show visually the process to the gamers.
setTimeout(round,50); //in place of round();
Source: http://www.designswan.com/archives/as3-recursive-functions-vs-loop-functions.html
I want to know how I can get out everyone of the the longest persons if there are several with the same length?
If only one person is the longest, then it works fine and the longest person with it´s name will show in MessageBox. But if there are more than one who are the longest, this code will not work...
public partial class Form1 : Form
{
int[] längdArray = new int[5];
string[] namnArray = new string[5];
int namn = 0;
int längd = 0;
public Form1()
{
InitializeComponent();
}
private void btnVisa_Click(object sender, EventArgs e)
{
int längst = 0;
int längdvärdet = 0;
int längdindex = 0;
string name = textBox1.Text;
namnArray[namn] = name;
namn = namn + 1;
textBox1.Clear();
int centimeter = int.Parse(textBox2.Text);
längdArray[längd] = centimeter;
längd++;
textBox2.Clear();
listBox1.Items.Add(name + " " + centimeter + " centimeter ");
if (längd == 5)
{
btnVisa.Enabled = false;
foreach (int antalLängder in längdArray)
{
if (antalLängder > längst)
{
längst = antalLängder;
längdvärdet = längdindex;
}
längdindex++;
}
string test = namnArray[längdvärdet]
MessageBox.Show(" Längsta person är " + test + " som är " + längst + " centimeter lång ");
}
Define behavior you want your app to present when there is more than one person. Should all display, or any one, or other? Try to use object constructions, it's easier to operate on them. C# is an object-oriented language. Put name and length in one structure then use LINQ.
I need a suggestion. I want to have a function that returns random numbers from let say 1 to 100, with condition to not repeat the chosen number. It is something like chess table that will be filled with something random and not one thing over another thing... If someone can tell a suggestion I'll be very happy. Thanks.
Create an Array of 100 numbers (1..100), then 'sort' the Array by 'random'. You can then pull out the numbers one at a time working your way through the array.
I haven't tested the code below but I had these snippets available that you could piece together to achieve the intended result.
public static function randomNumber(min:Number, max:Number):Number{
var rnd:Number = Math.floor((Math.random()*((max+1)-min))+min);
return rnd;
}
public static function randomize(arr:Array):Array{
var len:Number = arr.length;
var rnd:Number;
var tmp:Object;
for(var i:Number=0;i<len;i++){
rnd = randomNumber(0,(len-1));
tmp = arr[i];
arr[i] = arr[rnd];
arr[rnd] = tmp;
}
return arr;
}
var setOfNumbers:Array = new Array();
for(var i:int=0;i<100;i++){
setOfNumbers[i] = (i+1);
}
var shuffledSetOfNumbers:Array = randomize(setOfNumbers);
Notes:
For the purists this "randomizing" isn't "truly" random (if you're writing a Card shuffler for a Vegas gambling machine you'll want to use something different - case in point!)
My randomNumber and randomize functions above are static as I've typically included them that way in the apps I've needed them but you don't have to use it this way
My original lib used Number vs int or uint for some of the variables for more options when used but feel free to clean that up
also like that...
package
{
import flash.display.Sprite;
import flash.events.Event;
/**
* ...
* #author Vadym Gordiienko
*/
public class Main extends Sprite
{
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
var startArray:Array = generateNumberArray(100);
var randomArray:Array = randomArray(startArray);
trace("startArray = " + startArray);
trace("randomArray = " + randomArray);
}
/**
* generate Array of numbers by length
* #param length
* #return Array of numbers
*/
public static function generateNumberArray(length:int):Array
{
var numberArray:Array = [];
for (var i:int = 0; i < length; i++)
{
numberArray[i] = i+1;
}
return numberArray;
}
/**
* generate randomly mixed array by input array
* #param inputArray - simple not mixed array
* #return Array - mixed array
*/
public static function randomArray(inputArray:Array):Array
{
var randomArray:Array = [];
var tempArray:Array = [];
for (var i:int = 0; i < inputArray.length; i++)
{
tempArray.push(inputArray[i]);
}
while (tempArray.length)
{
var randomNumber:int = Math.round(Math.random() * (tempArray.length - 1));// get random number of left array
randomArray.push( tempArray[randomNumber] );
tempArray.splice(randomNumber, 1); // remove randomed element from temporary aarray
}
tempArray = null;
delete [tempArray];
return randomArray;
}
}
}