-1

Hi,

I have wrote a program that solve a Puzzle in Python. To progress in Dart, I have tried to write in this langage but unfortunately, I did not solve there:

Link of the puzzle: https://www.codingame.com/training/easy/happy-numbers

My code that It works but does not include BigInt (so not the two last test)

import 'dart:io';

int step(int number)
{
    int result = 0;
    int ten = 10;
    while( number != 0 )
    {
        result = result + (number % ten )*(number % ten );
        number = (number ~/ ten ); 
    }
    return result;
}

bool solve(int out, int number)
{
    int resultat = number;
    while( true )
    {
        resultat = step(resultat);

        if( resultat == 1 )
            return true;
        if( resultat == 4 )
            return false;
    }
}

void main() {
    int N = int.parse(stdin.readLineSync());
    for (int i = 0; i < N; i++) {
        int x = int.parse(stdin.readLineSync());
        bool res = solve(x,x);
        print( res == true ? '$x :)' : '$x :(');
    }
}

I have trued this with BigInt

import 'dart:io';

BigInt step(BigInt number)
{
    BigInt result = BigInt.parse('0');
    BigInt ten = BigInt.parse('10');
    while( number != 0 )
    {
        result = result + (number % ten )*(number % ten );
        number = (number ~/ ten ); 
    }
    return result;
}

bool solve(BigInt out, BigInt number)
{
    BigInt resultat = number;
    while( true )
    {
        resultat = step(resultat);

        if( resultat == BigInt.parse('1') )
            return true;
        if( resultat == BigInt.parse('4') )
            return false;
    }
}

void main() {
    int N = int.parse(stdin.readLineSync());
    for (int i = 0; i < N; i++) {
        BigInt x = BigInt.parse(stdin.readLineSync());
        bool res = solve(x,x);
        print( res == true ? '$x :)' : '$x :(');
    }
}

I don't find the misstake and I have no idea to resolve that.

:(

Gromph
  • 123
  • 12

1 Answers1

1

If you paste your program into dartpad.dartlang.org, you get the warning:

Equality operator `==` invocation with references of unrelated types - line 7

So, maybe change line 7 from:

while( number != 0 )

to

while (number != BigInt.zero)

(Also consider formatting your code with dart format, it makes it more readable to people used to reading Dart).

lrn
  • 64,680
  • 7
  • 105
  • 121
  • Thanks. It works and I Have completed the puzzle . :) It's a website where I code. But thanks for advice. – Gromph Aug 16 '20 at 14:06