Why I cant solve this puzzle? - dart

Im tring to solve this puzzle by using dart lang but I didint solve it and I got large number + error! There is an puzzle image to understand it from here
can you help or give me a tip to solve this puzzle ~!
See full code :
import 'dart:math';
void main() {
var value;
int loob = 0;
do {
var z = new Random().nextInt(20);
var x = new Random().nextInt(20);
var y = new Random().nextInt(20);
var n = new Random().nextInt(20);
if (z - x == 9) {
print('DONE LOOB1 Z = $z and X = $x');
do {
var x = new Random().nextInt(20);
var n = new Random().nextInt(20);
if (x + n == 2) {
print('DONE LOOB2 X = $x and n = $n ');
do {
var n = new Random().nextInt(20);
var y = new Random().nextInt(20);
if (y - n == 14) {
print('DONE LOOB3 y = $y and n = $n ');
do {
var z = new Random().nextInt(20);
var y = new Random().nextInt(20);
if (z - y == 12) {
print('DONE LOOB4 z = $z and y = $y ');
value = 1;
} else {}
} while (value != 1);
} else {}
} while (value != 1);
value = 1;
} else {}
} while (value != 1);
value = 1;
} else {
null;
}
print(++loob);
} while (value != 1);
}
reslate code :
DONE LOOB1 Z = 11 and X = 2
DONE LOOB2 X = 2 and n = 0
DONE LOOB3 y = 14 and n = 0
DONE LOOB4 z = 17 and y = 5
Finshed

this is your algorithm issue, you are adding 0.1 to your variable every step, and it means all numbers are equal in the end you must create two mathematical equations and two unknown values and then solve them. this is the main approach to solve such problems.
Assume this picture like these Equations:
x - y = 9
x + n = 2
y - n = 14
z - y = 12
now you have 4 equations and 4 unknown.
you can solve this equation by this (Matrix manipulation) or this (substitution one unknown with another) on method.

Related

Why at high circle division, the cone not complete itself?

