Using while to get 13 digits - asp.net

I am new to programming, I need to generate 13 random number using loop (while) number + 1 when the number reaches 13, I will like to store that number in text box.
Any help will be welcomed

What you see below is a 'static' class, which needs no initialization. So, with this in your project, you can just call RandomInts.GetRandomInts() and pass it on into your model for the input box to present to your user(s).
public static class RandomInts
{
private static int _x = 0;
public static int GetRandomInts()
{
var i = 0;
var rnd = new Random();
while (i < 13)
{
_x = rnd.Next();
i++;
}
return _x;
}
}

Here is with upper and lower bounds:
var x = random.[Next](minr, maxr)

Related

Get random items from firebase min 3 max 5

I am trying to get random items from my firebase database and it almost works,
sometimes I only get one or two items when the minimum is 3 and max is 5.
Every item has an index and it's getting the items that startAt(startindex) and endAt(startIndex+randomNumber).
Is there any other way to do this other than using an index on each item in the database?
Here is how the code looks now:
randomNumber = getRandomInt(3,5);
listView = (ListView)view.findViewById(R.id.listView);
int startIndex = (int)(Math.random() * childs+1);
adapter = new FirebaseListAdapter<TraningData>(getActivity(),TraningData.class,R.layout.layout_traning_item,ref_1
.orderByChild("index")
.startAt(startIndex)
.endAt(startIndex+randomNumber)) {
#Override
protected void populateView(View view, final TraningData td, int i) {
//Populating over here!
}
};
listView.setAdapter(adapter);
Since Firebase never want to add this feature.
Here how I solved it by adding all to an array and then make a random selection.
ArrayList<TraningData> randomSelected = new ArrayList<>();
Random rand = new Random();
int numElements = getRandomInt(3,5);
for(int i = 0;i < numElements;i++){
int randomIndex = rand.nextInt(traningData.size());
randomSlected.add(traningData.get(randomIndex));
}
cAdapter = new CustomAdapter(getActivity(),randomSlected);
listView.setAdapter(cAdapter);

Why isn't this Math.random method working?

Since Java doesn't allow to return two types in one method, I thought best way to do it is to use get methods.
Simply, I wanted computer to generate two random numbers, and if they were not the same I wanted it to print sum of them. If they were the same, I wanted it to roll once more and sum all of the rolls. Until here, it was okay, but then I wanted to see not only sum, but also the numbers that computer generated randomly before adding them up. Therefore, it had to be several return types.
But it prints 0 three times instead.
Can you help me with this? I want to learn what is wrong exactly with this code and if it can be done neater and cleaner? I know Java loves long ways..
Thank you.
class App {
public static int monopolyRoll(int side) {
double randomNumber = Math.random();
randomNumber = randomNumber * side;
randomNumber = randomNumber + 1;
int randomInt = (int) randomNumber;
return randomInt;
}
private int roll1 = monopolyRoll(6);
private int roll2 = monopolyRoll(6);
public int userRolls() {
if (roll1 != roll2) {
return roll1 + roll2;
} else {
int roll3 = monopolyRoll(6);
int roll4 = monopolyRoll(6);
return roll1 + roll2 + roll3 + roll4;
}
}
private static int first;
private static int second;
private static int third;
public App(int first, int second, int third) {
App.first = roll1;
App.second = roll2;
App.third = userRolls();
}
public static int getFirst() {
return first;
}
public static int getSecond() {
return second;
}
public static int getThird() {
return third;
}
public static void main(String[] args) {
int first = getFirst();
int second = getSecond();
int third = getThird();
System.out.println(first);
System.out.println(second);
System.out.println(third);
}
}
Math.random() works, but you never actually call it in your application. This is what your application does:
int first = getFirst();
int second = getSecond();
int third = getThird();
System.out.println(first);
System.out.println(second);
System.out.println(third);
That's it. Aside from the single return statements in those getter methods and the declared-but-never-assigned integers they return (so, zeroes), none of that other code ever executes.
I suspect this is coming from a bit of a misunderstanding on your part about the static keyword. By sprinkling around the static keyword until the code compiled, what you've done is create something that's syntactically correct but doesn't do anything :)
As a bit of a learning exercise, try moving all of the business logic out of the App class, leaving only the main() method as the application's entry point. And removing all static keywords from the new class you create. This should make the use of that class more clear.
Something like:
class Roller {
private int roll1;
private int roll2;
// other private variables
private int monopolyRoll(int side) {
// your code
}
// your other methods, also private and non-static
public Roller(int first, int second, int third) {
this.first = roll1;
this.second = roll2;
this.third = userRolls();
}
// and so on
}
The idea here is to make things instance-based (non-static) by default. Also make things private by default until explicitly needed to be accessed outside the class. Currently the only things your class needs to expose publicly are the constructor and the getters.
Then in the main() method you'll need to create an instance of your class to use it. Something like this:
Roller roller = new Roller(1, 2, 3);
int first = roller.getFirst();
int second = roller.getSecond();
int third = roller.getThird();
System.out.println(first);
System.out.println(second);
System.out.println(third);

