how to describe this series in code? - algorithm

i would like to find a formula describing this series.
i need to set a boolean depending on a positive integer.
it's pretty simple but i am stuck and feel a bit stupid.
0 false
1 true
2 true
3 false
4 false
5 true
6 true
7 false
8 false
9 true
10 true
11 false
12 false
...
so the flag changes at every odd number

Well, for the flag changing at every odd number, it looks like your boolean should be true if and only if (n+3)%4 <= 1, where % is the modulo operator:
n (n+3)%4 Boolean
-- ------- -------
0 3 false
1 0 true
2 1 true
3 2 false
4 3 false
5 0 true
6 1 true
7 2 false
8 3 false
9 0 true
10 1 true
11 2 false
12 3 false
:: : : :
I've deliberately added three instead of subtracting one, since some languages have different ideas of what the modulo operator should do for negative numbers. And keep in mind that this is language-agnostic. If you're specifically looking for a C or C-like language solution, see the excellent answer here from Christoffer Hammarström ((n + 1) & 2 just in case it ever disappears) - this is far more succinct in those particular languages.

In C and other languages where non-zero is true: (n + 1) & 2, and in other languages: (n + 1) & 2 != 0.

You can first divide the int value by 2 and then check if it is even or odd.
boolean flag = ((i+1)/2)%2!=0;
Maybe there is an off-by-one error, so check this.
N (N+1)/2 ((N+1)/2)%2 compare != 0
0 0 0 false
1 1 1 true
2 1 1 true
3 2 0 false
4 2 0 false
5 3 1 true
6 3 1 true
7 4 0 false
8 4 0 false
9 5 1 true
...

Flag changes at every odd number, means the last bit is set to 1.
1 => 01, 3 => 11, ... 9 => 1001, 11 => 1011
and so on..
so, u can just check the last bit at each step and whenever it is 1, flip the flag.

Related

Find minimum number of horizontal and vertical lines to seperate 1's with other 1's?

I have 2 rows and n columns.
I have to find the minimum number of lines required to separate 1 from other 1. For example:
Let n= 6
0 0 1 0 1 1
1 0 0 1 0 1
I need to draw 1 horizontal line between these 2 rows.
2 vertical lines after index(starts from 0) 2 and after index 4 till the bottom.
So total lines = 1+2 = 3.
Note that lines can be of any length i.e. it can be of length of one column but number of lines should be minimum and each 1(number of matrix) should be separated from other 1.
Another example to clarify this more:
Let n = 7
1 0 1 0 0 1 1
0 1 0 0 1 0 0
In this example I need 1 horizontal line and 2 vertical lines.
One vertical line after index 1 and other after index 5(line of length equal to column).
So total lines = 1+2 = 3.
Please provide me solution with least time complexity.
It seems as if the horizontal line is part of an optimal solution whenever both rows have at least one 1 (there are also cases when an optimal solution has only vertical lines, but you will always be able to switch one of these vertical lines for a horizontal one). So we can take that as given (the other case is easy to detect and easy to solve).
Then, you do not really have many options on how many lines to put. This makes it quite easily solvable. Traverse the rows simultaneously from left to right. Whenever you encounter a 1, check if you need to put a line. Here is some pseudo-code:
topRowHas1 := false
bottomRowHas1 := false
lines := 1 //the horizontal line
for location from 0 to n - 1 (inclusive)
if (topRow[location] == 1 && topRowHas1) || (bottomRow[location] == 1 && bottomRowHas1)
//we have to add a vertical line
lines++
topRowHas1 := false
bottomRowHas1 := false
end if
topRowHas1 |= topRow[location] == 1
bottomRowHas1 |= bottomRow[location] == 1
next
And here is the execution for your example
0 0 1 0 1 1
1 0 0 1 0 1
location topRowHas1 bottomRowHas1 lines
------------------------------------------
false false 1
0 false true 1
1 false true 1
2 true true 1
3 false false 2 //vertical line here
false true 2
4 true true 2
5 false false 3 //vertical line here
true true 3
So we have one horizontal line, one vertical line before position 3, and one vertical line before position 5.

Efficiently construct a square matrix with unique numbers in each row

