Recursive BinarySearch Problems - recursion

In my code I'm working on i have a binary search that is suppose to find specific numbers but as of right now i can't figure out why it tells me every single number isn't found. I am attempting to use recursion.
public class BinarySearch {
private static boolean binarySearch(int[] myList, int numberToFind) {
// So this will be your recursive method.
// Right now it just returns false.
// But you need to change this code.
return false;
}
public static void main(String[] args) {
// Create an array of sorted numbers
int[] evenList =
{ 2, 4, 9, 11, 17, 19, 22, 29, 30, 33,
39, 43, 46, 47, 51, 52, 54, 56, 58, 59,
63, 69, 70, 79, 88, 89, 92, 96, 98, 99 };
// Can we find every number?
for (int i = evenList.length -1; i >= 0; i--) {
if (binarySearch(evenList, evenList[i]))
System.out.printf("%d was found.\n\n", evenList[i]);
else
System.out.printf("%d was not found.\n\n", evenList[i]);
}
// Will we not find these numbers?
int[] testCases = { 1, 44, 100, 32 };
for (int i = 0; i > testCases.length; i--) {
if (binarySearch(evenList, testCases[i]))
System.out.printf("%d was found.\n\n", testCases[i]);
else
System.out.printf("%d was not found.\n\n", testCases[i]);
}
}
}

Well check out this code
private static boolean binarySearch(int[] myList, int numberToFind) {
// So this will be your recursive method.
// Right now it just returns false.
// But you need to change this code.
return false;
You need to implement that method before it will work.

Related

I'm getting error while running this on leetcode

Question:
Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
Return the running sum of nums.
Code:
class Solution {
public int[] runningSum(int[] nums) {
int[] ans = new int[nums.length];
for(int i = 0; i < nums.length; i++) {
ans[i] = nums[i] + nums[i+1];
}
return ans;
}
}
error:
java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
at line 6, Solution.runningSum
at line 54, __DriverSolution__.__helper__
at line 84, __Driver__.main

In JavaFX how to keep in the center of window a moving character drawn on a canvas?

I'm very new to JavaFX and currently working on a rouge like game in 2D, which uses GUI made with JavaFX. The moving character is drawn on the canvas with GraphicContext2D. There is only one canvas, and I'd like to solve my problem without overlaying if possible. Canvas is added to Borderpane as center, Scene created with this Borderpane, for the Stage this Scene was set. Canvas is redrawn after moving with character on KeyEvent. I've already made the Stage resizable. Everything is running well, with the exception that I just cannot keep my moving character on the center in the window and when canvas is bigger than the window it can move out of this window.
How can I keep my dear moving character in the middle?
OK, here is a very, very simplified version, but with same problem, character does not stay in middle, it can run off from window then return as canvas is set greater than window.
public class Main extends Application {
String[][] map = new String[40][20];
int[] playerCoords = {3,10};
//colored.png downloaded from https://kenney.nl/assets/bit-pack
Image tileset = new Image("/colored.png", 815 * 2, 373 * 2, true, false);
Canvas canvas = new Canvas(
20 * 32,
40 * 32);
GraphicsContext context = canvas.getGraphicsContext2D();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage){
BorderPane borderPane = new BorderPane();
borderPane.setCenter(canvas);
map[3][10] = "p";
refresh();
Scene scene = new Scene(borderPane);
scene.setOnKeyPressed(keyEvent -> {switch (keyEvent.getCode()) {
case UP:
this.movePlayer(true);
refresh();
break;
case DOWN:
this.movePlayer(false);
refresh();
break;}});
stage.setScene(scene);
stage.show();
}
void movePlayer(boolean up){
int direction = up ? -1 : 1;
int newPosRow = playerCoords[0] + direction;
if ( newPosRow >= 0 && newPosRow < map.length) {
map[playerCoords[0]][playerCoords[1]] = null;
playerCoords[0] = newPosRow;
map[playerCoords[0]][playerCoords[1]] = "p";
}
}
void refresh(){
context.setFill(Color.BLACK);
context.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
for (int i = 0; i < map.length; i++ ){
for (int j = 0; j < map[0].length; j++){
if (map[i][j] != null && map[i][j].equals("p")){
//player Tile 28, 0
context.drawImage(tileset, 952,0, 32,32,j * 32,i * 32, 32,32);
} else{
context.drawImage(tileset, 0,0, 32,32,j * 32,i * 32, 32,32);
}
}
}
}
}
Ok, so it seems there is not an easy JavaFX solution currently. But if someone knows one, thanks for sharing. :-)
In the meantime I thought about an algorythmic solution by transforming coords according to absolute and relative (player placed in middle) coordinates of the player. It's very far from perfect, it changes only the rowCoords of map, as the player can move only vertically in this example, and it works with a canvas not much greater than the window size. I needed to change only the refresh method. There is something I do not understand at the moment,
it works with substracting centerCol from player's row coord
int centerRow = map.length/2;
int centerCol = map[0].length/2;
int mapRowDiff = playerCoords[0] - centerCol;
not with substracting centerRow from player's row coord
int centerRow = map.length/2;
int centerCol = map[0].length/2;
int mapRowDiff = playerCoords[0] - centerRow;
But at least it started working.
And here is my refresh() with the transformation, it became a bit complex.
void refresh(){
context.setFill(Color.BLACK);
context.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
int centerRow = map.length/2;
int centerCol = map[0].length/2;
int mapRowDiff = playerCoords[0] - centerCol;
for (int i = 0; i < map.length; i++ ){
for (int j = 0; j < map[0].length; j++){
if (mapRowDiff >= 0
&& mapRowDiff < map.length) {
if (map[mapRowDiff][j] != null && map[mapRowDiff][j].equals("p")) {
//player Tile 28, 0
context.drawImage(tileset, 952, 0, 32, 32, j * 32, i * 32, 32, 32);
} else {
context.drawImage(tileset, 0, 0, 32, 32, j * 32, i * 32, 32, 32);
}
} else {
context.drawImage(tileset, 0, 34, 32, 32, j * 32, i * 32, 32, 32);
}
}
mapRowDiff++;
}
}