Is there a predefined method to compute area of a polygon in Nutiteq?

I ask IN NUTITEQ, I know the way to perform this with GoogleApi with computeArea() but I have not found anything in Nutiteq sdk/snapshot.
Thanks in advance.
p.s. I know many methods to compute the area but I want to call something own of Nutiteq
EDIT:
There are no built-in Method, thanks for the fast answer Jaak, so I researched and found 2 Methods, both of them under WSG84 Projection. I developed a little programm to compare both of them and then I compared to a KML Tool, which computes area of a Polygon.
how-can-i-measure-area-from-geographic-coordinates
A-link-to-a-Geographic-Framework
And the results with a kml tool of University of New Hampshire
12197.38184
import java.lang.Math.*;
import net.sf.geographiclib.*;
public class ComputeAreaTest {
private static double[][] moorwiese_coords = {{12.925634f,48.427168f},
{12.926825f,48.427217f},
{12.926788f,48.428385f},
{12.926069f,48.428374f},
{12.925431f,48.42825f},
{12.925624f,48.427192f},
{12.925634f,48.427168f}};
protected static double computeArea() {
double area=0.0;
double earthRadius = 6378137.0f;
int size = moorwiese_coords.length;
if (size > 2) {
double[] p1 = new double[2];
double[] p2 = new double[2];
for (int i=0; i<size-1; i++) {
p1 = moorwiese_coords[i];
p2 = moorwiese_coords[i+1];
area += Math.toRadians(p2[0] - p1[0]) * (2 +
Math.sin(Math.toRadians(p1[1]) ) + Math.sin(Math.toRadians(p2[1])) );
}
area = area * earthRadius * earthRadius / 2.0;
}
return area;
}
protected static double computeAreaWithGeographicLib() {
int size = moorwiese_coords.length;
PolygonArea p = new PolygonArea(Geodesic.WGS84, false);
try {
for (int i=0;i<size;i++) {
p.AddPoint(moorwiese_coords[i][4], moorwiese_coords[i][0]);
}
}
catch (Exception e) {}
PolygonResult r = p.Compute();
return r.area;
}
public static void main(String[] args) {
double areaGeoLib = computeAreaWithGeographicLib();
double area = computeArea();
System.out.println("Area: " + (-1)*area + "\nArea(GeoLib): "+areaGeoLib);
}
}
Output
Area: 12245.282587113787
Area(GeoLib): 12254.95547034964
I found not very suitable for accurate use ( Yes, under 0.5% Error may be unaccurate for many environments) but useful to learn how to compute the area of a irregular Polygon.
Thx, Jaak, I had not seen this freen Symbol to click "Right Answer", now I have seen, I must explicitly. So, an "answer" is in initial post.

Get a Number from String with no default decimal separator

