How to create ArrayAddition function using dart - 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();

Related

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

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

Function to find the duplicate characters in a string with their number of occurrences in the Dart language

How can we find duplicate characters in a string with their number of occurrences? The function should be generic in the Dart language.
Sample:
Input = “abcBCAacd”
Output = “a”: 3
“B” : 2 , “c” :3
void main(List<String> args) {
var input = 'abcBCAacd'.toLowerCase().split('');
var list1 = input.toSet();
var myMap = Map<String, int>.fromIterables(list1, List.generate(list1.length, (i) => 0));
input.forEach((e) => myMap[e] = myMap[e]! + 1);
print(myMap);
}
Result:
{a: 3, b: 2, c: 3, d: 1}
I had to presume you wanted the d counted, and that everything should be folded to lowercase. If B and b are in different buckets, just remove the toLowerCase() from below:
void main() {
var input = 'abcBCAacd';
var chars = input.toLowerCase().split('');
var counts = <String, int>{};
for (var char in chars) {
counts[char] = (counts[char] ?? 0) + 1;
}
print(counts);
}
void main() {
int nbOccurence = 0;
String input ="abcdeffff";
for( var i = 0 ; i < input.length; i++ ) {
nbOccurence = 0;
for( var j = 0 ; j < input.length; j++ ) {
if (input[i] == input[j]){
nbOccurence++;
}
}
print(input[i] + ":" + nbOccurence.toString());
}
}

How to make a docker image for AI created for connect 4