Haxe Maps vs Dynamic Object vs Fixed Object performance CPP

It seems maps in haxe are extremely slow vs dynamic objects
I would avoid them.
So using this code:
var nd=()->{
//var op:Dynamic = {x:100,y:1000};
//op.z = 22;
var op = {x:100,y:1000,z:22}
//var op = ['x'=>100,'y'=>1000];
//op['z'] = 22;
var i;
for(i in 0...1000000)
{
/*
op['x']++;
op['y']--;
op['z']++;
*/
op.x++;
op.y--;
op.z++;
}
trace('Line');
}
var j;
var q:Float = haxe.Timer.stamp();
for(j in 0...100) nd();
trace(haxe.Timer.stamp()-q);
Maps: 19 second
Dynamic Object: 9 seconds
Object: 0.6 seconds
It's amazing how slow maps are
It's not that maps are slow, it's that your test doesn't consider compiler optimizations. And it seems like it was ran in Debug mode?
Let's take a look at a slightly more verbose test (10x fewer iterations, shuffled order and averages):
import haxe.DynamicAccess;
class Main {
static inline var times = 10000;
static function testInline() {
var o = { x: 100, y: 1000, z: 22 };
for (_ in 0 ... times) {
o.x++;
o.y--;
o.z++;
}
}
static function getClass() {
return new Vector(100, 1000, 22);
}
static function testClass() {
var o = getClass();
for (_ in 0 ... times) {
o.x++;
o.y--;
o.z++;
}
}
static function testClassDynamic() {
var o:Dynamic = getClass();
for (_ in 0 ... times) {
o.x++;
o.y--;
o.z++;
}
}
static function getObj() {
return { x: 100, y: 1000, z: 22 };
}
static function testObj() {
var o = getObj();
for (_ in 0 ... times) {
o.x++;
o.y--;
o.z++;
}
}
static function testDynamic() {
var o:Dynamic = { x: 100, y: 1000, z: 22 };
for (_ in 0 ... times) {
o.x++;
o.y--;
o.z++;
}
}
static function testDynamicPlus() {
var o:Dynamic = { };
o.x = 100;
o.y = 1000;
o.z = 22;
for (_ in 0 ... times) {
o.x++;
o.y--;
o.z++;
}
}
static function testDynamicAccess() {
var o:DynamicAccess<Int> = getObj();
for (_ in 0 ... times) {
o["x"]++;
o["y"]--;
o["z"]++;
}
}
static function testMapString() {
var o = ["x" => 100, "y" => 1000, "z" => 22];
for (_ in 0 ... times) {
o["x"]++;
o["y"]--;
o["z"]++;
}
}
static function testMapInt() {
var o = [100 => 100, 200 => 1000, 300 => 22];
for (_ in 0 ... times) {
o[100]++;
o[200]--;
o[300]++;
}
}
static function shuffleSorter(a, b) {
return Math.random() > 0.5 ? 1 : -1;
}
static function main() {
var tests = [
new Test("inline", testInline),
new Test("class", testClass),
new Test("object", testObj),
new Test("object:Dynamic", testDynamic),
new Test("class:Dynamic", testClassDynamic),
new Test("object:Dynamic+", testDynamicPlus),
new Test("DynamicAccess", testDynamicAccess),
new Test("Map<String, Int>", testMapString),
new Test("Map<Int, Int>", testMapInt),
];
var shuffle = tests.copy();
var iterations = 0;
while (true) {
iterations += 1;
Sys.println("Step " + iterations);
for (i => v in shuffle) {
var k = Std.random(shuffle.length);
shuffle[i] = shuffle[k];
shuffle[k] = v;
}
for (test in shuffle) {
var t0 = haxe.Timer.stamp();
var fn = test.func;
for (_ in 0 ... 100) fn();
var t1 = haxe.Timer.stamp();
test.time += t1 - t0;
Sys.sleep(0.001);
}
for (test in tests) {
Sys.println('${test.name}: ${Math.ffloor(test.time / iterations * 10e6) / 1e3}ms avg');
}
Sys.sleep(1);
}
}
}
class Test {
public var time:Float = 0;
public var func:Void->Void;
public var name:String;
public function new(name:String, func:Void->Void) {
this.name = name;
this.func = func;
}
public function toString() return 'Test($name)';
}
class Vector {
public var x:Int;
public var y:Int;
public var z:Int;
public function new(x:Int, y:Int, z:Int) {
this.x = x;
this.y = y;
this.z = z;
}
}
And its output after a hundred or so "steps":
inline: 0.011ms avg
class: 15.737ms avg
object: 281.417ms avg
object:Dynamic: 275.509ms avg
class:Dynamic: 233.208ms avg
object:Dynamic+: 1208.83ms avg
DynamicAccess: 1021.248ms avg
Map<String, Int>: 1293.529ms avg
Map<Int, Int>: 916.552ms avg
Let's take a look at what each test compiles to.
Haxe-generated C++ code is formatted for readability
inline
This is what you were testing, although you have evidently suspected something judging by the commented out line.
If it seems suspiciously fast, that's because it is - the Haxe compiler noticed that your object is local and inlined it completely:
void Main_obj::testInline()
{
HX_STACKFRAME(&_hx_pos_e47a9afac0942eb9_5_testInline)
int o_x = 100;
int o_y = 1000;
int o_z = 22;
{
int _g = 0;
while ((_g < 10000))
{
_g = (_g + 1);
int _ = (_g - 1);
o_x = (o_x + 1);
o_y = (o_y - 1);
o_z = (o_z + 1);
}
}
}
Consequently, the C++ compiler might figure out that you aren't really doing anything in this function, at which point the contents are removed:
(whereas if you were to return o.z, the contents would be equivalent to return 10022 instead)
class
Let's talk about the things that you should be doing in a good case scenario.
Known field access on a class instance is very fast because it is compiled to a C++ class with direct field access:
::Vector Main_obj::getClass()
{
HX_GC_STACKFRAME(&_hx_pos_e47a9afac0942eb9_15_getClass)
return ::Vector_obj::__alloc(HX_CTX, 100, 1000, 22);
}
void Main_obj::testClass()
{
HX_STACKFRAME(&_hx_pos_e47a9afac0942eb9_17_testClass)
::Vector o = ::Main_obj::getClass();
{
int _g = 0;
while ((_g < 10000))
{
_g = (_g + 1);
int _ = (_g - 1);
o->x++;
o->y--;
o->z++;
}
}
}
Getting a class from a function call is required to prevent the Haxe compiler from inlining it; the C++ compiler may still collapse the for-loop.
object
Let's prevent the compiler from inlining the anonymous object by returning it from a function.
But it's still faster than a map.
Since dynamic objects are used pretty often (JSON and all), a few tricks are utilized - for instance, if you are creating an anonymous object with a set of predefined fields, additional work will be performed for these so that they can be accessed quicker (seen here as Create(n) and a subsequent chain of setFixed calls):
::Dynamic Main_obj::getObj()
{
HX_STACKFRAME(&_hx_pos_e47a9afac0942eb9_36_getObj)
return ::Dynamic(::hx::Anon_obj::Create(3)
->setFixed(0, HX_("x", 78, 00, 00, 00), 100)
->setFixed(1, HX_("y", 79, 00, 00, 00), 1000)
->setFixed(2, HX_("z", 7a, 00, 00, 00), 22));
}
void Main_obj::testObj()
{
HX_STACKFRAME(&_hx_pos_e47a9afac0942eb9_38_testObj)
::Dynamic o = ::Main_obj::getObj();
{
int _g = 0;
while ((_g < 10000))
{
_g = (_g + 1);
int _ = (_g - 1);
::hx::FieldRef((o).mPtr, HX_("x", 78, 00, 00, 00))++;
::hx::FieldRef((o).mPtr, HX_("y", 79, 00, 00, 00))--;
::hx::FieldRef((o).mPtr, HX_("z", 7a, 00, 00, 00))++;
}
}
}
You can see a handful of these tricks in Anon.cpp and Anon.h.
Dynamic
Same as above, but by typing the variable as Dynamic instead, and without an extra function call. Personally I wouldn't rely on this behaviour.
class:Dynamic
Although the code is effectively identical to above,
void Main_obj::testClassDynamic()
{
HX_STACKFRAME(&_hx_pos_e47a9afac0942eb9_26_testClassDynamic)
::Dynamic o = ::Main_obj::getClass();
{
int _g = 0;
while ((_g < 10000))
{
_g = (_g + 1);
int _ = (_g - 1);
::hx::FieldRef((o).mPtr, HX_("x", 78, 00, 00, 00))++;
::hx::FieldRef((o).mPtr, HX_("y", 79, 00, 00, 00))--;
::hx::FieldRef((o).mPtr, HX_("z", 7a, 00, 00, 00))++;
}
}
}
this runs a little faster. This is a accomplished by pre-generating functions for Reflection that will first check if the variable happens to be one of the predefined ones:
::hx::Val Vector_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 1:
if (HX_FIELD_EQ(inName,"x") ) { return ::hx::Val( x ); }
if (HX_FIELD_EQ(inName,"y") ) { return ::hx::Val( y ); }
if (HX_FIELD_EQ(inName,"z") ) { return ::hx::Val( z ); }
}
return super::__Field(inName,inCallProp);
}
DynamicAccess
Same as Dynamic, but we're also forcing the runtime to jump through a few (unnecessary) hoops with Reflect functions.
void Main_obj::testDynamicAccess()
{
HX_STACKFRAME(&_hx_pos_e47a9afac0942eb9_66_testDynamicAccess)
::Dynamic o = ::Main_obj::getObj();
{
int _g = 0;
while ((_g < 10000))
{
_g = (_g + 1);
int _ = (_g - 1);
{
::String tmp = HX_("x", 78, 00, 00, 00);
{
int value = ((int)((::Reflect_obj::field(o, tmp) + 1)));
::Reflect_obj::setField(o, tmp, value);
}
}
// ...
}
}
}
object:Dynamic+
We can disregard the aforementioned predefined field optimization by creating an empty Dynamic object and then filling it up with fields. This puts us pretty close to Map's performance.
void Main_obj::testDynamicPlus()
{
HX_STACKFRAME(&_hx_pos_e47a9afac0942eb9_55_testDynamicPlus)
::Dynamic o = ::Dynamic(::hx::Anon_obj::Create(0));
o->__SetField(HX_("x", 78, 00, 00, 00), 100, ::hx::paccDynamic);
o->__SetField(HX_("y", 79, 00, 00, 00), 1000, ::hx::paccDynamic);
o->__SetField(HX_("z", 7a, 00, 00, 00), 22, ::hx::paccDynamic);
{
int _g = 0;
while ((_g < 10000))
{
_g = (_g + 1);
int _ = (_g - 1);
::hx::FieldRef((o).mPtr, HX_("x", 78, 00, 00, 00))++;
::hx::FieldRef((o).mPtr, HX_("y", 79, 00, 00, 00))--;
::hx::FieldRef((o).mPtr, HX_("z", 7a, 00, 00, 00))++;
}
}
}
Map<String, Int>
Given that Map is unable to benefit from most of the above contextual optimizations (in fact, many wouldn't make sense for normal use cases), its performance should not be particularly surprising.
void Main_obj::testMapString()
{
HX_GC_STACKFRAME(&_hx_pos_e47a9afac0942eb9_74_testMapString)
::haxe::ds::StringMap _g = ::haxe::ds::StringMap_obj::__alloc(HX_CTX);
_g->set(HX_("x", 78, 00, 00, 00), 100);
_g->set(HX_("y", 79, 00, 00, 00), 1000);
_g->set(HX_("z", 7a, 00, 00, 00), 22);
::haxe::ds::StringMap o = _g;
{
int _g1 = 0;
while ((_g1 < 10000))
{
_g1 = (_g1 + 1);
int _ = (_g1 - 1);
{
::String tmp = HX_("x", 78, 00, 00, 00);
{
int v = ((int)((o->get(tmp) + 1)));
o->set(tmp, v);
}
}
// ...
}
}
}
Map<String, Int>
A bonus: to any or no surprise, computing a hash of an integer is cheaper than doing so for a string.
Conclusions
Don't be hasteful to write your code one or other way based on what a microbenchmark suggests. For example, although this might seem like an in-depth breakdown, it does not account for garbage collection nor optimization differences between various C++ compilers.

collapse list of int to list of ranges in kotlin

I have a list of ints that needs to be compressed to list of int ranges without loosing any information (there must be a way to reverse this operation).
Currently I have:
val ints = listOf(8, 9, 45, 48, 49, 60, 61, 61, 62, 63, 3, 4, 5, 4, 5, 6)
val out = ints
.map { it..it }
.fold(mutableListOf(ints[0]..(ints[0] - 1)),
{ acc, next ->
val prev = acc.last()
if (prev.last + 1 == next.first) {
acc[acc.lastIndex] = prev.first..next.last
} else {
acc.add(next)
}
acc
}).toList()
That correctly produces:
[8..9, 45..45, 48..49, 60..61, 61..63, 3..5, 4..6]
There are two aspects I dislike in my solution though,
it does not work for empty list because of fold's initial value
it's quite verbose for kotlin. I have a feeling that this can be resolved in bit nicer way.
So, the question is how to fix 1 and/or 2?
Thanks in advance!
Since you actually mutate the acc and return the same list of ranges at all iterations of fold, you may not really need the fold, that is, forEach is enough.
Then, mapping each number to it..it seems to be redundant here.
Taking the two notes above into account leads to the following, a bit simplified, version of your solution:
val result = mutableListOf<IntRange>()
ints.forEach {
val lastRange = result.lastOrNull()
if (lastRange?.endInclusive == it - 1)
result[result.lastIndex] = lastRange.first..it
else
result += it..it
}
UPD: with the addition of buildList to the Kotlin standard library, you can rewrite the above as:
val result = buildList {
ints.forEach {
val last = lastOrNull()
if (last?.endInclusive == it -1) {
set(lastIndex, last.start..it)
} else {
add(it..it)
}
}
}
My solution doesn't look much different, but I was able to fix your empty list issue:
val out = ints.fold(mutableListOf<IntRange>()) { acc, next ->
acc.apply {
if(isNotEmpty() && last().endInclusive.inc() == next) {
this[lastIndex] = this[lastIndex].start .. next
} else {
add(next..next)
}
}
}
It's also a bit less mapping, and using apply takes away some of the verbosity and having to refer to acc at the end.

Calling atan function on Blackberry 4.2 JDE

I need to calculate the arc tan value from my Blackberry Java app. Unfortunately, the blackberry 4.2 api doesn't have the Math.atan() function. Version 4.6 of the Blackberry JDE has it, but not 4.2.
Does anyone know of a workaround to calculate atan?
From Arctan in J2ME by Stephen Zimmerman:
// calculation functions
public class Calculation {
// Because J2ME has no floating point numbers,
// some sort of fixed point math is required.
// My implementation is simply to shift 10 places.
// for example, 1024 (>> 10) = 1
// and 512 (>> 10) = 0.5
public static final int[] AtanTable = { 0, 1, 2, 3, 5, 6, 7, 8, 10, 11, 12,
13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 29,
30, 30,31, 32, 33, 34, 35, 36, 37, 37, 38, 39, 40, 40, 41,
42, 43, 43, 44, 45 };
// / returns angle 0->359 in degrees
public static int atan(int Y, int X) {
boolean swap = false;
int top = Math.abs(Y);
int bottom = Math.abs(X);
if (top > bottom) {
int btemp = bottom;
bottom = top;
top = btemp;
swap = true;
} else if (bottom == 0)
return -300;
// this should keep index inbounds [0, 45]
int index = (top * 45) / bottom;
int angle = AtanTable[index];
if (swap)
angle = 90 - angle;
// X & Y += 180
// X & !Y = ...90
// !X & Y = ... 270
if ((X < 0) && (Y < 0))
angle += 180;
else if (Y < 0) {
angle = 90 - angle;
angle += 270;
} else if (X < 0) {
angle = 90 - angle;
angle += 90;
}
if (angle == 360)
angle = 0;
return angle;
}
}
When all else fails, one could probably obtain a decent value by estimating the result of an infinite series of the arctan function.
The Wikipedia page on inverse trigonometic functions has a section on the infinite series of inverse trigonometric functions, including arctan. In order to obtain an estimate, one would carry out the infinite series until the desired precision is obtained.
As for the reason why the arctan function is not included, it is probably because the processor in the Blackberry isn't very powerful, and would take a lot of processor resources to perform the calculation.
Also, looking at the Blackberry JDE 4.2 API documentation, there appears to be a fixed-point math library called Fixed32 which offers two flavors of arctan. They perform the calculation with 32-bit integers, so they probably offer some performance advantages over performing floating-point arithmetic.
Here is the function I use (no guarantees that it is very fast):
/** Square root from 3 */
final static public double SQRT3 = 1.732050807568877294;
static public double atan(double x)
{
boolean signChange=false;
boolean Invert=false;
int sp=0;
double x2, a;
// check up the sign change
if(x<0.)
{
x=-x;
signChange=true;
}
// check up the invertation
if(x>1.)
{
x=1/x;
Invert=true;
}
// process shrinking the domain until x<PI/12
while(x>Math.PI/12)
{
sp++;
a=x+SQRT3;
a=1/a;
x=x*SQRT3;
x=x-1;
x=x*a;
}
// calculation core
x2=x*x;
a=x2+1.4087812;
a=0.55913709/a;
a=a+0.60310579;
a=a-(x2*0.05160454);
a=a*x;
// process until sp=0
while(sp>0)
{
a=a+Math.PI/6;
sp--;
}
// invertation took place
if(Invert) a=Math.PI/2-a;
// sign change took place
if(signChange) a=-a;
//
return a;
}
I had the same problem... the missing math functions can be found in the following package:
net.rim.device.api.util.MathUtilities
First implement the standard arctan(x) using Taylor series (as described at http://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Infinite_series)
The do the following before calling arctan:
1) First do this check.
if (x == 0) {
return 0;
}
2) if |x| > 1, compute arctan(1/x) and finally subtract the result from Pi/2
3) if |x| is close to 1, compute arctan of the half angle using the half angle formula
arctan(x) = 2*arctan(x/(1+sqrt(1+x*x))). That is, first compute the half angle and then multiply the result by 2. Otherwise, for |x| close to 1, arctan converges very slowly.

Resources