AS3 random algorithm - algorithm

I need a suggestion. I want to have a function that returns random numbers from let say 1 to 100, with condition to not repeat the chosen number. It is something like chess table that will be filled with something random and not one thing over another thing... If someone can tell a suggestion I'll be very happy. Thanks.

Create an Array of 100 numbers (1..100), then 'sort' the Array by 'random'. You can then pull out the numbers one at a time working your way through the array.
I haven't tested the code below but I had these snippets available that you could piece together to achieve the intended result.
public static function randomNumber(min:Number, max:Number):Number{
var rnd:Number = Math.floor((Math.random()*((max+1)-min))+min);
return rnd;
}
public static function randomize(arr:Array):Array{
var len:Number = arr.length;
var rnd:Number;
var tmp:Object;
for(var i:Number=0;i<len;i++){
rnd = randomNumber(0,(len-1));
tmp = arr[i];
arr[i] = arr[rnd];
arr[rnd] = tmp;
}
return arr;
}
var setOfNumbers:Array = new Array();
for(var i:int=0;i<100;i++){
setOfNumbers[i] = (i+1);
}
var shuffledSetOfNumbers:Array = randomize(setOfNumbers);
Notes:
For the purists this "randomizing" isn't "truly" random (if you're writing a Card shuffler for a Vegas gambling machine you'll want to use something different - case in point!)
My randomNumber and randomize functions above are static as I've typically included them that way in the apps I've needed them but you don't have to use it this way
My original lib used Number vs int or uint for some of the variables for more options when used but feel free to clean that up

also like that...
package
{
import flash.display.Sprite;
import flash.events.Event;
/**
* ...
* #author Vadym Gordiienko
*/
public class Main extends Sprite
{
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
var startArray:Array = generateNumberArray(100);
var randomArray:Array = randomArray(startArray);
trace("startArray = " + startArray);
trace("randomArray = " + randomArray);
}
/**
* generate Array of numbers by length
* #param length
* #return Array of numbers
*/
public static function generateNumberArray(length:int):Array
{
var numberArray:Array = [];
for (var i:int = 0; i < length; i++)
{
numberArray[i] = i+1;
}
return numberArray;
}
/**
* generate randomly mixed array by input array
* #param inputArray - simple not mixed array
* #return Array - mixed array
*/
public static function randomArray(inputArray:Array):Array
{
var randomArray:Array = [];
var tempArray:Array = [];
for (var i:int = 0; i < inputArray.length; i++)
{
tempArray.push(inputArray[i]);
}
while (tempArray.length)
{
var randomNumber:int = Math.round(Math.random() * (tempArray.length - 1));// get random number of left array
randomArray.push( tempArray[randomNumber] );
tempArray.splice(randomNumber, 1); // remove randomed element from temporary aarray
}
tempArray = null;
delete [tempArray];
return randomArray;
}
}
}

Related

JavaScript Sorting a Function That Has multiple Numbers

I am trying to create a Random Lottery Number Generator code but I am having issues sorting the numbers from lower to greater. Here is my code of getting the numbers but I can't seem to figure out how to sort them.
function ball(){
let ball = Math.ceil(Math.random() * 70);
console.log(ball);
}
function whiteBalls(){
for(let i = 1; i <= 5; i++){
ball();
}
}
whiteBalls();
I've tried many different ways but keep getting errors. Thank you in advance.
Store the result in an array and sort the array:
function ball() {
return Math.ceil(Math.random() * 70);
}
function whiteBalls() {
let result = []
for(let i = 0; i < 5; i++) {
result.push(ball());
}
return result.sort()
}
console.log(whiteBalls());

Generate an array of random numbers not present in a list dart

