Converting grid coordinates - math

So I have a grid which is in one form and im trying to get the X and Y.
Is there a formula where I could turn for example 12 into 2,2 or 14 to 2,3
Also is there a name for this type of grid?
static int getX(int z)
{
int count = 0;
int res = 0;
int curr = 0;
for(int temp = z; temp > 0; temp >>= 1)
{
if(count % 2 ==0)
{
res += ((temp & 1) << curr);
curr++;
}
count++;
}
return res;
}
static int getY(int z)
{
int count = 0;
int res = 0;
int curr = 0;
for(int temp = z; temp > 0; temp >>= 1)
{
if(count % 2 ==1)
{
res += ((temp & 1) << curr);
curr++;
}
count++;
}
return res;
}

As Sneftel observed, this looks like a Z-order curve. As such, you can convert coordinates by interleaving binary representations. So your examples are
0 1 0 x=2 0 1 0 x=2
0 1 0 y=2 0 1 1 y=3
001100 p=12 001110 p=14
So to get x and y coordinates from the cell number p, you assign the bits of p alternatingly to x and y. This kind of bit arithmetic is pretty hard to express using elementary arithmetic operations, and there is no generally recognized formula symbol for this that I'm aware of, but the idea is quite simple.

Related

Setting Base Cases for Recursive Function

class Solution {
//given a location on the matrix, this function recursively find the deepest possible depth, which is the length of a side of a found square
private int isSquare(int row_index, int col_index, int depth, char[][] matrix) {
int last_row = row_index + depth;
int last_col = col_index + depth;
if (row_index >= matrix.length || col_index >= matrix[0].length) {
return 0;
}
if (last_row >= matrix.length || last_col >= matrix[0].length) {
return 0;
}
for (int i = col_index; i < last_col; i++) {
if (matrix[row_index][i] != '1') {
return 0;
}
}
for (int i = row_index; i < last_row; i++ ) {
if (matrix[i][col_index] != '1') {
return 0;
}
}
return Math.max(depth, isSquare(row_index, col_index, depth + 1, matrix));
}
public int maximalSquare(char[][] matrix) {
int max = 0;
for (int row = 0; row < matrix.length; row ++) {
for (int col = 0; col <matrix[0].length; col ++) {
int curr_depth = isSquare(row, col, 1, matrix);
if (curr_depth > max) {
max = curr_depth;
}
}
};
return max * max;
}
}
Hi, I was working on LeetCode 221, and it seems like that my solution is not passing test cases with output 1, where the biggest square on the given matrix is just 1 x 1. To me it looks like those depth 1 cases are not passing the two for loops in function isSquare, which is supposed to catch 0s in the square.
I tried LC debugging tool but it did not help much, and my base cases seem fine to me. Please let me know what is going on here. For the problem, https://leetcode.com/problems/maximal-square/
One of the depth 1 test cases that I am failing is below.
Input:
[["0","1"],["1","0"]]
Output:
0
Expected:
1

What is an algorithm to generate the following sequence?

I want to find out the function to generate the sequence with the following pattern.
1 2 3 1 1 2 2 3 3 1 1 1 1 2 2 2 2 3 3 3 3 ....
Where the lower bound number is 1 upper number bound number is 3. Each time numbers start from 1 and each number repeats 2 ^ n times, with n starting with 0.
Here it goes, I hope it will help.
#include <iostream>
#include <math.h>
int main(){
for(int n = 0; n < 5;n++){
for(int i = 1; i < 4;i++){
for(int j = 0;j < pow(2,n) ;j++){
std::cout << i;
}
}
}
return 0;
}
Here is a code in C++:
#include <iostream>
#include <cmath>
int main()
{
// These are the loop control variables
int n, m, i, j, k;
// Read the limit
cin >> n;
// Outermost loop to execute the pattern {1..., 2..., 3...} n times
for (i = 0; i < n; ++i)
{
// This loop generates the required numbers 1, 2, and 3
for (j = 1; j <= 3; ++j)
{
// Display the generated number 2^i times
m = pow(2, i);
for (k = 0; k < m; ++k)
{
std::cout << j << ' ';
}
}
}
}
You can use the same logic in any language you choose to implement it.

