A value of type 'Null' can't be assigned to a variable of type 'double' - flutter

Hello I have a connect four game who worked before null safety but I try to make the migration, but I have a problem with scores[i] = null; I can't write like that but without it I have a freeze when CPU is certain to loose
int _compute(Board board, int step, int deepness, List<double> scores) {
for (var i = 0; i < 7; ++i) {
final boardCopy = board.clone();
final target = boardCopy.getColumnTarget(i);
if (target == -1) {
scores[i] = null; // <<<---- HERE I CAN'T USE NULL
continue;
}
final coordinate = Coordinate(i, target);
boardCopy.setBox(coordinate, player);
if (boardCopy.checkWinner(coordinate, player)) {
scores[i] += deepness / (step + 1);
continue;
}
for (var j = 0; j < 7; ++j) {
final target = boardCopy.getColumnTarget(j);
if (target == -1) {
continue;
}
final coordinate = Coordinate(j, target);
boardCopy.setBox(coordinate, otherPlayer);
if (boardCopy.checkWinner(coordinate, otherPlayer)) {
scores[i] -= deepness / (step + 1);
continue;
}
if (step + 1 < deepness) {
_compute(board, step + 1, deepness, scores);
}
}
}
return _getBestScoreIndex(scores);
}
int _getBestScoreIndex(List<double> scores) {
int bestScoreIndex = scores.indexWhere((s) => s != null);
scores.asMap().forEach((index, score) {
if (score != null &&
(score > scores[bestScoreIndex] ||
(score == scores[bestScoreIndex] && _random.nextBool()))) {
bestScoreIndex = index;
}
});
return bestScoreIndex;
}
if I use List<double?>
int _compute(Board board, int step, int deepness, List<double?> scores) {
for (var i = 0; i < 7; ++i) {
final boardCopy = board.clone();
final target = boardCopy.getColumnTarget(i);
if (target == -1) {
scores[i] = null;
continue;
}
final coordinate = Coordinate(i, target);
boardCopy.setBox(coordinate, player);
if (boardCopy.checkWinner(coordinate, player)) {
scores[i] += deepness / (step + 1);//<<<---- HERE I CAN'T USE +=
continue;
}
for (var j = 0; j < 7; ++j) {
final target = boardCopy.getColumnTarget(j);
if (target == -1) {
continue;
}
final coordinate = Coordinate(j, target);
boardCopy.setBox(coordinate, otherPlayer);
if (boardCopy.checkWinner(coordinate, otherPlayer)) {
scores[i] -= deepness / (step + 1); //<<<---- HERE I CAN'T USE -=
continue;
}
if (step + 1 < deepness) {
_compute(board, step + 1, deepness, scores);
}
}
}
return _getBestScoreIndex(scores);
}
int _getBestScoreIndex(List<double?> scores) {
int bestScoreIndex = scores.indexWhere((s) => s != null);
scores.asMap().forEach((index, score) {
if (score != null && // <<<---- HERE I CAN'T USE score !=
(score > scores[bestScoreIndex] || // <<<---- HERE I CAN'T USE score >
(score == scores[bestScoreIndex] && _random.nextBool()))) {
bestScoreIndex = index;
}
});
return bestScoreIndex;
}

The issue with your code is that in the function definition you have defined the data type of score variable as List<double>. Due to which you get an error on assigning score[i] = null. To fix this use data type of score as List<double?>

i believe the param scores is a type-defined value and it has a double, which is a non null value. So you can't assign null to double as it has the type of value assigned.
You can make it double as an optional value, like a List<double?>. but with this, the values in the list will be optional and you need to force unwrap or do null check before using them.

Related

In Flutter and if the number after decimal point is equal 0 convert the number to int

This is a function if the endValueFixed is equal for example 12.0 I want to print the number without zero so I want it to be 12.
void calculateIncrease() {
setState(() {
primerResult = (startingValue * percentage) / 100;
endValue = startingValue + primerResult;
endValueFixe`enter code here`d = roundDouble(endValue, 2);
});
}
This may be an overkill but it works exactly as you wish:
void main() {
// This is your double value
final end = 98.04;
String intPart = "";
String doublePart = "";
int j = 0;
for (int i = 0; i < end.toString().length; i++) {
if (end.toString()[i] != '.') {
intPart += end.toString()[i];
} else {
j = i + 1;
break;
}
}
for (int l = j; l < end.toString().length; l++) {
doublePart += end.toString()[l];
}
if (doublePart[0] == "0" && doublePart[1] != "0") {
print(end);
} else {
print(end.toString());
}
}
You may use this code as a function and send whatever value to end.
if (endValueFixed==12) {
print('${endValueFixed.toInt()}');
}
conditionally cast it to an int and print it then :)

Need to update the Date format on my Google Mail Script