so i have a list of predefined numbers where each number consists of 6 numbers like this {1,2,3,4,5,6 ; 34,52,3,76,12,4 ; 53,1,4,76,23,5 ; .... }
each individual number in the group of numbers range from 1 to 99,
import 'dart:math';
main() {
var rng = new Random();
var l = new List.generate(12, (_) => rng.nextInt(100));
}
i want to generate an array of 6 different random numbers using dart in a way that it is not already present in the list of numbers i already have.
import 'dart:math';
void main() {
var listOfSets = List<Set<int>>();
final int nElementsWithMax = 99;
final int kTaken = 6;
final int requiredResults = 3;
for (int i = 0; i < requiredResults; i++) {
bool isInList = false;
Set<int> anewSet;
do {
anewSet = Set.of(listRandom(nElementsWithMax, kTaken));
isInList = listOfSets.firstWhere(
(setInList) => anewSet.intersection(setInList).length == anewSet.length,
orElse: () => null)
!= null;
} while (isInList);
listOfSets.add(anewSet);
}
print(listOfSets);
}
List<int> listRandom(int maxNumber, int numberOfGenerations) {
final random = Random();
var currentOptions = List<int>.generate(maxNumber, (i) => i);
var list = List.generate(numberOfGenerations, (_) {
final index = random.nextInt(currentOptions.length);
final result = currentOptions[index];
currentOptions.removeAt(index);
return result;
});
return list;
}
Keep in mind that you cannot exceed the combination limit defined here.
In your case, requiredResults cannot exceed (100!)/((6! * (100 - 6)!) ... some huge number

Calulate two random numbers in flutter

I'm trying to generate two different random numbers and add those together, but Flutter doesn't seem to like my math. I keep getting the message that '+' isn't defined for the class Random.
import 'package:flutter/material.dart';
import 'dart:math';
void main() => runApp(MaterialApp(
title: 'Random Numbers',
theme: ThemeData(primarySwatch: Colors.orange),
home: MyHome(),
));
class MyHome extends StatefulWidget {
#override
_MyHomeState createState() => _MyHomeState();
}
class _MyHomeState extends State<MyHome> {
#override
Widget build(BuildContext context) {
var num1 = new Random();
for (var i = 0; i < 10; i++) {
print(num1.nextInt(10));
}
var num2 = new Random();
for (var i = 0; i < 10; i++) {
print(num2.nextInt(10));
}
//var sum = num1 + num2;
return Container();
}
}
My goal is to display it something like this: "2 + 5 = "
where the user will fill in the answer. If correct do this else do that.
The error is telling you that you're trying to add two Random objects, and not two numbers. You're printing them correctly, using nextInt() on your loops, but when you try to sum them, you're using the original variable of the type Random.
Try this:
class _MyHomeState extends State<MyHome> {
#override
Widget build(BuildContext context) {
// Instantiate a Random class object
var numGenerator = new Random();
//You don't need a second loop because it was the same exact code,
//only with a different variable name.
for (var i = 0; i < 10; i++) {
print(numGenerator.nextInt(10));
}
// Save the numbers you generated. Each call to nextInt returns a new one
var num1 = numGenerator.nextInt(10);
var num2 = numGenerator.nextInt(10);
var sum = num1 + num2;
//use num1, num2 and sum as you like
return Container();
}
}
Thank you very much Gerorge and Sorry for my abscense.
I got some help to solve this through dart
Random seed = Random();
const int MAX_VALUE = 10;
int val1 = seed.nextInt(MAX_VALUE);
int val2 = seed.nextInt(MAX_VALUE);
int sum = val1 + val2;
print('$val1 + $val2 = $sum');

Feature Detection Opencv/Javacv not working

I am trying to run the feature detection program of javacv to compare the similar features in 2 images however I am getting a runtimeexception. Since I am completely new to javacv I don't know how to resolve this.
The exception trace is
OpenCV Error: Assertion failed (queryDescriptors.type() == trainDescCollection[0].type()) in unknown function, file ..\..\..\src\opencv\modules\features2d\src\matchers.cpp, line 351
Exception in thread "main" java.lang.RuntimeException: ..\..\..\src\opencv\modules\features2d\src\matchers.cpp:351: error: (-215) queryDescriptors.type() == trainDescCollection[0].type()
at com.googlecode.javacv.cpp.opencv_features2d$DescriptorMatcher.match(Native Method)
at Ex7DescribingSURF.main(Ex7DescribingSURF.java:63)
Here is the source code
import static com.googlecode.javacv.cpp.opencv_core.NORM_L2;
import static com.googlecode.javacv.cpp.opencv_core.cvCreateImage;
import static com.googlecode.javacv.cpp.opencv_features2d.drawMatches;
import static com.googlecode.javacv.cpp.opencv_highgui.cvLoadImage;
import java.util.Arrays;
import java.util.Comparator;
import javax.swing.JFrame;
import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.cpp.opencv_core.CvMat;
import com.googlecode.javacv.cpp.opencv_core.CvScalar;
import com.googlecode.javacv.cpp.opencv_core.CvSize;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
import com.googlecode.javacv.cpp.opencv_features2d.BFMatcher;
import com.googlecode.javacv.cpp.opencv_features2d.DMatch;
import com.googlecode.javacv.cpp.opencv_features2d.DescriptorExtractor;
import com.googlecode.javacv.cpp.opencv_features2d.DrawMatchesFlags;
import com.googlecode.javacv.cpp.opencv_features2d.KeyPoint;
import com.googlecode.javacv.cpp.opencv_nonfree.SURF;
public class Ex7DescribingSURF {
/**
* Example for section "Describing SURF features" in chapter 8, page 212.
*
* Computes SURF features, extracts their descriptors, and finds best
* matching descriptors between two images of the same object. There are a
* couple of tricky steps, in particular sorting the descriptors.
*/
public static void main(String[] args) {
IplImage img = cvLoadImage("A.jpg");
IplImage template = cvLoadImage("B.jpg");
IplImage images[] = { img, template };
// Setup SURF feature detector and descriptor.
double hessianThreshold = 2500d;
int nOctaves = 4;
int nOctaveLayers = 2;
boolean extended = true;
boolean upright = false;
SURF surf = new SURF(hessianThreshold, nOctaves, nOctaveLayers,
extended, upright);
DescriptorExtractor surfDesc = DescriptorExtractor.create("SURF");
KeyPoint keyPoints[] = { new KeyPoint(), new KeyPoint() };
CvMat descriptors[] = new CvMat[2];
// Detect SURF features and compute descriptors for both images
for (int i = 0; i < 1; i++) {
surf.detect(images[i], null, keyPoints[i]);
// Create CvMat initialized with empty pointer, using simply `new
// CvMat()` leads to an exception.
descriptors[i] = new CvMat(null);
surfDesc.compute(images[i], keyPoints[i], descriptors[i]);
}
// Create feature matcher
BFMatcher matcher = new BFMatcher(NORM_L2, true);
DMatch matches = new DMatch();
// "match" is a keyword in Scala, to avoid conflict between a keyword
// and a method match of the BFMatcher,
// we need to enclose method name in ticks: `match`.
matcher.match(descriptors[0], descriptors[1], matches, null);
System.out.println("Matched: " + matches.capacity());
// Select only 25 best matches
DMatch bestMatches = selectBest(matches, 25);
// Draw best matches
IplImage imageMatches = cvCreateImage(new CvSize(images[0].width()
+ images[1].width(), images[0].height()), images[0].depth(), 3);
drawMatches(images[0], keyPoints[0], images[1], keyPoints[1],
bestMatches, imageMatches, CvScalar.BLUE, CvScalar.RED, null,
DrawMatchesFlags.DEFAULT);
CanvasFrame canvas = new CanvasFrame("");
canvas.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
canvas.showImage(imageMatches);
}
// ----------------------------------------------------------------------------------------------------------------
/** Select only the best matches from the list. Return new list. */
private static DMatch selectBest(DMatch matches, int numberToSelect) {
// Convert to Scala collection for the sake of sorting
int oldPosition = matches.position();
DMatch a[] = new DMatch[matches.capacity()];
for (int i = 0; i < a.length; i++) {
DMatch src = matches.position(i);
DMatch dest = new DMatch();
copy(src, dest);
a[i] = dest;
}
// Reset position explicitly to avoid issues from other uses of this
// position-based container.
matches.position(oldPosition);
// Sort
DMatch aSorted[] = a;
Arrays.sort(aSorted, new DistanceComparator());
// DMatch aSorted[]=sort(a);
// Create new JavaCV list
DMatch best = new DMatch(numberToSelect);
for (int i = 0; i < numberToSelect; i++) {
// Since there is no may to `put` objects into a list DMatch,
// We have to reassign all values individually, and hope that API
// will not any new ones.
copy(aSorted[i], best.position(i));
}
// Set position to 0 explicitly to avoid issues from other uses of this
// position-based container.
best.position(0);
return best;
}
private static void copy(DMatch src, DMatch dest) {
// TODO: use Pointer.copy() after JavaCV/JavaCPP 0.3 is released
// (http://code.google.com/p/javacpp/source/detail?r=51f4daa13d618c6bd6a5556ff2096d0e834638cc)
// dest.put(src)
dest.distance(src.distance());
dest.imgIdx(src.imgIdx());
dest.queryIdx(src.queryIdx());
dest.trainIdx(src.trainIdx());
}
static class DistanceComparator implements Comparator<DMatch> {
public int compare(DMatch o1, DMatch o2) {
if (o1.compare(o2))
return -1;
else
return 1;
}
};
}
Does anybody know what I might need more to make this work.. Any help appreciated
As the error clearly says that descriptor types does not match. You have to check for the condition if the descriptor types match.
A simple if statement before matcher.match would solve your problem
if (descriptors[0].type() == descriptors[1].type())
{
matcher.match(descriptors[0], descriptors[1], matches, null);
System.out.println("Matched: " + matches.capacity());
}
The CvMat was not initialized properly which was giving the error.
descriptors[i] = new CvMat(null);
Instead I put it like this which solved the problem.
descriptors[i] = CvMat.create(1, 1);
Don't know if still needed, but I found answer. In code there's problem with this loop:
for (int i = 0; i < 1; i++) {
surf.detect(images[i], null, keyPoints[i]);
// Create CvMat initialized with empty pointer, using simply `new
// CvMat()` leads to an exception.
descriptors[i] = new CvMat(null);
surfDesc.compute(images[i], keyPoints[i], descriptors[i]);
}
i is just 0, than the loop exits and you try to use object descriptors[1] which is absent.
Change it to for( int i = 0, i < 2, i++) {

Get nearby locations using google places api in php/codeigniter

I have to fetch results of nearby locations within 2 km of my given latitude/longitude values. Have to do it using Google Places API. Details go here:
http://code.google.com/apis/maps/documentation/javascript/places.html
They have provided a sample code in javascript. But I need to have this in php. Can anyone give me any idea how may I achieve it? Or how may I use this same javascript code in my php controller class? [I am using code igniter framework]. I have been stuck on this issue for so many hours. It will be great if someone can provide a sample php code. Highly appreciate any assistance.
Here is the code of my controller class:
<?php
class Welcome extends CI_Controller {
public function index()
{
$config = "";
//$this->load->library('googlemaps');
$this->load->library('googlemaps');
$config['center'] = '37.4419, -122.1419';
$config['zoom'] = 'auto';
$config['places'] = TRUE;
$config['placesLocation'] = '37.4419, -122.1419';
$config['placesRadius'] = 200;
$this->googlemaps->initialize($config);
$data['map'] = $this->googlemaps->create_map();
$this->load->view('map_view', $data);
}
}
?>
This is the error I encounter while I try to run the above code:
Fatal error: Using $this when not in object context in /Applications/XAMPP/xamppfiles/htdocs/ciplaces/application/controllers/mapcontroller.php on line 9
I am accessing my code using this url:
http://localhost/ciplaces/index.php/mapcontroller
Thanks
I've got a CodeIgniter library that has integration with the Google Maps and Places API. You can find information and download the library here:
http://biostall.com/codeigniter-google-maps-v3-api-library
A demo of the 'Places' integration can also be found below:
http://biostall.com/demos/google-maps-v3-api-codeigniter-library/places
Give me a shout if you have any questions or require any changes made to the library and I'll be happy to help out where I can.
Cheers
I have done something simular in PHP using the Lumb algorithm.
You should be able to get something from the code below (sits in my model, but you can put in anywhere).
public function search($start_latitude, $start_longitude, $radius, $radius_type, $offset, $limit)
{
$results = array();
$locations = array();
$sql = "SELECT `location_id`, `latitude`, `longitude` FROM `table`";
$query = $this->db->query($sql);
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$geo_data = $this->_bearing_distance_calc($start_latitude, $start_longitude, $row->latitude, $row->longitude, $radius_type);
$geo_data['radius_type'] = $radius_type;
if($geo_data['distance'] <= $radius)
{
// radial serach results
$locations[] = $row->location_id;
}
}
// return amount requested
$results['total'] = count($locations);
$results['locations'] = array_slice($locations, $offset, $limit);
return $results;
}
else
{
// no results
return FALSE;
}
}
/**
* Calculate Distance Between two points.
*
* This method is used to calculate the distance between to geographical points. <br />
* Used by the search method.
*
* #access private
*
* #param float $device_latitude
* #param float $device_longitude
* #param float $beach_latitude
* #param float $beach_longitude
* #param integer $radius_type
*
* #return array
*/
private function _bearing_distance_calc($start_latitude, $start_longitude, $building_latitude, $building_longitude, $radius_type)
{
// using Rhumb lines(or loxodrome)
// convert to rads for php trig functions
$start_latitude = deg2rad($start_latitude);
$start_longitude = deg2rad($start_longitude);
$building_latitude = deg2rad($building_latitude);
$building_longitude = deg2rad($building_longitude);
// testing variables
//$start_latitude = deg2rad(39.4422);
//$start_longitude = deg2rad(-122.0307);
//$building_latitude = deg2rad(49.4422);
//$building_longitude = deg2rad(-112.0307);
// calculate delta of lat and long
$delta_latitude = $building_latitude-$start_latitude;
$delta_longitude = $building_longitude-$start_longitude;
// earth radius
if ($radius_type == 'miles') // using miles
{
$earth_radius = 3959;
}
else // using kilometers
{
$earth_radius = 6371;
}
// now lets start mathing !!
// cast types
$dPhi = log(tan($building_latitude/2+M_PI/4)/tan($start_latitude/2+M_PI/4));
if ($dPhi != 0)
{
$q = $delta_latitude/$dPhi;
}
else
{
$q = cos($start_latitude);
}
//$q = (!is_nan($delta_latitude/$dPhi)) ? $delta_latitude/$dPhi : cos($start_latitude); // E-W line gives dPhi=0
// if dLon over 180° take shorter rhumb across 180° meridian:
if (abs($delta_longitude) > M_PI)
{
$delta_longitude = $delta_longitude>0 ? -(2*M_PI-$delta_longitude) : (2*M_PI+$delta_longitude);
}
$geo_data = array();
$geo_data['distance'] = sqrt($delta_latitude*$delta_latitude + $q*$q*$delta_longitude*$delta_longitude) * $earth_radius;
$bearing = rad2deg(atan2($delta_longitude, $dPhi));
if($bearing < 0)
{
$bearing = 360 + $bearing;
}
$geo_data['bearing'] = $bearing;
return $geo_data;
}

Resources