how to send 100 digit in serial communication from processing to arduino

i am converting pixel array to String and send this String to arduino. but i Think this String is not converted properly because Serial.write send (8 bit or 8 character) i don’t know. and also want to send 100 character of string into Serial .
please send your suggestion and getting help me out of this problem.
for any mistake Sorry in advance.
for(int x =0 ; x < img.height; x++)
{
for(int y=0; y <img.width; y++)
{
int i = x+y*width;
if(img.pixels[i] == color(0,0,0))
{
i=1;
}
else
{
i=0;
}
String s = str(i);
print(s);
Serial.write(s);
delay(2);
}
}
and also tell me how to stop string after 100 character by not using ("\n" or "\r" )
It seems you are looking for the code below:
for (int x = 0; x < img.height; x++) { // iterate over height
for (int y = 0; y < img.width; y++) { // iterate over width
int i = x + y * width;
if (img.pixels[i] == color(0, 0, 0)) { // determine if zero
Serial.write('1'); // send non zero char
} else {
Serial.write('0'); // send zero char
}
}
Serial.write("\n\r");
}
If you want to cluster your output in units the size of img.width you could do this:
for (int x = 0; x < img.height; x++) { // iterate over height
String s;
for (int y = 0; y < img.width; y++) { // iterate over width
int i = x + y * width;
if (img.pixels[i] == color(0, 0, 0)) { // determine if zero
s += '1'; // append a non zero char to string s
} else {
s += '0'; // append a zero char to string s
}
}
Serial.println(s);
}
Please remember:
Serial.write outputs raw binary value(s).
Serial.print outputs character(s).
Serial.println outputs character(s) and appends a newline character to output.
I have serious doubts about this calculation int i = x+y*width; as your data is probably structured as:
vertical data: 0 1 2
horizontal data: [row 0][row 1][row 2]
Instead of:
horizontal data: 0 1 2
vertical data: [column 0][column 1][column 2]

count distinct prime factors

I have to count number of distinct prime factors over 2 to 100000, Is there any fast method than what I am doing ?
i.e.. 2 has 1 distinct prime factor 2
10 has 2 distinct prime factor (2,5)
12 has 2 distinct prime factor (2,3)
My code :-
#include<stdio.h>
#include<math.h>
typedef unsigned long long ull;
char prime[100000]={0};
int P[10000],fact[100000],k;
void sieve()
{
int i,j;
P[k++]=2;
for(i=3;i*i<1000;i+=2)
{
if(!prime[i])
{
P[k++]=i;
for(j=i*i;j<100000;j+=i+i)
prime[j] = 1;
}
}
for(i=1001;i<100000;i+=2)
if(!prime[i])
P[k++]=i;
}
int calc_fact() {
int root,i,count,j;
fact[1]=fact[2]=fact[3]=1;
for(i=4;i<=100000;i++) {
count=0;
root=i/2+1;
for(j=0;P[j]<=root;j++) {
if(i%P[j]==0)count++;
}
if(count==0) fact[i]=1;
else fact[i]=count;
}
return 0;
}
int main(){
int i;
sieve();
calc_fact();
for(i=1;i<10000;i++) printf("%d ,",fact[i]);
return 0;
}
You can easily adapt the sieve of Erasthotenes to count the number of prime factors a number has.
Here's an implementation in C, along with some tests:
#include <stdio.h>
#define N 100000
static int factorCount[N+1];
int main(void)
{
int i, j;
for (i = 0; i <= N; i++) {
factorCount[i] = 0;
}
for (i = 2; i <= N; i++) {
if (factorCount[i] == 0) { // Number is prime
for (j = i; j <= N; j += i) {
factorCount[j]++;
}
}
}
printf("2 has %i distinct prime factors\n", factorCount[2]);
printf("10 has %i distinct prime factors\n", factorCount[10]);
printf("11111 has %i distinct prime factors\n", factorCount[11111]);
printf("12345 has %i distinct prime factors\n", factorCount[12345]);
printf("30030 has %i distinct prime factors\n", factorCount[30030]);
printf("45678 has %i distinct prime factors\n", factorCount[45678]);
return 0;
}
You can definitely do better by making a sieve of Eratosthenes.
In Python
N = 100000
M = int(N**.5) # M is the floor of sqrt(N)
nb_of_fact = [0]*N
for i in xrange(2,M):
if nb_of_fact[i] == 0: # test wether i is prime
for j in xrange(i,N,i): # loop through the multiples of i
nb_of_fact[j] += 1
for i in xrange(M,N):
if nb_of_fact[i] == 0:
nb_of_fact[i] = 1
At the end of the loop, nb_of_fact[i] is the number of prime factors of i (in particular it is 1 if and only if i is prime).
Older wrong version
N = 100000
nb_of_fact = [1]*N
for i in xrange(2,N):
if nb_of_fact[i] == 1: # test wether i is prime
for j in xrange(2*i,N,i): # loop through the multiples of i
nb_of_fact[j] += 1