A matrix of size nxn needs to be constructed with the desired properties.
n is even. (given as input to the algorithm)
Matrix should contain integers from 0 to n-1
Main diagonal should contain only zeroes and matrix should be symmetric.
All numbers in each row should be different.
For various n , any one of the possible output is required.
input
2
output
0 1
1 0
input
4
output
0 1 3 2
1 0 2 3
3 2 0 1
2 3 1 0
Now the only idea that comes to my mind is to brute-force build combinations recursively and prune.
How can this be done in a iterative way perhaps efficiently?
IMO, You can handle your answer by an algorithm to handle this:
If 8x8 result is:
0 1 2 3 4 5 6 7
1 0 3 2 5 4 7 6
2 3 0 1 6 7 4 5
3 2 1 0 7 6 5 4
4 5 6 7 0 1 2 3
5 4 7 6 1 0 3 2
6 7 4 5 2 3 0 1
7 6 5 4 3 2 1 0
You have actually a matrix of two 4x4 matrices in below pattern:
m0 => 0 1 2 3 m1 => 4 5 6 7 pattern => m0 m1
1 0 3 2 5 4 7 6 m1 m0
2 3 0 1 6 7 4 5
3 2 1 0 7 6 5 4
And also each 4x4 is a matrix of two 2x2 matrices with a relation to a power of 2:
m0 => 0 1 m1 => 2 3 pattern => m0 m1
1 0 3 2 m1 m0
In other explanation I should say you have a 2x2 matrix of 0 and 1 then you expand it to a 4x4 matrix by replacing each cell with a new 2x2 matrix:
0 => 0+2*0 1+2*0 1=> 0+2*1 1+2*1
1+2*0 0+2*0 1+2*1 0+2*1
result => 0 1 2 3
1 0 3 2
2 3 0 1
3 2 1 0
Now expand it again:
0,1=> as above 2=> 0+2*2 1+2*2 3=> 0+2*3 1+2*3
1+2*2 0+2*2 1+2*3 0+2*3
I can calculate value of each cell by this C# sample code:
// i: row, j: column, n: matrix dimension
var v = 0;
var m = 2;
do
{
var p = m/2;
v = v*2 + (i%(n/p) < n/m == j%(n/p) < n/m ? 0 : 1);
m *= 2;
} while (m <= n);
We know each row must contain each number. Likewise, each row contains each number.
Let us take CS convention of indices starting from 0.
First, consider how to place the 1's in the matrix. Choose a random number k0, from 1 to n-1. Place the 1 in row 0 at position (0,k0). In row 1, if k0 = 1 in which case there is already a one placed. Otherwise, there are n-2 free positions and place the 1 at position (1,k1). Continue in this way until all the 1 are placed. In the final row there is exactly one free position.
Next, repeat with the 2 which have to fit in the remaining places.
Now the problem is that we might not be able to actually complete the square. We may find there are some constraints which make it impossible to fill in the last digits. The problem is that checking a partially filled latin square is NP-complete.(wikipedia) This basically means pretty compute intensive and there no know short-cut algorithm. So I think the best you can do is generate squares and test if they work or not.
If you only want one particular square for each n then there might be simpler ways of generating them.
The link Ted Hopp gave in his comment Latin Squares. Simple Construction does provide a method for generating a square starting with the addition of integers mod n.
I might be wrong, but if you just look for printing a symmetric table - a special case of latin squares isomorphic to the symmetric difference operation table over a powerset({0,1,..,n}) mapped to a ring {0,1,2,..,2^n-1}.
One can also produce such a table, using XOR(i,j) where i and j are n*n table indexes.
For example:
def latin_powerset(n):
for i in range(n):
for j in range(n):
yield (i, j, i^j)
Printing tuples coming from previously defined special-case generator of symmetric latin squares declared above:
def print_latin_square(sq, n=None):
cells = [c for c in sq]
if n is None:
# find the length of the square side
n = 1; n2 = len(cells)
while n2 != n*n:
n += 1
rows = list()
for i in range(n):
rows.append(" ".join("{0}".format(cells[i*n + j][2]) for j in range(n)))
print("\n".join(rows))
square = latin_powerset(8)
print(print_latin_square(square))
outputs:
0 1 2 3 4 5 6 7
1 0 3 2 5 4 7 6
2 3 0 1 6 7 4 5
3 2 1 0 7 6 5 4
4 5 6 7 0 1 2 3
5 4 7 6 1 0 3 2
6 7 4 5 2 3 0 1
7 6 5 4 3 2 1 0
See also
This covers more generic cases of latin squares, rather than that super symmetrical case with the trivial code above:
https://www.cut-the-knot.org/arithmetic/latin2.shtml (also pointed in the comments above for symmetric latin square construction)
https://doc.sagemath.org/html/en/reference/combinat/sage/combinat/matrices/latin.html

How do I shorten execution time by replacing the while-loop?

