Error: missing return statement - return

My code was working perfectly before and now it doesn't compile anymore. I have searched for the missing return statement for a while but still can't find it...Here is the code:
private static boolean Prime(int x){
for(int i=1;i<x;i++)
{
if(x%i==0){
return false;
}
return true;
}
}
}

shouldn't the last return be one closing curly brace later?
private static boolean Prime(int x){
for(int i=1;i*i<x;i++)
{
if(x%i==0){
return false;
}
}
return true;
}
and, as a side note, you could stop the for loop at the square root of x.
i * i < x
or
i < sqrt(x)
I updated the condition in the indented code block.

It's easy to see a problem if you use indentations:
private static boolean Prime(int x) {
for (int i = 1; i < x; i++) {
if (x % i == 0) {
return false;
}
return true;
}
}
}

Related

Determine if two Trees are Identical

This is the question of Binary Tree. Level: Easy
In the second code, in while loop I just stored the value of popped integer value from stack in int variables and then wrote the condition of if loop. But in first I did not stored them in any variables I directly used them in if condition of while loop. Can anyone please explain why is it creating a difference?
This was my approach, in this if the input trees are 333 and 333 then it gives "no"(trees are not identical).
`
class Solution
{
public void preOrder(Node root,Stack<Integer> stack){
if(root==null){
return ;
}
stack.push(root.data);
preOrder(root.left,stack);
preOrder(root.right,stack);
}
boolean isIdentical(Node root1, Node root2)
{
// Code Here
if(root1==null||root2==null)
return false;
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
preOrder(root1,stack1);
preOrder(root2,stack2);
if(stack1.size()!=stack2.size())
return false;
while(!stack1.isEmpty()&&!stack2.isEmpty()){
if(stack1.pop()!=stack2.pop())
return false;
}
return true;
}
}`
But, in this the same input trees(333 and 333) gave correct output i.e "yes".
` class Solution
{
public void preOrder(Node root,Stack<Integer> stack){
if(root==null){
return ;
}
stack.push(root.data);
preOrder(root.left,stack);
preOrder(root.right,stack);
}
boolean isIdentical(Node root1, Node root2)
{
// Code Here
if(root1==null||root2==null)
return false;
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
preOrder(root1,stack1);
preOrder(root2,stack2);
if(stack1.size()!=stack2.size())
return false;
while(!stack1.isEmpty()&&!stack2.isEmpty()){
int n1 = stack1.pop();
int n2 = stack2.pop();
if(n1!=n2)
return false;
}
return true;
}
}`

Can I use class methods inside factory constructor via Dart