Determine position of number in a grid of numbers centered around 0 and increasing in spiral

I've got the following grid of numbers centered around 0 and increasing in spiral. I need an algorithm which would receive number in spiral and return x; y - numbers of moves how to get to that number from 0. For example for number 9 it would return -2; -1. For 4 it would be 1; 1.
25|26|... etc.
24| 9|10|11|12
23| 8| 1| 2|13
22| 7| 0| 3|14
21| 6| 5| 4|15
20|19|18|17|16
This spiral can be slightly changed if it would help the algorithm to be better.
Use whatever language you like. I would really appreciate mathematical explanation.
Thank you.
First we need to determine which cycle (distance from center) and sector (north, east, south or west) we are in. Then we can determine the exact position of the number.
The first numbers in each cycle is as follows: 1, 9, 25
This is a quadratic sequence: first(n) = (2n-1)^2 = 4n^2 - 4n + 1
The inverse of this is the cycle-number: cycle(i) = floor((sqrt(i) + 1) / 2)
The length of a cycle is: length(n) = first(n+1) - first(n) = 8n
The sector will then be:
sector(i) = floor(4 * (i - first(cycle(i))) / length(cycle(i)))
Finally, to get the position, we need to extrapolate from the position of the first number in the cycle and sector.
To put it all together:
def first(cycle):
x = 2 * cycle - 1
return x * x
def cycle(index):
return (isqrt(index) + 1)//2
def length(cycle):
return 8 * cycle
def sector(index):
c = cycle(index)
offset = index - first(c)
n = length(c)
return 4 * offset / n
def position(index):
c = cycle(index)
s = sector(index)
offset = index - first(c) - s * length(c) // 4
if s == 0: #north
return -c, -c + offset + 1
if s == 1: #east
return -c + offset + 1, c
if s == 2: #south
return c, c - offset - 1
# else, west
return c - offset - 1, -c
def isqrt(x):
"""Calculates the integer square root of a number"""
if x < 0:
raise ValueError('square root not defined for negative numbers')
n = int(x)
if n == 0:
return 0
a, b = divmod(n.bit_length(), 2)
x = 2**(a+b)
while True:
y = (x + n//x)//2
if y >= x:
return x
x = y
Example:
>>> position(9)
(-2, -1)
>>> position(4)
(1, 1)
>>> position(123456)
(-176, 80)
Do you mean something like this? I did not implement any algorithm and the code can be written better but it works - that's always a start :) Just change the threshold value for whatever you wish and you'll get the result.
static int threshold=14, x=0, y=0;
public static void main(String[] args) {
int yChange=1, xChange=1, count=0;
while( !end(count) ){
for (int i = 0; i < yChange; i++) {
if( end(count) )return;
count++;
y--;
}
yChange++;
for (int i = 0; i < xChange; i++) {
if( end(count) )return;
count++;
x++;
}
xChange++;
for (int i = 0; i < yChange; i++) {
if( end(count) )return;
count++;
y++;
}
yChange++;
for (int i = 0; i < xChange; i++) {
if( end(count) )return;
count++;
x--;
}
xChange++;
}
}
public static boolean end(int count){
if(count<threshold){
return false;
}else{
System.out.println("count: "+count+", x: "+x+", y: "+y);
return true;
}
}

Resources