I have written a small code in Octave and part of it is checking whether values in the first rows of two matrices are equal, and if so, adding the value of the second row of the second matrix to the value of the second row of the first matrix.
This is that part of the code that I have written, using a small set of data:
PositionLoadArray =
1 5 3 7 4 6 9 2 1 2
1 2 3 4 5 6 7 8 9 10
X =
0 1 2 3 4 5 6 7 8 9
0 0 0 0 0 0 0 0 0 0
x=1; #row number in matrix X
y=1; #row number in matrix PositionLoadArray
while y<=columns(PositionLoadArray)
if PositionLoadArray(1,y)==X(1,x)
X(2,x)=X(2,x)+PositionLoadArray(,y);
y=y+1;
x=1;
else
x=x+1;
endif
endwhile
This gives the result:
X =
0 1 2 3 4 5 6 7 8 9
0 10 18 3 5 2 6 4 0 7
The loop runs and works perfectly for small sets like the one above (i.e. where the total number of columns for X and PositionLoadArray (max. values of x and y, respectively) are small). But the loop takes hours to be executed with larger values.
How can I reduce the execution time and get the same result?
Try
X(2, X(1,:) == Y(1,:)) += Y(2, X(1,:) == Y(1,:))

Represent integers on d digits using smallest possible base

I'd like to create a function where for an arbitrary integer input value (let's say unsigned 32 bit) and a given number of d digits the return value will be a d digit B base number, B being the smallest base that can be used to represent the given input on d digits.
Here is a sample input - output of what I have in mind for 3 digits:
Input Output
0 0 0 0
1 0 0 1
2 0 1 0
3 0 1 1
4 1 0 0
5 1 0 1
6 1 1 0
7 1 1 1
8 0 0 2
9 0 1 2
10 1 0 2
11 1 1 2
12 0 2 0
13 0 2 1
14 1 2 0
15 1 2 1
16 2 0 0
17 2 0 1
18 2 1 0
19 2 1 1
20 0 2 2
21 1 2 2
22 2 0 2
23 2 1 2
24 2 2 0
25 2 2 1
26 2 2 2
27 0 0 3
28 0 1 3
29 1 0 3
30 1 1 3
.. .....
The assignment should be 1:1, for each input value there should be exactly one, unique output value. Think of it as if the function should return the nth value from the list of strangely sorted B base numbers.
Actually this is the only approach I could come up so far with - given an input value, generate all the numbers in the smallest possible B base to represent the input on d digits, then apply a custom sorting to the results ('penalizing' the higher digit values and putting them further back in the sort), and return the nth value from the sorted array. This would work, but is a spectacularly inefficient implementation - I'd like to do this without generating all the numbers up to the input value.
What would be an efficient approach for implementing this function? Any language or pseudocode is fine.
MBo's answer shows how to find the smallest base that will represent an integer number with a given number of digits.
I'm not quite sure about the ordering in your example. My answer is based on a different ordering: Create all possible n-digit numbers up to base b (e.g. all numbers up to 999 for max. base 10 and 3 digits). Sort them according to their maximum digit first. Numbers are sorted normalls within a group with the same maximum digit. This retains the characteristic that all values from 8 to 26 must be base 3, but the internal ordering is different:
8 0 0 2
9 0 1 2
10 0 2 0
11 0 2 1
12 0 2 2
13 1 0 2
14 1 1 2
15 1 2 0
16 1 2 1
17 1 2 2
18 2 0 0
19 2 0 1
20 2 0 2
21 2 1 0
22 2 1 1
23 2 1 2
24 2 2 0
25 2 2 1
26 2 2 2
When your base is two, life is easy: Just generate the appropriate binary number.
For other bases, let's look at the first digit. In the example above, five numbers start with 0, five start with 1 and nine start with 2. When the first digit is 2, the maximum digit is assured to be 2. Therefore, we can combine 2 with a 9 2-digit numbers of base 3.
When the first digit is smaller than the maximum digit in the group, we can combine it with the 9 2-digit numbers of base 3, but we must not use the 4 2-digit numbers that are ambiguous with the 4 2-digit numbers of base 2. That gives us five possibilites for the digits 0 and 1. These possibilities – 02, 12, 20, 21 and 22 – can be described as the unique numbers with two digits according to the same scheme, but with an offset:
4 0 2
5 1 2
6 2 0
7 2 1
8 2 2
That leads to a recursive solution:
for one digit, just return the number itself;
for base two, return the straightforward representation in base 2;
if the first number is the maximum digit for the determined base, combine it with a straighforward representations in that base;
otherwise combine it with a recursively determined representation of the same algorithm with one fewer digit.
Here's an example in Python. The representation is returned as list of numbers, so that you can represent 2^32 − 1 as [307, 1290, 990].
import math
def repres(x, ndigit, base):
"""Straightforward representation of x in given base"""
s = []
while ndigit:
s += [x % base]
x /= base
ndigit -= 1
return s
def encode(x, ndigit):
"""Encode according to min-base, fixed-digit order"""
if ndigit <= 1:
return [x]
base = int(x ** (1.0 / ndigit)) + 1
if base <= 2:
return repres(x, ndigit, 2)
x0 = (base - 1) ** ndigit
nprev = (base - 1) ** (ndigit - 1)
ncurr = base ** (ndigit - 1)
ndiff = ncurr - nprev
area = (x - x0) / ndiff
if area < base - 1:
xx = x0 / (base - 1) + x - x0 - area * ndiff
return [area] + encode(xx, ndigit - 1)
xx0 = x0 + (base - 1) * ndiff
return [base - 1] + repres(x - xx0, ndigit - 1, base)
for x in range(32):
r = encode(x, 3)
print x, r
Assuming that all values are positive, let's make simple math:
d-digit B-based number can hold value N if
Bd > N
so
B > N1/d
So calculate N1/d value, round it up (increment if integer), and you will get the smallest base B.
(note that numerical errors might occur)
Examples:
d=2, N=99 => 9.95 => B=10
d=2, N=100 => 10 => B=11
d=2, N=57 => 7.55 => B=8
d=2, N=33 => 5.74 => B=6
Delphi code
function GetInSmallestBase(N, d: UInt32): string;
const
Digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var
Base, i: Byte;
begin
Base := Ceil(Power(N, 1/d) + 1.0E-12);
if Base > 36 then
Exit('Big number, few digits...');
SetLength(Result, d);
for i := d downto 1 do begin
Result[i] := Digits[1 + N mod Base]; //Delphi string is 1-based
N := N div Base;
end;
Result := Result + Format(' : base [%d]', [Base]);
end;
begin
Memo1.Lines.Add(GetInSmallestBase(99, 2));
Memo1.Lines.Add(GetInSmallestBase(100, 2));
Memo1.Lines.Add(GetInSmallestBase(987, 2));
Memo1.Lines.Add(GetInSmallestBase(1987, 2));
Memo1.Lines.Add(GetInSmallestBase(87654321, 6));
Memo1.Lines.Add(GetInSmallestBase(57, 2));
Memo1.Lines.Add(GetInSmallestBase(33, 2));
99 : base [10]
91 : base [11]
UR : base [32]
Big number, few digits...
H03LL7 : base [22]
71 : base [8]
53 : base [6]