I have a TextInput where a need to return a Number.
My problem is that entered value is localized to a logged in user and that effects the decimal separator.
I seem to always get a NaN when i try to get a Number from a Polish user but it works great for English users:
Input example:
English: 23.5
Polish: 23,5
Is there a workaround for this? I have the following that doesn't work:
public function get myValue():Number {
var value:Number = new Number(StringUtil.trim(text)); //NaN with Polish
return value;
}
I have also tried the following but it also gives a NaN:
private function myValue(number:Number, precision:Number=2):Number{
var numberFormatter:NumberFormatter = getNumberFormatter(precision);
return new Number(numberFormatter.formatNumber(number));
}
private function getNumberFormatter(precision:Number=2):NumberFormatter{
var iso:String = ClientInfo.instance.language.ISOCode;
var formattedIso:String = iso.substr(0, 2)+'_'+iso.substr(2,2);
var numberFormatter:NumberFormatter = new NumberFormatter(formattedIso);
numberFormatter.fractionalDigits = precision;
numberFormatter.trailingZeros = true;
return numberFormatter;
}
When I debug the code I can see that the NumberFormatter works correctly but its always the call to new Number("23,5") that gives a NaN.
Can't test it now, but I guess it should work:
public function get myValue():Number
{
var value:Number = getNumberFormatter.parseNumber(StringUtil.trim(text));
return value;
}
I think the key is, that you should use parseNumber()!
[Update]
Here is a FlexUnit test for better understanding:
[Test]
public function test(): void
{
var number: Number = new NumberFormatter("de-DE").parseNumber("23,5");
assertEquals(23.5, number);
number = new NumberFormatter("en-US").parseNumber("23.5");
assertEquals(23.5, number);
number = new NumberFormatter("de-DE").parseNumber("1.023,456");
assertEquals(1023.456, number);
number = new NumberFormatter("pl-PL").parseNumber("1023,45");
assertEquals(1023.45, number);
number = new NumberFormatter("pl-PL").parseNumber("1.023,45");
assertTrue(isNaN(number));
number = new NumberFormatter("pl-PL").parseNumber("1 023,45");
assertEquals(1023.45, number);
number = new NumberFormatter("pl-PL").parseNumber(" 10 531 023,45 ");
assertEquals(10531023.45, number);
}
As you can see NumberFormatter handles decimal and thousands separator correctly.
If you want to format it back, then you could use it like this:
var numFmt: NumberFormatter = new NumberFormatter("pl-PL");
assertEquals("23,50", numFmt.formatNumber(numFmt.parseNumber(" 23,5 ")));
numFmt.fractionalDigits = 1;
assertEquals("23,6", numFmt.formatNumber(numFmt.parseNumber(" 23,57 ")));
Assuming your numbers are not being returned with commas between each 10^3 number group (i.e. 1,000,000 for 1 million), you could just use a replace on the commas.
Number("23,5".replace(",","."); // output Number( "23.5" ) = 23.5
That will replace all commas in the number with a period and should be read as a normal number by the system.

How do I add ROW_NUMBER to a LINQ query or Entity?

I'm stumped by this easy data problem.
I'm using the Entity framework and have a database of products. My results page returns a paginated list of these products. Right now my results are ordered by the number of sales of each product, so my code looks like this:
return Products.OrderByDescending(u => u.Sales.Count());
This returns an IQueryable dataset of my entities, sorted by the number of sales.
I want my results page to show the rank of each product (in the dataset). My results should look like this:
Page #1
1. Bananas
2. Apples
3. Coffee
Page #2
4. Cookies
5. Ice Cream
6. Lettuce
I'm expecting that I just want to add a column in my results using the SQL ROW_NUMBER variable...but I don't know how to add this column to my results datatable.
My resulting page does contain a foreach loop, but since I'm using a paginated set I'm guessing using that number to fake a ranking number would NOT be the best approach.
So my question is, how do I add a ROW_NUMBER column to my query results in this case?
Use the indexed overload of Select:
var start = page * rowsPerPage;
Products.OrderByDescending(u => u.Sales.Count())
.Skip(start)
.Take(rowsPerPage)
.AsEnumerable()
.Select((u, index) => new { Product = u, Index = index + start });
Actually using OrderBy and then Skip + Take generates ROW_NUMBER in EF 4.5 (you can check with SQL Profiler).
I was searching for a way to do the same thing you are asking for and I was able to get what I need through a simplification of Craig's answer:
var start = page * rowsPerPage;
Products.OrderByDescending(u => u.Sales.Count())
.Skip(start)
.Take(rowsPerPage)
.ToList();
By the way, the generated SQL uses ROW_NUMBER > start and TOP rowsPerPage.
Try this
var x = Products.OrderByDecending(u => u.Sales.Count());
var y = x.ToList();
for(int i = 0; i < y.Count; i++) {
int myNumber = i; // this is your order number
}
As long as the list stays in the same order, which should happen unless the sales number changes. You could be able to get an accurate count;
There is also this way of doing it.
var page = 2;
var count = 10;
var startIndex = page * count;
var x = Products.OrderByDecending(u => u.Sales.Count());
var y = x.Skip(startIndex).Take(count);
This gives the start index for the page, plus it gives you a small set of sales to display on the page. You just start the counting on your website at startIndex.
Here is a long winded answer. First create a class to house the number/item pair like so:
public class NumberedItem<T>
{
public readonly int Number;
public readonly T Item;
public NumberedItem(int number, T item)
{
Item = item;
Number = number;
}
}
Next comes an abstraction around a page of items (numbered or not):
class PageOf<T> : IEnumerable<T>
{
private readonly int startsAt;
private IEnumerable<T> items;
public PageOf(int startsAt, IEnumerable<T> items)
{
this.startsAt = startsAt;
this.items = items;
}
public IEnumerable<NumberedItem<T>> NumberedItems
{
get
{
int index = 0;
foreach (var item in items)
yield return new NumberedItem<T>(startsAt + index++, item);
yield break;
}
}
public IEnumerator<T> GetEnumerator()
{
foreach (var item in items)
yield return item;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
Once you have that you can "Paginate" a particular queryable collection using this:
class PaginatedQueryable<T>
{
private readonly int PageSize;
private readonly IQueryable<T> Source;
public PaginatedQueryable(int PageSize, IQueryable<T> Source)
{
this.PageSize = PageSize;
this.Source = Source;
}
public PageOf<T> Page(int pageNum)
{
var start = (pageNum - 1) * PageSize;
return new PageOf<T>(start + 1, Source.Skip(start).Take(PageSize));
}
}
And finally a nice extension method to cover the ugly:
static class PaginationExtension
{
public static PaginatedQueryable<T> InPagesOf<T>(this IQueryable<T> target, int PageSize)
{
return new PaginatedQueryable<T>(PageSize, target);
}
}
Which means you can now do this:
var products = Products.OrderByDescending(u => u.Sales.Count()).InPagesOf(20).Page(1);
foreach (var product in products.NumberedItems)
{
Console.WriteLine("{0} {1}", product.Number, product.Item);
}

Resources