Generate 4 random numbers that add to a certain value in Dart - flutter

I want to make 4 numbers that add up to a certain number that is predefined.
For instance, I want four random numbers when added gives me 243.
Any type of way works as long as it works :)

this is more a math problem than a programming problem.
Maybe you can do something like this, if 0 is allowed.
var random = new Random();
final predefindedNumber = 243;
var rest = predefindedNumber;
final firstValue = random.nextInt(predefindedNumber);
rest -= firstValue;
final secondValue = rest <= 0 ? 0 : random.nextInt(rest);
rest -= secondValue;
final thirdValue = rest <= 0 ? 0 : random.nextInt(rest);
rest -= thirdValue;
final fourthValue = rest;
print("$fourthValue $secondValue $thirdValue $fourthValue");
With this implementation it´s possible to get somthing like this 243 0 0 0

This works:
import 'dart:math';
void main() {
int numberOfRandNb = 4;
List randomNumbers = [];
int predefinedNumber = 243;
for(int i = 0; i < numberOfRandNb - 1; i++) {
int randNb = Random().nextInt(predefinedNumber);
randomNumbers.add(randNb);
predefinedNumber -= randNb;
}
randomNumbers.add(predefinedNumber);
print(randomNumbers.join(' '));
}

Related

Dart find the capital word in a given String

How can I write a code that finds capital words in a given string in dart
for example
String name ='deryaKimlonLeo'
//output='KL'
Hmmm try this using pattern if you only want to get only the big letter then try this
String name ='deryaKimlonLeo';
print(name.replaceAll(RegExp(r'[a-z]'),""));
//Output you wanted will be
// KL
try this on dart pad it works
A basic way of doing this is like
void main() {
String name = 'deryaKimlonLeo';
String result = '';
for (int i = 0; i < name.length; i++) {
if (name.codeUnitAt(i) <= 90 && name.codeUnitAt(i) >= 65) {
result += name[i];
}
}
print(result);
}
More about ASCII and codeUnitAt.
sample code:
void main() {
String test = "SDFSDdsfdDFDS";
for (int i = 0; i < test.length; i++) {
if (test[i].compareTo('A') >= 0 && test[i].compareTo('Z') <= 0)
print(test[i]);
}
}

How to generate random numbers without repetition in Flutter

I need to generate random numbers to use them as index and i need the generated number to be within a range and cannot be repeated. Is there a predefined function in Flutter to do that or am i going to create my own function?
you can use the Random class and then use a Set because unlike List you don't need to do any extra checking for duplication as Set itself won't allow any duplicated element.
for example:
Set<int> setOfInts = Set();
setOfInts.add(Random().nextInt(max));
I think you could simply create a simple shuffled list of index and use removeLast() on it each time you need a new value.
var randomPicker = List<int>.generate(n, (i) => i + 1)..shuffle();
...
int random1 = randomPicker.removeLast();
int random2 = randomPicker.removeLast();
assert(random1 != random2);
Where n is your maximum index.
Use random from math library:
import 'dart:math';
Random random = new Random();
int random_number = random.nextInt(100); // from 0 up to 99
And if you want to change minimum number you can use below trick, it will select from 10 up to 99:
int randomNumber = random.nextInt(90) + 10;
If you need multiple you can add those numbers to list and check them if there is exist with contain, such as:
List<int> numberList=[];
Random random = new Random();
for (var i = 0; i == 10; i++){
int random_number = random.nextInt(100);
if (!numberList.contains(random_number)) {numberList.add(random_number);}
}
I tried using all the codes above but none solved my problem.
I created this and it worked for me:
class Utils {
static final _random = Random();
static final Set<int> _setOfInts = {};
static int randomUnique({required limit}) {
debugPrint("limit: $limit ---> ${_setOfInts.length} ${_setOfInts.toString()}");
int randomInt = _random.nextInt(limit) + 1;
if (_setOfInts.contains(randomInt)) {
return randomUnique(limit: limit);
} else {
_setOfInts.add(randomInt);
return randomInt;
}
}
}

DL4J linear regression