I have the below code that is creating the PriortyQueue structure using Dart. But since I cannot use heapify function inside the Constructor or factory constructor I cannot initialize PQ with an existing set of List. Can somebody guide me and show me how I can use heapify while creating PQ instance so I can initialize it with an existing List? Also If you have any other suggestions against doing something like this please also help me as well. thank you
class PriorityQueue<T extends Comparable<T>> {
List<T?> _tree;
PriorityQueue._(List<T?> tree) : _tree = tree;
factory PriorityQueue([List<T>? array]) {
List<T?> newArray = [null, ...array ?? []];
// ignore: todo
//TODO: missing heapify
return PriorityQueue._(newArray);
}
void insert(T node) {
_tree.add(node);
_swim(_tree.length - 1);
}
T getTop() {
_swap(1, _tree.length - 1);
T top = _tree.removeLast() as T;
_sink(1);
return top;
}
List<T> _heapify(List<T> array) {
int sinkNodeIndex = (array.length - 1) ~/ 2;
while (sinkNodeIndex >= 1) {
_sink(sinkNodeIndex);
sinkNodeIndex--;
}
}
void _sink(int nodeIndex) {
int leftChildIndex = nodeIndex * 2;
int rightChildIndex = leftChildIndex + 1;
int minNodeIndex = leftChildIndex;
// index can be unreachable
T? leftChild =
leftChildIndex >= _tree.length ? null : _tree[leftChildIndex];
T? rightChild =
rightChildIndex >= _tree.length ? null : _tree[rightChildIndex];
if (leftChild == null) {
return;
}
if (rightChild != null && leftChild.compareTo(rightChild) > 0) {
minNodeIndex = rightChildIndex;
}
if ((_tree[minNodeIndex] as T).compareTo(_tree[nodeIndex] as T) < 0) {
_swap(nodeIndex, minNodeIndex);
_sink(minNodeIndex);
}
}
void _swim(int nodeIndex) {
if (nodeIndex <= 1) return;
int parentIndex = nodeIndex ~/ 2;
if ((_tree[nodeIndex] as T).compareTo(_tree[parentIndex] as T) < 0) {
_swap(nodeIndex, parentIndex);
_swim(parentIndex);
}
}
void _swap(int i, int j) {
T temp = _tree[i] as T;
_tree[i] = _tree[j];
_tree[j] = temp;
}
#override
String toString() {
return _tree.toString();
}
}
I would make all the helper functions. _heapify, _sink/_swim, even _swap, be static functions which take the list as argument.
Then you can use them from anywhere, including inside the factory constructor.
Alternatively, you can change the constructor to returning:
return PriorityQueue._(newArray).._heapify();
This creates the PriorityQueue object, and then calls the _heapify method on it, before returning the value.
(I'd also make _tree have type List<T> and not insert the extra null at the beginning. It's more efficient to add/subtract 1 from indices than it is to cast to T.)
I ended up doing like Irn's first suggestion. But when I do functions static they lost Type of the class so I needed to specify for each function. Also, making List<T?> instead of List ended up with me fighting against the compiler.
class PriorityQueue<T extends Comparable<T>> {
List<T?> _tree;
PriorityQueue._(List<T?> tree) : _tree = tree;
factory PriorityQueue([List<T>? array]) {
List<T?> newArray = [null, ...array ?? []];
_heapify(newArray);
return PriorityQueue._(newArray);
}
bool get isNotEmpty {
return _tree.isNotEmpty;
}
void insert(T node) {
_tree.add(node);
_swim(_tree, _tree.length - 1);
}
void insertMultiple(List<T> array) {
for (var element in array) {
insert(element);
}
}
T? removeTop() {
if (_tree.length == 1) return null;
_swap(_tree, 1, _tree.length - 1);
T top = _tree.removeLast() as T;
_sink(_tree, 1);
return top;
}
void removeAll() {
_tree = [null];
}
static void _heapify<T extends Comparable<T>>(List<T?> array) {
int sinkNodeIndex = (array.length - 1) ~/ 2;
while (sinkNodeIndex >= 1) {
_sink(array, sinkNodeIndex);
sinkNodeIndex--;
}
}
static void _sink<T extends Comparable<T>>(List<T?> tree, int nodeIndex) {
int leftChildIndex = nodeIndex * 2;
int rightChildIndex = leftChildIndex + 1;
int minNodeIndex = leftChildIndex;
T? leftChild = leftChildIndex >= tree.length ? null : tree[leftChildIndex];
T? rightChild =
rightChildIndex >= tree.length ? null : tree[rightChildIndex];
if (leftChild == null) {
return;
}
if (rightChild != null && leftChild.compareTo(rightChild) > 0) {
minNodeIndex = rightChildIndex;
}
if ((tree[minNodeIndex] as T).compareTo(tree[nodeIndex] as T) < 0) {
_swap(tree, nodeIndex, minNodeIndex);
_sink(tree, minNodeIndex);
}
}
static void _swim<T extends Comparable<T>>(List<T?> tree, int nodeIndex) {
if (nodeIndex <= 1) return;
int parentIndex = nodeIndex ~/ 2;
if ((tree[nodeIndex] as T).compareTo(tree[parentIndex] as T) < 0) {
_swap(tree, nodeIndex, parentIndex);
_swim(tree, parentIndex);
}
}
static void _swap<T extends Comparable<T>>(List<T?> tree, int i, int j) {
T temp = tree[i] as T;
tree[i] = tree[j];
tree[j] = temp;
}
#override
String toString() {
return _tree.toString();
}
}