I created in webgl a javascript file that needs to draw a cone. If I choose a low circle division, it work perfectly, and all the lines are displayed. But at high one, high from 255, it breaks. It seems not all of the vertices are linked. I can not understand why the difference.
case 'cone':{
var CONE_DIV = 255;
var angolo = 360 / CONE_DIV;
var altezza = 1.0;
// Coordinates
var vertices = [];
vertices.push(0.0); //v0t X
vertices.push(0.0); //v0t Y
vertices.push(0.0); //v0t Z
vertices.push(0.0); //v0 X
vertices.push(altezza); //v0 Y
vertices.push(0.0); //v0 Z
for (var i = 0; i < CONE_DIV; i++) {
var ai = i * 2 * Math.PI / CONE_DIV;
var si = Math.sin(ai);
var ci = Math.cos(ai);
vertices.push(ci); //coordinate X
vertices.push(0.0); //coordinate Y
vertices.push(si); //coordinate Z
}
// Colors
var colors = [];
for (var k = 0; k < CONE_DIV; k++) {
for (var t = 0; t < 2; t++) {
colors.push(a);
colors.push(b);
colors.push(c);
}
}
// Indices of the vertices
var indices = [];
//index high vertex
for (var j = 1; j <= CONE_DIV; j++) {
indices.push(1);
indices.push(j+1);
var l = j + 2; //last vertex base - return to first
if (l == CONE_DIV + 2) {
indices.push(2);
} else {
indices.push(l);
}
}
//index base
for (var j = 1; j <= CONE_DIV; j++) {
indices.push(0);
indices.push(j+1);
var l = j+2;
if (l == CONE_DIV + 2) { //last vertex base - return to first
indices.push(2);
} else {
indices.push(l);
}
}

Finding path between two nodes in a graph using BFS and DFS

I'm following following links.
DFS: http://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/DepthFirstPaths.java.html
where pathTo methods is like this
public Iterable<Integer> pathTo(int v) {
validateVertex(v);
if (!hasPathTo(v)) return null;
Stack<Integer> path = new Stack<Integer>();
for (int x = v; x != s; x = edgeTo[x])
path.push(x);
path.push(s);
return path;
}
BFS: http://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/BreadthFirstPaths.java.html
where pathTo method is like this
public Iterable<Integer> pathTo(int v) {
validateVertex(v);
if (!hasPathTo(v)) return null;
Stack<Integer> path = new Stack<Integer>();
int x;
for (x = v; distTo[x] != 0; x = edgeTo[x])
path.push(x);
path.push(x);
return path;
}
My doubt is why for (x = v; distTo[x] != 0; x = edgeTo[x]) is used in BFS and for (int x = v; x != s; x = edgeTo[x]) in DFS. What will go wrong if I use x != s instead of distTo[x] != 0 in BFS's pathTo method ?
You are right in your observation, that the conditions x != s and distTo[x] != 0 are interchangeable. The reason is distTo[s] is 0, so loop breaks when we encounter the source vertex. So to break the loop when we encounter the source vertex, either of the two conditions will work.

Testcase failed after converting codes from Objective-C to Swift

I am doing some bitwise operations in Swift style, which these codes are originally written in Objective-C/C. I use UnsafeMutablePointer to state the beginning index of memory address and use UnsafeMutableBufferPointer for accessing the element within the scope.
You can access the original Objective-C file Here.
public init(size: Int) {
self.size = size
self.bitsLength = (size + 31) / 32
self.startIdx = UnsafeMutablePointer<Int32>.alloc(bitsLength * sizeof(Int32))
self.bits = UnsafeMutableBufferPointer(start: startIdx, count: bitsLength)
}
/**
* #param from first bit to check
* #return index of first bit that is set, starting from the given index, or size if none are set
* at or beyond its given index
*/
public func nextSet(from: Int) -> Int {
if from >= size { return size }
var bitsOffset = from / 32
var currentBits: Int32 = bits[bitsOffset]
currentBits &= ~((1 << (from & 0x1F)) - 1).to32
while currentBits == 0 {
if ++bitsOffset == bitsLength {
return size
}
currentBits = bits[bitsOffset]
}
let result: Int = bitsOffset * 32 + numberOfTrailingZeros(currentBits).toInt
return result > size ? size : result
}
func numberOfTrailingZeros(i: Int32) -> Int {
var i = i
guard i != 0 else { return 32 }
var n = 31
var y: Int32
y = i << 16
if y != 0 { n = n - 16; i = y }
y = i << 8
if y != 0 { n = n - 8; i = y }
y = i << 4
if y != 0 { n = n - 4; i = y }
y = i << 2
if y != 0 { n = n - 2; i = y }
return n - Int((UInt((i << 1)) >> 31))
}
Testcase:
func testGetNextSet1() {
// Passed
var bits = BitArray(size: 32)
for i in 0..<bits.size {
XCTAssertEqual(32, bits.nextSet(i), "\(i)")
}
// Failed
bits = BitArray(size: 34)
for i in 0..<bits.size {
XCTAssertEqual(34, bits.nextSet(i), "\(i)")
}
}
Can someone guide me why the second testcase fail but the objective-c version pass ?
Edit: As #vacawama mentioned: If you break testGetNextSet into 2 tests, both pass.
Edit2: When I run tests with xctool, and tests which calling BitArray's nextSet() will crash while running.
Objective-C version of numberOfTrailingZeros:
// Ported from OpenJDK Integer.numberOfTrailingZeros implementation
- (int32_t)numberOfTrailingZeros:(int32_t)i {
int32_t y;
if (i == 0) return 32;
int32_t n = 31;
y = i <<16; if (y != 0) { n = n -16; i = y; }
y = i << 8; if (y != 0) { n = n - 8; i = y; }
y = i << 4; if (y != 0) { n = n - 4; i = y; }
y = i << 2; if (y != 0) { n = n - 2; i = y; }
return n - (int32_t)((uint32_t)(i << 1) >> 31);
}
When translating numberOfTrailingZeros, you changed the return value from Int32 to Int. That is fine, but the last line of the function is not operating properly as you translated it.
In numberOfTrailingZeros, replace this:
return n - Int((UInt((i << 1)) >> 31))
With this:
return n - Int(UInt32(bitPattern: i << 1) >> 31)
The cast to UInt32 removes all but the lower 32 bits. Since you were casting to UInt, you weren't removing those bits. It is necessary to use bitPattern to make this happen.
Finally I found out that startIdx just need to be initialized after allocation.
self.startIdx = UnsafeMutablePointer<Int32>.alloc(bitsLength * sizeof(Int32))
self.startIdx.initializeFrom(Array(count: bitsLength, repeatedValue: 0))
Or use calloc with just one line code:
self.startIdx = unsafeBitCast(calloc(bitsLength, sizeof(Int32)), UnsafeMutablePointer<Int32>.self)
Furthermore, I use lazy var to defer the Initialization of UnsafeMutableBufferPointer until the property is first used.
lazy var bits: UnsafeMutableBufferPointer<Int32> = {
return UnsafeMutableBufferPointer<Int32>(start: self.startIdx, count: self.bitsLength)
}()
On the other hand, don't forget to deinit:
deinit {
startIdx.destroy()
startIdx.dealloc(bitsLength * sizeof(Int32))
}

How to iterate through pixels in clockwise direction rather usual row column scanning in swift?

Project is to find boundary of an image and the given idea is to find the bigger difference of pixel values between clockwise pixel locations zeroing in on the center of the image thereby finding the boundary pixel locations. Any way we can iterate through pixels in clockwise direction ?
The usual row column scan doesn't work for finding pixel difference along boundary of the image.
for y in 0..<rgbaImage.height {
for x in 0..<rgbaImage.width {
let index = x * rgbaImage.height + y
var pixel = rgbaImage.pixels[index]
print("\((Int32(pixel.red) + Int32(pixel.green) + Int32(pixel.blue)) / 3)", terminator:" ")
Here is a quick example of looping in a spiral to build an n x n array. You can use the same approach to loop through an image.
Paste this into a playground to test:
//: Playground - noun: a place where people can play
var spiral = [[Int]](count: 5, repeatedValue: [Int](count: 5, repeatedValue: 0))
var n:Int = 5
var value:Int = 0
var minCol:Int = 0
var maxCol:Int = n-1
var minRow:Int = 0
var maxRow:Int = n-1
while value != n*n {
for var i = minCol; i <= maxCol; i += 1 {
spiral[minRow][i] = value;
value += 1;
}
for var i = minRow+1; i <= maxRow; i += 1 {
spiral[i][maxCol] = value;
value += 1;
}
for var i = maxCol-1; i >= minCol; i-- {
spiral[maxRow][i] = value;
value += 1;
}
for var i = maxRow-1; i >= minRow+1; i-- {
spiral[i][minCol] = value;
value += 1;
}
minCol += 1;
minRow += 1;
maxCol -= 1;
maxRow -= 1;
}
//loop through the array we just built
for var x = 0; x < n; x += 1 {
for var y = 0; y < n; y += 1 {
print(spiral[x][y],terminator: "\t")
}
print();
}
The output looks like this:
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8

Highcharts Scatter Plot - How to Fix Overlapping Data Labels?

I have seen many posts on this topic, but it doesn't seem the issue has ever been properly addressed.
We have a large scatter with about 30 points on it (nothing overwhelming). But in certain cases, the dots will be very close together or overlapping (not much we can really do about that, I guess).
The main problem is that we want the data labels visible at all times, and these data labels are overlapping when the points are close to each other.
We have tried allowOverlap: false, but that's not really what we need/want. Our ideal outcome is allowing all datalabels to be displayed on screen inside the scatter while still being able to read each one at all times.
Do we fix this by adjusting the separation of the dots or by adjusting the separation/padding of the datalabels? Any suggestions? Thank you.
I haven't found a working configuration solution of this problem from Highcharts (although I cannot guarantee there isn't one in latest version). However there are some algorithms for acceptable randomization of the labels coordinates that split data labels.
Here are some useful links that could help you with the algorithm:
wordcloud package in R (cloud.R is the file containing the algorithm)
direct labels package in R
And some dummy pseudo code translation in JavaScript of the R code would be:
splitLabels: function() {
// Create an array of x-es and y-es that indicate where your data lie
var xArr = getAllDataX();
var yArr = getAllDataY();
var labelsInfo = {};
this.chartSeries.forEach(function(el) {
var text = el.data.name;
labelsInfo[el.data.id] = {
height: getHeight(text),
width: getWidth(text),
text: text
};
}, this);
var sdx = getStandardDeviation(xArr);
var sdy = getStandardDeviation(yArr);
if(sdx === 0) sdx = 1;
if(sdy === 0) sdy = 1;
var boxes = [];
var xlim = [], ylim = [];
xlim[0] = this.chart.xAxis[0].getExtremes().min;
xlim[1] = this.chart.xAxis[0].getExtremes().max;
ylim[0] = this.chart.yAxis[0].getExtremes().min;
ylim[1] = this.chart.yAxis[0].getExtremes().max;
for (var i = 0; i < data.length; i++) {
var pointX = data[i].x;
var pointY = data[i].y;
if (pointX<xlim[0] || pointY<ylim[0] || pointX>xlim[1] || pointY>ylim[1]) continue;
var theta = Math.random() * 2 * Math.PI,
x1 = data[i].x,
x0 = data[i].x,
y1 = data[i].y,
y0 = data[i].y,
width = labelsInfo[data[i].id].width,
height = labelsInfo[data[i].id].height ,
tstep = Math.abs(xlim[1] - xlim[0]) > Math.abs(ylim[1] - ylim[0]) ? Math.abs(ylim[1] - ylim[0]) / 100 : Math.abs(xlim[1] - xlim[0]) / 100,
rstep = Math.abs(xlim[1] - xlim[0]) > Math.abs(ylim[1] - ylim[0]) ? Math.abs(ylim[1] - ylim[0]) / 100 : Math.abs(xlim[1] - xlim[0]) / 100,
r = 0;
var isOverlapped = true;
while(isOverlapped) {
if((!hasOverlapped(x1-0.5*width, y1-0.5*height, width, height, boxes)
&& x1-0.5*width>xlim[0] && y1-0.5*height>ylim[0] && x1+0.5*width<xlim[1] && y1+0.5*height<ylim[1]) )
{
boxes.push({
leftX: x1-0.5*width,
bottomY: y1-0.5*height,
width: width,
height: height,
icon: false,
id: data[i].id,
name: labelsInfo[data[i].id].text
});
data[i].update({
name: labelsInfo[data[i].id].text,
dataLabels: {
x: (x1 - data[i].x),
y: (data[i].y - y1)
}
}, false);
isOverlapped = false;
} else {
theta = theta+tstep;
r = r + rstep*tstep/(2*Math.PI);
x1 = x0+sdx*r*Math.cos(theta);
y1 = y0+sdy*r*Math.sin(theta);
}
}
}
// You may have to redraw the chart here
},
You can call this function on redraw or optimized to call it less often.
Please note that if you have some big points or shapes or icons indicating where your data items lie you will have to check if any of the proposed solutions does not interfere(overlap) with the icons as well.
You can try to adapt this algorithm:
function StaggerDataLabels(series) {
sc = series.length;
if (sc < 2) return;
for (s = 1; s < sc; s++) {
var s1 = series[s - 1].points,
s2 = series[s].points,
l = s1.length,
diff, h;
for (i = 0; i < l; i++) {
if (s1[i].dataLabel && s2[i].dataLabel) {
diff = s1[i].dataLabel.y - s2[i].dataLabel.y;
h = s1[i].dataLabel.height + 2;
if (isLabelOnLabel(s1[i].dataLabel, s2[i].dataLabel)) {
if (diff < 0) s1[i].dataLabel.translate(s1[i].dataLabel.translateX, s1[i].dataLabel.translateY - (h + diff));
else s2[i].dataLabel.translate(s2[i].dataLabel.translateX, s2[i].dataLabel.translateY - (h - diff));
}
}
}
}
}
//compares two datalabels and returns true if they overlap
function isLabelOnLabel(a, b) {
var al = a.x - (a.width / 2);
var ar = a.x + (a.width / 2);
var bl = b.x - (b.width / 2);
var br = b.x + (b.width / 2);
var at = a.y;
var ab = a.y + a.height;
var bt = b.y;
var bb = b.y + b.height;
if (bl > ar || br < al) {
return false;
} //overlap not possible
if (bt > ab || bb < at) {
return false;
} //overlap not possible
if (bl > al && bl < ar) {
return true;
}
if (br > al && br < ar) {
return true;
}
if (bt > at && bt < ab) {
return true;
}
if (bb > at && bb < ab) {
return true;
}
return false;
}
http://jsfiddle.net/menXU/6/

Resources