So I am working on creating a docker image that contains the AI for Connect 4. I have tried looking up tutorials and tried doing code but I am stuck. If you are in the defi space, you might have heard of golem network, I am currently just trying to implement Connect 4 into it. I would truly be happy with any help. Thx
Here is my code for the AI (this is currently not a docker image)
C4.AI = function(_game, _player, _strength) {
var _rack = _game.rack;
var _columns = _rack.length;
var _rows = _rack[0].length;
var _best_col = 0;
_player.human = false;
function findAndPlayMove() {
if (_game.current === _player) {
// Give the previous move's drop animation some time to finish
setTimeout(function() {
var best = alphabeta(_strength, -Infinity, Infinity, _player);
var r = _game.util.getDropRow(_best_col);
_game.trigger('drop', { col_index : _best_col });
_best_col = 0;
}, 500);
}
}
function alphabeta(depth, alpha, beta, player) {
var value = evaluateBoard(player);
// If maximum search depth is reached or this board is a win/loss we
// don't need to look further
if (depth === 0 || value === Infinity || value === -Infinity) {
return value;
}
// Calculate moves for this AI player
if (player === _player) {
var scores = [];
// For each column calculate the max possible score
// (player tries to maximize)
for (var c = 0; c < _columns; c++) {
var r = _game.util.getDropRow(c);
// This column is already full of coins
if (r === -1) continue;
// Temporarily store move
_rack[c][r] = player;
// Recursively calculate the best result this move could have
// for this player
alpha = Math.max(alpha, alphabeta(depth - 1, alpha, beta, player.opponent));
// Undo the move
delete _rack[c][r];
scores[c] = alpha;
if (beta <= alpha) break;
}
if (depth === _strength) {
var max_score = -Infinity;
var last_valid = null;
for (var i = 0; i < scores.length; i++) {
// TODO: find out why >= screws up AI
var score = scores[i];
if (score > max_score) {
max_score = score;
_best_col = i;
}
if (score) last_valid = i;
}
// All moves by player will lead to loss
// Just pick a valid column
if (max_score === -Infinity) {
_best_col = last_valid;
}
}
return alpha;
} else {
// For each column calculate the min possible score
// (opponent tries to minimize)
for (var c = 0; c < _columns; c++) {
var r = _game.util.getDropRow(c);
// This column is already full
if (r === -1) continue;
// Temporarily store move
_rack[c][r] = player;
// Recursively calculate the best result this move could have
// for oppponent
beta = Math.min(beta, alphabeta(depth - 1, alpha, beta, player.opponent));
// Undo the move
delete _rack[c][r];
// If the opponent's score for this column is <= to our player's
// maximum there's no need to further explore this branch: it
// would never lead to a better score
if (beta <= alpha) {
break;
}
}
return beta;
}
}
/* ################################################################################
UTILITIES
################################################################################ */
function evaluateBoard(player) {
// Some pre-calculated values for each rack position, based on the
// number of possible 4-in-a-rows a position could theoretically be part of
var values = [
[ 3, 4, 5, 5, 4, 3 ],
[ 4, 6, 8, 8, 6, 4 ],
[ 5, 8, 11, 11, 8, 5 ],
[ 7, 10, 13, 13, 10, 7 ],
[ 5, 8, 11, 11, 8, 5 ],
[ 4, 6, 8, 8, 6, 4 ],
[ 3, 4, 5, 5, 4, 3 ]
];
var patterns = {
'2 connected, empty on the left': {
rx: /__#{2}[^#_]/g,
value: 10
},
'2 connected, empty on the right': {
rx: /[^#_]#{2}__/g,
value: 10
},
'2 connected, empty on both sides': {
rx: /_#{2}_/g,
value: 20
},
'3 connected, empty on the left': {
rx: /_#{3}/g,
value: 50
},
'3 connected, empty on the right': {
rx: /#{3}_/g,
value: 50
},
'3 connected, empty middle left': {
rx: /#_#{2}/g,
value: 50
},
'3 connected, empty middle right': {
rx: /#{2}_#/g,
value: 50
},
'3 connected, empty on both sides': {
rx: /_#{3}_/g,
value: 100
}
};
var views = [
getSouthView(player),
getEastView(player),
getSouthWestView(player),
getSouthEastView(player)
];
var score = 0;
$.each(views, function(i, view) {
var player_view = view.replace(/X/g, '#');
var opponent_view = view.replace(/O/g, '#');
if (opponent_view.match(/#{4}/)) {
score = -Infinity;
return false;
}
if (player_view.match(/#{4}/)) {
score = Infinity;
return false;
}
$.each(patterns, function(name, pattern) {
var matches = player_view.match(pattern.rx);
if (matches) {
score += matches.length * pattern.value;
}
matches = opponent_view.match(pattern.rx);
if (matches) {
score -= matches.length * pattern.value;
}
});
});
return score;
}
function isCell(c, r) {
return 0 <= c && c < _columns && 0 <= r && r < _rows;
}
function getCellChar(c, r, player) {
var cell = _rack[c][r];
if (cell === _player) {
return 'X';
} else if (cell) {
return 'O';
}
return '_';
}
/* ################################################################################
VIEWS
################################################################################ */
function getEastView(player) {
var a = [];
for (var r = 0; r < _rows; r++) {
a.push('\n');
for (var c = 0; c < _columns; c++) {
a.push(getCellChar(c, r, player));
}
}
return a.join('') + '\n';
}
function getSouthView(player) {
var a = [];
for (var c = 0; c < _columns; c++) {
a.push('\n');
for (var r = 0; r < _rows; r++) {
a.push(getCellChar(c, r, player));
}
}
return a.join('') + '\n';
}
function getSouthWestView(player) {
var c = 0;
var r = 0;
var max = _columns * _rows;
var counter = 0;
var a = [];
a.push('\n');
while (counter != max) {
if (isCell(c, r)) {
var cell = _rack[c][r];
a.push(getCellChar(c, r, player));
counter++;
c++;
r--;
} else if (r < 0) {
a.push('\n');
r = c;
c = 0;
} else {
c++;
r--;
}
}
return a.join('') + '\n';
}
function getSouthEastView(player) {
var c = _columns - 1;
var r = 0;
var max = _columns * _rows;
var counter = 0;
var a = [];
a.push('\n');
while (counter != max) {
if (isCell(c, r)) {
var cell = _rack[c][r];
a.push(getCellChar(c, r, player));
counter++;
c--;
r--;
} else if (r < 0) {
a.push('\n');
r = _columns - c - 1;
c = _columns - 1;
} else {
c--;
r--;
}
}
return a.join('') + '\n';
}
_game.on('waitingForDrop', findAndPlayMove);
};

Dart - For looping doesn't loop

for(n = 0; n < length - 1; n++);
{
if(sbin[n] == '1'){
ctr = ctr + 1;
print(sbin[0]);
}
}
return ('Bit counter - $ctr');
It only showed the 1st letter of sbin.
main() {
print(someFunction());
}
someFunction() {
var length = 5;
var sbin = ['1', '2', '3', '4', '5'];
var ctr = 0;
for(var n = 0; n < length - 1; n++) {
if(sbin[n] == '1'){
ctr = ctr + 1;
print(sbin[0]);
}
}
return ('Bit counter - $ctr');
}
DartPad example

Resources