I am new in neural networks. I am trying to implement and train simple neural network with DL4j. My function:
y = x * 2 + 300
My vision
My result
Parameters:
public final int seed = 12345;
public final int iterations = 1;
public final int nEpochs = 1;
public final int batchSize = 1000;
public final double learningRate = 0.01;
public final Random rng = new Random(seed);
public final int numInputs = 2;
public final int numOutputs = 1;
public final double maxX = 100;//xmax = 100; ymax=500.
public final double scale = 500;//for scale out x and y.
Network configuration:
public MultiLayerConfiguration createConf() {
return new NeuralNetConfiguration.Builder()
.seed(seed)
.iterations(iterations)
.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.learningRate(learningRate)
.weightInit(WeightInit.XAVIER)
.updater(new Nesterovs(0.9))
.list()
.layer(0, new OutputLayer.Builder(LossFunctions.LossFunction.MSE)
.activation(Activation.IDENTITY)
.nIn(numInputs).nOut(numOutputs).build())
.pretrain(false).backprop(true).build();
}
Training data:
public DataSetIterator generateTrainingData() {
List<DataSet> list = new ArrayList<>();
for (int i = 0; i < batchSize; i++) {
double x = rng.nextDouble() * maxX * (rng.nextBoolean() ? 1 : -1);
double y = y(x);
list.add(
new DataSet(
Nd4j.create(new double[]{x / scale, 1}),
Nd4j.create(new double[]{y / scale})
)
);
}
return new ListDataSetIterator(list, batchSize);
}
Testing:
public void test() {
final MultiLayerNetwork net = new MultiLayerNetwork(createConf());
net.init();
net.setListeners(new ScoreIterationListener(1));
for (int i = 0; i < nEpochs; i++) {
net.fit(generateTrainingData());
}
int idx = 0;
double x[] = new double[19];
double y[] = new double[19];
double p[] = new double[19];
for (double i = -90; i < 100; i += 10) {
x[idx] = i;
y[idx] = y(i);
p[idx] = scale * net.output(Nd4j.create(new double[]{i / scale, 1})).getDouble(0, 0);
idx++;
}
plot(x, y, p);
}
Please tell me what i am doing wrong or if i have incorrect vision...
Thank you in advance,
Regards,
Minas
Take a look at this example:
https://github.com/deeplearning4j/dl4j-examples/tree/master/dl4j-examples/src/main/java/org/deeplearning4j/examples/feedforward/regression
Few tips:
Use our built in normalization tools. Don't do this yourself.
Our normalization tools allow you to normalize labels as well.
Turn minibatch off (set minibatch(false) on the neural net config near the top)
Ultimately you still aren't actually doing "minibatch learning"
Also, you're regenerating the dataset each time. There's no need to do that. Just create it once and pass it in to fit.
For visualization purposes, use the restore mechanism I mentioned earlier (This is in the example, you can pick 1 of any of the normalizers like MinMaxScalar, NormalizeStandardize,.. etc)
Your iterations are also wrong. Just keep that value at 1 and keep your for loop. Otherwise you're just overfitting and spending way more of your training time then you need to. An "iteration" is actually the number of updates you want to run per fit call on the same dataset. Next release we are getting rid of that option anyways.

Attempts to call a method in the same class not working (java)

I'm creating a random number generator which then sorts the digits from largest to smallest. Initially it worked but then I changed a few things. As far as I'm aware I undid all the changes (ctrl + z) but now I have errors at the points where i try to call the methods. This is probably a very amateur problem but I haven't found an answer. The error i'm met with is "method in class cannot be applied to given types"
Here's my code:
public class RandomMath {
public static void main(String[] args) {
String bigger = bigger(); /*ERROR HERE*/
System.out.println(bigger);
}
//create method for generating random numbers
public static int generator(int n){
Random randomGen = new Random();
//set max int to 10000 as generator works between 0 and n-1
for(int i=0; i<1; i++){
n = randomGen.nextInt(10000);
// exclude 1111, 2222, 3333, 4444, 5555, 6666, 7777, 8888, 9999, 0000
if((n==1111 || n==2222 || n==3333 || n ==4444 || n==5555)
||(n==6666 || n==7777 || n==8888 || n==9999 || n==0000)){
i--;
}
}
return n;
}
//create method for denoting the bigger number
public static String bigger(int generated){
generated = generator(); /*ERROR HERE*/
System.out.println(generated);
int[] times = new int[10];
while (generated != 0) {
int val = generated % 10;
times[val]++;
generated /= 10;
}
String bigger = "";
for (int i = 9; i >= 0; i--) {
for (int j = 0; j < times[i]; j++) {
bigger += i;
}
}
return bigger;
}
}
You have not defined a method bigger(), only bigger(int generated). Therefore, you must call your bigger method with an integer parameter.

Unity3d: Random.Range() Not working the way I intended

I'm spawning objects from a list and so-far i got them to find a parent object that's already live in the scene.The problem is Random.Range() isn't working like I want. I want the listed Objects to spawn to a random parent, instead, they're spawning to the they're parent relative to the order of the list.
Ex. 0,1,2,3,4,5,6,7,8,9 = Bad
Ex. 8,3,1,4,6,3,7,9,5,2 = Good
lol
var theRange = Random.Range(obj1.Length,obj1.Length);
for(var i: int = 0; i < theRange; i++){
var obj2 : GameObject = obj1[i];
if(obj2.transform.childCount == 0){
objfromList.transform.parent = obj2.transform;
objfromList.transform.localPosition = Vector3(0,-2,0);
}
}
Deeply thankful
Following up on my comment, it sounds like you just want a shuffle function. Here is a simple Fisher-Yates shuffle:
void shuffle(int[] a){
for(int i = a.Length-1; i>=0; i--){
int j = Random.Range(0,i);
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
void usage(){
int[] a = {0,1,2,3,4,5}; // assumes obj1.Length = 6
shuffle(a);
for(int i = 0; i < a.Length; i++){
GameObject obj2 = obj1[a[i]];
GameObject objFromList = GetNextObject(); // dummy method grabbing next list object
objFromList.transform.parent = obj2.transform;
objFromList.transform.localPosition = Vector3(0,-2,0);
}
}
This should get you part way to what you need. If the order of obj1 isn't important you can shuffle it directly instead of using a secondary array like a in my example.