Dart - For looping doesn't loop - dart

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

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

Why am I getting wrong answer for this SPOJ Question

I still dont know weather I am allowed discuss Competetive Programming Doubts here, please let me know..
Can someone help me on this SPOJ question, I am getting wrong Answer:
https://www.spoj.com/problems/SPIKES/
I have tried all the test cases I could think of and the code always gives correct output.
Before posting it here, I also asked it in spoj forum but Its been two days, no one replies...
#include<bits/stdc++.h>
using namespace std;
// # = 35
// # = 64
// . = 46
// s = 115
// Using Dijkstra to find the path with minimum no. of Spikes
int n,m,j;
const int N = 100;
const int INF = 9;
vector<int> g[N];
int vis[N][N];
pair<int,int> dist[N][N];
vector<pair<int,int>> movements = {
{0,1},{0,-1},{1,0},{-1,0}
};
bool isvalid(int i, int j){
return i>=0 && j>=0 && i<n && j<m;
}
void bfs(int sourcei, int sourcej){
set<pair<int,pair<int,int>>> q;
q.insert({0,{sourcei,sourcej}});
dist[sourcei][sourcej] = {0,INF};
while(q.size()>0){
auto curr_v = *q.begin();
int curr_i = (curr_v.second).first;
int curr_j = (curr_v.second).second;
int spikes = curr_v.first;
q.erase(q.begin());
if(vis[curr_i][curr_j]) continue;
vis[curr_i][curr_j] = 1;
for(auto m : movements){
int child_i = curr_i + m.first;
int child_j = curr_j + m.second;
int spikec = spikes;
if(!isvalid(child_i,child_j)) continue;
if(g[child_i][child_j] == 115) spikec = spikes+1;
if(vis[child_i][child_j]) continue;
if(g[child_i][child_j]==35) continue;
if(dist[child_i][child_j].second > spikec){
dist[child_i][child_j] = {(dist[curr_i][curr_j].first +1),spikec};
q.insert({spikec , {child_i,child_j}});
}
}
}
}
int main(){
cin>>n>>m>>j;
int start_j,start_i;
int end_j,end_i;
for (int i = 0; i < N; ++i){
for (int j = 0; j < N; ++j){
dist[i][j].second = INF;
dist[i][j].first = 0;
}
}
for (int i = 0; i < n; ++i){
for (int j = 0; j < m; ++j){
char x; cin>>x;
g[i].push_back((int)x);
if(x=='#') {
start_i = i;
start_j = j;
}
if(x=='x'){
end_i = i;
end_j = j;
}
}
}
bfs(start_i,start_j);
// for (int i = 0; i < n; ++i){
// for (int j = 0; j < m; ++j){
// cout<<dist[i][j].first<<","<<dist[i][j].second<<" ";
// }cout<<endl;
// }
if(dist[end_i][end_j].second <= (int)j/2) cout<<"SUCCESS"<<endl;
else cout<<"IMPOSSIBLE"<<endl;
return 0;
}

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

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

Boxing Detected Objects in OpenCV