How to return two value from a function in dart?

here is my code
import 'dart:io';
import 'dart:math';
void main() {
bool flag = false;
for (int i = 0; i < 100; i++) {
gameCode();
if (userNumber == computerNumber) {
flag = true;
break;
}
}
}
int randomNumber(number) {
Random randNumber = Random();
int random = randNumber.nextInt(number);
return random;
}
gameCode() {
int computerNumber = randomNumber(9);
print("start guessing the number : ");
int userNumber = int.parse(stdin.readLineSync()!);
if (userNumber == computerNumber) {
print("You got it");
}
}
in this code you can see gameCode function. in that function there is two value that i need to use in main function.so how do i return those two keyword from that function ?
//userNumber // computerNumber
this is the variable that i want to return from that code
Dart not support return multiple values in function, you can return it with array, map, or you can use third lib tuple
Dart does not support returning multiple values in the current latest version. I would in your case recommend creating a class for the specific purpose of define the result from gameCode(). So something like this:
class GameCodeResult {
int userNumber;
int computerNumber;
GameCodeResult({
required this.userNumber,
required this.computerNumber,
});
}
Which we can then use like this in your program:
import 'dart:io';
import 'dart:math';
void main() {
bool flag = false;
for (int i = 0; i < 100; i++) {
GameCodeResult result = gameCode();
if (result.userNumber == result.computerNumber) {
flag = true;
break;
}
}
}
final _random = Random();
int randomNumber(int maxNumber) => _random.nextInt(maxNumber);
GameCodeResult gameCode() {
int computerNumber = randomNumber(9);
print("start guessing the number : ");
int userNumber = int.parse(stdin.readLineSync()!);
if (userNumber == computerNumber) {
print("You got it");
}
return GameCodeResult(userNumber: userNumber, computerNumber: computerNumber);
}
Note, I also fixed your randomNumber() method since it is not recommended to generate a new Random() object for each new random number you want. We should instead reuse an instance of Random in our program.
Please refer to below code
import 'dart:io';
import 'dart:math';
void main() {
bool flag = false;
for (int i = 0; i < 100; i++) {
Map<String, dynamic> res = gameCode();
print(res);
if (res['user_number'] == res['computer_number']) {
flag = true;
break;
}
}
}
int randomNumber(number) {
Random randNumber = Random();
int random = randNumber.nextInt(number);
return random;
}
Map<String, dynamic> gameCode() {
int computerNumber = randomNumber(9);
print("start guessing the number : ");
int userNumber =
int.parse(stdin.readLineSync()!);
if (userNumber == computerNumber) {
print("You got it");
}
return {
"computer_number": computerNumber,
"user_number": userNumber,
};
}

foreach statement overload in d programing language