I'm creating a Gmail script that includes 5 variables, one of which is a due date. I just want it to populate as MM/DD/YYYY, however, it is currently populating as Thu Sep 13 2018 00:00:00 GMT-0400 (EDT).
Is there a way I can do that? I've pasted my code below for your reference. Any assistance is much appreciated.
function getRowsData(sheet, range, columnHeadersRowIndex) {
columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
var numColumns = range.getEndColumn() - range.getColumn() + 1;
var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
var headers = headersRange.getValues()[0];
return getObjects(range.getValues(), normalizeHeaders(headers));
}
function getObjects(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
function normalizeHeaders(headers) {
var keys = [];
for (var i = 0; i < headers.length; ++i) {
var key = normalizeHeader(headers[i]);
if (key.length > 0) {
keys.push(key);
}
}
return keys;
}
function normalizeHeader(header) {
var key = "";
var upperCase = false;
for (var i = 0; i < header.length; ++i) {
var letter = header[i];
if (letter == " " && key.length > 0) {
upperCase = true;
continue;
}
if (!isAlnum(letter)) {
continue;
}
if (key.length == 0 && isDigit(letter)) {
continue;
}
if (upperCase) {
upperCase = false;
key += letter.toUpperCase();
} else {
key += letter.toLowerCase();
}
}
return key;
}
function isCellEmpty(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
function isAlnum(char) {
return char >= 'A' && char <= 'Z' ||
char >= 'a' && char <= 'z' ||
isDigit(char);
}
function isDigit(char) {
return char >= '0' && char <= '9';

Binary addition in java

I wrote a program for a binary addition in java. But the result is sometimes not right.
For example if i add 1110+111. The result should be 10101.
But my program throws out 10001.
Maybe one of you find the mistake.
import java.util.Scanner;
public class BinaryAdder {
public static String add(String binary1, String binary2) {
int a = binary1.length()-1;
int b = binary2.length()-1;
int sum = 0;
int carry = 0;
StringBuffer sb = new StringBuffer();
while (a >= 0 || b >= 0) {
int help1 = 0;
int help2 = 0;
if( a >=0){
help1 = binary1.charAt(a) == '0' ? 0 : 1;
a--;
} if( b >=0){
help2 = binary2.charAt(b) == '0' ? 0 : 1;
b--;
}
sum = help1 +help2 +carry;
if(sum >=2){
sb.append("0");
carry = 1;
} else {
sb.append(String.valueOf(sum));
carry = 0;
}
}
if(carry == 1){
sb.append("1");
}
sb.reverse();
String s = sb.toString();
s = s.replaceFirst("^0*", "");
return s;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("First: ");
String input1 = scan.next("(0|1)*");
System.out.print("Second: ");
String input2 = scan.next("(0|1)*");
scan.close();
System.out.println("Result: " + add(input1, input2));
}
}
this function is much simpler :
public static String binaryAdd(String binary1,String binary2){
return Long.toBinaryString(Long.parseLong(binary1,2)+Long.parseLong(binary2,2));
}
you can change Long.parseLong into Integer.parseInt if you don't expect very large numbers, you can also replace parse(Long/Int) with parseUnsigned(Long/Int) since you don't expect your strings to have a minus sign do you ?
You are not considering the case when
help1 + help2 = 3
So your method String add(String binary1, String binary2) should be like this:
public static String add(String binary1, String binary2) {
int a = binary1.length()-1;
int b = binary2.length()-1;
int sum = 0;
int carry = 0;
StringBuffer sb = new StringBuffer();
while (a >= 0 || b >= 0) {
int help1 = 0;
int help2 = 0;
if( a >=0){
help1 = binary1.charAt(a) == '0' ? 0 : 1;
a--;
} if( b >=0){
help2 = binary2.charAt(b) == '0' ? 0 : 1;
b--;
}
sum = help1 +help2 +carry;
if (sum == 3){
sb.append("1");
carry = 1;
}
else if(sum ==2){
sb.append("0");
carry = 1;
} else {
sb.append(String.valueOf(sum));
carry = 0;
}
}
if(carry == 1){
sb.append("1");
}
sb.reverse();
String s = sb.toString();
s = s.replaceFirst("^0*", "");
return s;
}
I hope this could help you!
sum = help1 +help2 +carry;
if(sum >=2){
sb.append("0");
carry = 1;
} else {
sb.append(String.valueOf(sum));
carry = 0;
}
If sum is 2 then append "0" and carry = 1
What about when the sum is 3, append "1" and carry = 1
Will never be 4 or greater
Know I'm a bit late but I've just done a similar task so to anyone in my position, here's how I tackled it...
import java.util.Scanner;
public class Binary_Aids {
public static void main(String args[]) {
System.out.println("Enter the value you want to be converted");
Scanner inp = new Scanner(System.in);
int num = inp.nextInt();
String result = "";
while(num > 0) {
result = result + Math.floorMod(num, 2);
num = Math.round(num/2);
}
String flippedresult = "";
for(int i = 0; i < result.length(); i++) {
flippedresult = result.charAt(i) + flippedresult;
}
System.out.println(flippedresult);
}
}
This took an input and converted to binary. Once here, I used this program to add the numbers then convert back...
import java.util.Scanner;
public class Binary_Aids {
public static void main(String args[]) {
Scanner inp = new Scanner(System.in);
String decimalToBinaryString = new String();
System.out.println("First decimal number to be added");
int num1 = inp.nextInt();
String binary1 = decimalToBinaryString(num1);
System.out.println("Input decimal number 2");
int num2 = inp.nextInt();
String binary2 = decimalToBinaryString(num2);
int patternlength = Math.max[binary1.length[], binary2.length[]];
while(binary1.length() < patternlength) {
binary1 = "0" + binary2;
}
System.out.println(binary1);
System.out.println(binary2);
int carry = 0;
int frequency_of_one;
String result = "";
for(int i = patternlength -i; i >= 0; i--) {
frequency_of_one = carry;
if(binary1.charAt(i) == '1') {
frequency_of_one++;
}
if(binary2.charAt(i) == '1') {
frequency_of_one++;
}
switch(frequency_of_one) {
case 0 ;
carry = 0;
result = "1" + result;
break;
case 1 ;
carry = 0;
result = "1" + result;
break;
case 2;
carry = 1;
result = "0" + result;
breake;
case 3;
carry = 1;
result = "1" + result;
breake;
}
}
if(carry == 1) {
result = "1" + result;
}
System.out.println(result);
}
public static String decimalToBinaryString(int decimal1) {
String result = "";
while(decimal1 > 0) {
result = result + Math.floorMod(decimal1, 2);
decimal = Math.round(decimal1/2);
}
String flipresult = "";
for(int i = 0; i < result.length[]; i++) {
flipresult = result.charAt(i) + flippedresult;
}
return flippedresult;
}
}

making a trail that destroys enemies in unity

After searching for a way to do this I found a script from robertbu that should work for detecting collisions, I am trying to make it so that when this system detects a collision with "Virus" by using other.CompareTag like you would with ontriggerenter(other:collider). Here's the neccesary part of the script.
function Update() {
if (Hit() == true){
if (other.CompareTag("Virus")){
Destroy(other.gameObject);
}
}
}
function Hit() : boolean {
var i = head;
var j = (head - 1);
if (j < 0) j = arv3.Length - 1;
while (j != head) {
if (Physics.Linecast(arv3[i], arv3[j], hit))
return true;
i = i - 1;
if (i < 0) i = arv3.Length - 1;
j = j - 1;
if (j < 0) j = arv3.Length - 1;
}
return false;
}
function Update() {
Hit();
}
function Hit() : boolean {
var i = head;
var j = (head - 1);
if (j < 0) j = arv3.Length - 1;
while (j != head) {
if (Physics.Linecast(arv3[i], arv3[j], hit) && hit.collider.tag == "Virus") {
Destroy(hit.collider.gameObject);
}
i = i - 1;
if (i < 0) i = arv3.Length - 1;
j = j - 1;
if (j < 0) j = arv3.Length - 1;
}
}
it works with this code

Change Value of Duplicate Object in NSMutableArray?

I have the method below, which in my Blackjack app will get the value of the hand which is an NSMutableArray. The problem here is that when 2 Ace's are in a hand, it should be a 12, but because it counts Ace's as 11, it results in being 22, which then makes lowValue returned.
How can I make it so that I can check and see if the for loop has already found an Ace and if it finds another, makes the next Ace worth only 1, not 11?
Thanks!
int getHandValue(NSMutableArray *hand) {
int lowValue = 0;
int highValue = 0;
for (KCCard *aCard in hand) {
if (aCard.value == Ace) {
lowValue+= 1;
highValue+= 11;
} else if (aCard.value == Jack || aCard.value == Queen || aCard.value == King) {
lowValue += 10;
highValue += 10;
} else {
lowValue += aCard.value;
highValue += aCard.value;
}
}
return (highValue > 21) ? lowValue : highValue;
}
Perhaps you can add a boolean value before the for loop setting it initially to NO. When an Ace is found then you can break from the for loop after setting the boolean to YES, that way if you encounter another Ace && your boolean value == YES you can handle the case accordingly.
int getHandValue(NSMutableArray *hand) {
int lowValue = 0;
int highValue = 0;
BOOL isFoundAce = NO;
for (KCCard *aCard in hand) {
if (aCard.value == Ace) {
if (isFoundAce) {
lowValue+= 1;
highValue+= 1;
}
else {
lowValue+= 1;
highValue+= 11;
isFoundAce= YES;
}
} else if (aCard.value == Jack || aCard.value == Queen || aCard.value == King) {
lowValue += 10;
highValue += 10;
} else {
lowValue += aCard.value;
highValue += aCard.value;
}
}
return (highValue > 21) ? lowValue : highValue;
}
My example without a redundant code from zsxwing's example:
int getHandValue(NSMutableArray *hand) {
int cardValue = 0;
int aceCount = 0;
for (KCCard *aCard in hand) {
if (aCard.value == Ace) {
aceCount++;
cardValue += 11;
} else if (aCard.value == Jack || aCard.value == Queen || aCard.value == King) {
cardValue += 10;
} else {
cardValue += aCard.value;
}
}
while ((cardValue > 21) && (aceCount > 0)) {
cardValue -= 10;
aceCount--;
}
return cardValue;
}