I am currently implementing a connected components algorithm and the last step of the algorithm requires me to enclose the objects I found in a box. I have attempted to enclose an object in a box and this is the result:
As you can see some of them seem to be enclosed in a box. Some of the lines of the box are not seen unless I stretch the windows of the imshow function's output and also some of them have color when I expected a line with a shade of gray.
My question is: Is the object really getting enclosed since I remember when I ran a similar code of mine into a different OS the lines with color are not see at all but are seen in my computer. Additionally, why are some of the lines in a different color given that I was expecting a shade of gray.
Mat src, src_gray;
Mat dst, detected_edges;
const char* window_name = "THRESHOLDED IMAGE";
/**
* #function connectedComponent
*/
static void connectedComponent(int, void*)
{
Mat test; //dummy
Mat sub;
int newObject = 0;
int zeroTest = 0, nonZero = 0;
int arr[5] = {0,0,0,0,0};
/// Reduce noise with a kernel 3x3
blur( src_gray,detected_edges, Size(3,3) ); //filtering out of noise
namedWindow("INITIAL", WINDOW_NORMAL);
imshow("INITIAL",detected_edges);
resizeWindow("INITIAL", 300, 300);
threshold(detected_edges, detected_edges, 0,255, THRESH_BINARY | THRESH_OTSU);
int** newSub = new int*[detected_edges.rows];
for(int i = 0; i < detected_edges.rows; i++)
newSub[i] = new int[detected_edges.cols];
for(int i = 0; i < detected_edges.rows; i++){
for(int j = 0; j < detected_edges.cols; j++){
newSub[i][j] = 0;
}
}
/*INITIAL MARKING LOOP*/
for(int i = 0; i < detected_edges.rows; i++){
for(int j = 0; j < detected_edges.cols; j++){
if(detected_edges.at<uchar>(i,j) == 0){
if(i-1 < 0 && j-1 < 0){
newObject = newObject + 1; //no values
newSub[i][j] = newObject;
}else if(i-1 >= 0 && j-1 < 0){
if(newSub[i-1][j] != 0){
newSub[i][j] = newSub[i-1][j]; //only up has value
}else{
newObject = newObject + 1; //no values
newSub[i][j] = newObject;
}
}else if(i-1 < 0 && j-1 >= 0){
if(newSub[i-1][j] != 0){
newSub[i][j] = newSub[i-1][j]; //only left has value
}else{
newObject = newObject + 1; //no values
newSub[i][j] = newObject;
}
}else{
if(newSub[i-1][j] == 0 && newSub[i][j-1] == 0){
newObject = newObject + 1; //no values
newSub[i][j] = newObject;
}else if(newSub[i-1][j] == newSub[i][j-1]){ //same value
newSub[i][j] = newSub[i-1][j];
}else if((newSub[i-1][j] != 0 && newSub[i][j-1] == 0)){
newSub[i][j] = newSub[i-1][j]; //only up has value
}else if(newSub[i-1][j] == 0 && newSub[i][j-1] != 0 ){
newSub[i][j] = newSub[i][j-1]; //only left has value
}else if(newSub[i-1][j] != newSub[i][j-1]){
newSub[i][j] = newSub[i-1][j]; //different values follow upper's value
}
}
}
}
}
int a = 1;
int maxRows = detected_edges.rows;
int maxCols = detected_edges.cols;
/*CONNECTING PIXELS RIGHT-BOTTOM*/
while(a < newObject){
int update = 0;
for(int i = 0; i < maxRows; i++){
for(int j = 0; j < maxCols; j++){
if(newSub[i][j] == a){
if(i+1 < maxRows && j+1 < maxCols){
if(newSub[i][j+1] > a){ //both points allowed
int value = newSub[i][j+1]; //get the value I need to replace
for(int h = 0; h < maxRows; h++){
for(int k = 0; k < maxCols; k++){
if(newSub[h][k] == value){ //replace all instances of that value
newSub[h][k] = a;
}
}
}
update = 1;
}
if(newSub[i+1][j] > a){ //both points allowed
int value = newSub[i+1][j]; //get the value I need to replace
for(int h = 0; h < maxRows; h++){
for(int k = 0; k < maxCols; k++){
if(newSub[h][k] == value){
newSub[h][k] = a; //replace all instances of that value
}
}
}
update = 1;
}
}else if(i+1 > maxRows && j+1 < maxCols){
if(newSub[i][j+1] > a){ //bottom is not allowed
int value = newSub[i][j+1]; //get the value I need to replace
for(int h = 0; h < maxRows; h++){
for(int k = 0; k < maxCols; k++){
if(newSub[h][k] == value){
newSub[h][k] = a; //replace all instances of that value
}
}
}
update = 1;
}
}else if(i+1 < maxRows && j+1 > maxCols){
if(newSub[i+1][j] > a){ //right is not allowed
int value = newSub[i+1][j]; //get the value I need to replace
for(int h = 0; h < maxRows; h++){
for(int k = 0; k < maxCols; k++){
if(newSub[h][k] == value){ //replace all instances of that value
newSub[h][k] = a;
}
}
}
update = 1;
}
}
}
}
}
a++;
}
/*CONNECTING PIXELS LEFT-TOP*/
a = newObject;
while(a > 0){
int update = 0;
for(int i = maxRows-1; i > 0; i--){
for(int j = maxCols-1; j > 0 ; j--){
if(newSub[i][j] == a){
if(i-1 >= 0 && j-1 >= 0){
if(newSub[i][j-1] > a){ //both points allowed
int value = newSub[i][j-1]; //get the value I need to replace
for(int h = 0; h < maxRows; h++){
for(int k = 0; k < maxCols; k++){
if(newSub[h][k] == value){
newSub[h][k] = a;
}
}
}
update = 1;
}
if(newSub[i-1][j] > a){
int value = newSub[i-1][j]; //get the value I need to replace
for(int h = 0; h < maxRows; h++){
for(int k = 0; k < maxCols; k++){
if(newSub[h][k] == value){ //replace all instances of that value
newSub[h][k] = a;
}
}
}
update = 1;
}
}else if(i-1 >= 0 && j-1 < 0){
if(newSub[i][j-1] > a){ //left is not allowed
int value = newSub[i][j-1]; //get the value I need to replace
for(int h = 0; h < maxRows; h++){
for(int k = 0; k < maxCols; k++){ //replace all instances of that value
if(newSub[h][k] == value){
newSub[h][k] = a;
}
}
}
update = 1;
}
}else if(i-1 < 0 && j-1 >= 0){
if(newSub[i-1][j] > a){ //top is not allowed
int value = newSub[i-1][j]; //get the value I need to replace
for(int h = 0; h < maxRows; h++){
for(int k = 0; k < maxCols; k++){ //replace all instances of that value
if(newSub[h][k] == value){
newSub[h][k] = a;
}
}
}
update = 1;
}
}
}
}
}
a--;
}
for(int i = 0; i < maxRows; i++){
for(int j = 0; j < maxCols; j++){
int check = 0;
if(newSub[i][j] != 0){
for(int k = 0; k < 5; k++){
if(newSub[i][j] == arr[k]){ //check if there is an instance of the value in the given array of values
check = 1;
break;
}
}
if(check == 0){
for(int r = 0; r < 5; r++){
if(arr[r] == 0){
arr[r] = newSub[i][j]; //if new value is found add to array
break;
}
}
}
}
}
}
/*
I HAVE AN ARRAY CONTAINING ALL VALUES
**/
src.copyTo( sub, detected_edges);
sub = Scalar::all(0);
/*SET AN INTENSITY FOR CORRESPONDING VALUES*/
int intensity = 50;
a = 0;
while(a < 5){
int update = 0;
for(int i = 0; i < maxRows; i++){
for(int j = 0; j < maxCols; j++){
if(newSub[i][j] == arr[a]){
sub.at<uchar>(i,j) = intensity;
}
}
}
a++;
intensity = intensity + 50;
}
a = 250;
/*GETTING MIN-MAX COORDINATES*/
while(a >= 50){
int setter = 0;
int minRow = 0;
int minCol = 0;
int maxRow = 0;
int maxCol = 0;
for(int i = 0; i < maxRows; i++){
for(int j = 0; j < maxCols; j++){
if(sub.at<uchar>(i,j) == a){
if(setter == 0){
minRow = i;
minCol = j;
maxRow = i;
maxCol = j;
setter = 1;
}else{
if(i <= minRow){
minRow = i;
}
else{
if(i > maxRow){
maxRow = i;
}
}
if(j <= minCol){
minCol = j;
}
else{
if(j > maxCol){
maxCol = j;
}
}
}
}
}
}
/*THIS IS WHERE I MAKE MY BOUNDING BOX*/
for(int i = minRow; i < maxRow; i++){
sub.at<uchar>(i,minCol) = 255; //set up the horizontal lines
sub.at<uchar>(i,maxCol) = 255;
}
for(int i = minCol; i < maxCol; i++){
sub.at<uchar>(minRow,i) = 255; //set up the vertical lines
sub.at<uchar>(maxRow,i) = 255;
}
a = a - 50;
}
dst = Scalar::all(0);
src.copyTo( dst, detected_edges);
imshow( window_name, dst );
namedWindow("FINAL", WINDOW_NORMAL);
imshow("FINAL",sub); //final output
resizeWindow("FINAL", 300, 300);
for(int i = 0; i < detected_edges.rows; i++)
delete[] newSub[i];
delete[] newSub;
}
/**
* #function main
*/
int main( int, char** argv )
{
/// Load an image
src = imread( argv[1] );
if( src.empty() )
{ return -1; }
/// Create a matrix of the same type and size as src (for dst)
dst.create( src.size(), src.type() );
/// Convert the image to grayscale
cvtColor( src, src_gray, COLOR_BGR2GRAY ); //grayscale for one channel for easy computation
/// Create a window
namedWindow( window_name, WINDOW_NORMAL );
resizeWindow(window_name, 300,300);
/// Show the image
connectedComponent(0, 0);
/// Wait until user exit program by pressing a key
waitKey(0);
return 0;
}

Resources