Division algorithm with decimal bignum

EDIT: I rebased my bignum class to use std::bitset and I just implemented long division fine. I just didn't know any class to store bits. (like std::bitset)
I'm making a bignum class with std::string to use decimal characters as internal representation. I tried implementing division with a simple algorithm:
while N ≥ D do
N := N - D
end
return N
And of course it was slow. I tried implementing long division but that was too hard to do with decimal characters.
Thanks in advance.
Instead of subtracting D very often you could try to find the highest value of the form
D^2n and sub this. Than repeat that steps with the remaining value until the remaining is less than D.
Pseudocode
0 result=0
1 powerOfD = D
2 while (powerOfD*powerOfD<N)
3 powerOfD=powerOfD*powerOfD
4 result = result+powerOfD/D, N=N-powerOfD;
5 if(N>D)
6 goto 1
7 return result
Example 31/3 (N=31, D=3)
0 result=0
1 powerD = 3;
2 3*3 < 31 TRUE
3 powerOfD= 3*3;
2 9*9 < 31 FALSE
4 result=0+9/3; N=31 - 9
5 22> 3 TRUE
6 goto 1
1 powerD = 3
2 3*3 < 22 TRUE
3 powerOfD= 3*3;
2 9*9 < 31 FALSE
4 result=3+9/3; N=22 - 9
5 13> 3 TRUE
6 goto 1
1 powerD = 3
2 3*3 < 13 TRUE
3 powerOfD= 3*3;
2 9*9 < 31 FALSE
4 result=6+9/3; N=13 - 9
5 4> 3 TRUE
6 goto 1
1 powerD = 3
2 3*3 < 4 ALSE
4 result=9+3/3; N=4-3
5 1> 3 FALSE
7 return 10

Resources