Hello I would like to define my own class collection, and make it iterable in a foreach statement, just like this :
public class Collection(Type)
{
...
private T head;
private Collection!(T) queue;
}
Collection!(int) temp;
foreach (int t; temp) { ... }
What methods should I define, and how ?
you can specify the front, popfront() and empty functions: (but this will consume your collection unless you use save())
public class Collection(T) { ... private T head; private Collection!(T) queue;
#property T front(){
return head;
}
#property bool empty(){
return queue is null;
}
void popfront(){
head = queue.head;
queue = queue.queue;
}
Collection!T save(){
return new Collection!T(head,queue);
}
}
or use a dedicated struct for iteration (as is done in the std.container module
public class Collection(T) { ... private T head; private Collection!(T) queue;
Range opSlice(){
return Range(head,queue);
}
struct Range{
T h;
Collection!(T) q;
this(T he, Collection!(T) qu){
h=he;
q=qu;
}
#property T front(){
return h;
}
#property bool empty(){
return q is null;
}
void popfront(){
h = q.head;
q= q.queue;
}
Collection!T save(){
return this;
}
}
}
so iteration is done like so
Collection!(int) temp; foreach (int t;temp[]) { ... }
you also can add an opApply for the normal foreach:
public int opApply(int delegate(ref T) dg){
int res=0;
foreach(ref T;this[]){
res = dg(t);
if(res)return res;
}
return res;
}
Take a look at this documentation on ForeachStatements and scroll down a bit.
If I'm reading your example correctly, you could define an opApply for Collection as follows:
public int opApply(int delegate(ref T) dg){
Collection!T p = this;
int res = 0;
while(!res && p !is null){
res = dg(p.head);
p = p.queue;
}
return res;
}
Your Collection class should implement opApply. Your foreach body becomes a delegate to an internal for loop, and you iterate over your internal collection (in your case a queue) using a for loop.
Consider the example given in the docs
class Foo {
uint array[2];
int opApply(int delegate(ref uint) dg)
{ int result = 0;
for (int i = 0; i < array.length; i++)
{
result = dg(array[i]);
if (result)
break;
}
return result;
}
}

how to set a BasicEditField to accept dotted decimal numbers

I have added a BasicEditField to a GridFieldManager. When I test it, it allows input values like 11.11.11. How can I make my BasicEditField accept only correct double numbers, like 101.1 or 123.123. That is, allow only one decimal point.
gfm = new GridFieldManager(1, 2, 0);
gfm.add(new LabelField(" Enter value : "));
bef = new BasicEditField(BasicEditField.NO_NEWLINE|BasicEditField.FILTER_REAL_NUMERIC);
bef.setFilter(TextFilter.get(NumericTextFilter.REAL_NUMERIC));
bef.setFilter(TextFilter.get(TextFilter.REAL_NUMERIC));
bef.setText("1");
bef.setMaxSize(8);
gfm.add(bef);
add(gfm);
i had tried everything that i can. but the problem is yet in my app. can anyone give me a proper way to design a input field tha accepts decimal numbers?
Please add all the objects into the mainScreen with add(field);.
and then trying to get value of that fields.
now in your code put
String s = bef.getText();
Dialog.alert(s);
after
add(gfm);
and
To accept number like 1.1111.
then add
BasicEditField.FILTER_REAL_NUMERIC
in BasicEditFieldConstructor.
Now i think you got your solution.
finally i got the solution for a forum(forgot to copy the link)..
here it is...
inside my class i put the variables...
private int maxIntDigits = -1;
private int maxFractDigits = -1;
private String old;
i had added a BasicEditField, bef..
bef = new BasicEditField("","1");
bef.setMaxSize(8);
bef.setChangeListener(this);
add(bef);
And then in its fieldChanged().
public void fieldChanged(Field field, int context)
{
if(field==bef)
{
String str = bef.getText();
if(str.equals(""))
{
old = "";
//return;
}
if(str.indexOf('.') == str.lastIndexOf('.'))
{
if(str.indexOf('-') >= 0)
{
bef.setText(old);
}
if(validateIntPart(str) && validateFractPart(str))
{
old = str;
//return;
}
else
{
bef.setText(old);
}
}
else
{
bef.setText(old);
//return;
}
}
}
and then two functions in it...
private boolean validateIntPart(String str) {
if(maxIntDigits == -1) {
return true; //no limit has been set
}
int p = str.indexOf('.');
if(p == -1) {
p = str.length();
}
int digits = str.substring(0, p).length();
if(digits > maxIntDigits) {
return false;
} else {
return true;
}
}
private boolean validateFractPart(String str) {
if(maxFractDigits == -1) {
return true; //no limit has been set
}
int p = str.indexOf('.');
if(p == -1) {
return true; //if no '.' found then the fract part can't be too big
}
int digits = str.substring(p + 1, str.length()).length();
if(digits > maxFractDigits) {
return false;
} else {
return true;
}
}

Resources