What is the time Complexity - algorithm

count = 0
for(int i = 1; i <= n; i*=2){
for(int j = 1; j <= i; j++){
count++
}
}
What will be the time complexity of the above code?
With my calculation, it will be log base 2 n.
Please help me with it

The inner loop will do the following number of iterations:
        1
        2
        4
        8
        ...
        ~𝑛
...where each line represents one iteration of the outer loop.
The total number of times that the body of the inner loop runs is therefore:
        20 + 21 + 22 + 23 + ... + 2log2𝑛
This is equal to:
        21+log2𝑛 − 1 = 2𝑛 − 1
...which is O(𝑛)

Related

largest value in two complements representation

Which of the following representation in two complements notation represents the largest value?
a. 00000010
b. 11111111
c. 00000001
d. 11111110
I found that answer is A. that is 00000010 but how?
So you have signed bytes to compare; these values are in [-128..127] range. Now let's check them:
a. 00000010 == 10 (binary) == 2 <- the largest value (among -2, -1, 1, 2)
b. 11111111 == -1 (binary) == -1
c. 00000001 == 1 (binary) == 1
d. 11111110 == -10 (binary) == -2
Note, that if binary representation starts from 1 the value is negative.
You can obtain absolute values of these negative numbers via 2 complement:
x => ~x + 1
Where ~ stands for bitwise not and + 1 is adding 1 as usual
For instance:
11111111 => 00000000 + 1 == 00000001 == 1 (and we have -1)
11111110 => 00000001 + 1 == 00000010 == 2 (and we have -2)
Edit: Let's implement a simple routine (C#) for the general case (note, that leading zeroes are mandatory):
private static string SignedIntegerValue(string value) {
if (value.StartsWith('0'))
return value;
StringBuilder sb = new StringBuilder(value.Length + 1);
sb.Append('-');
sb.Append(value);
int shift = 1;
for (int i = sb.Length - 1; i >= 1; --i) {
int v = (1 - sb[i] + '0') + shift;
sb[i] = (char)('0' + (v % 2));
shift = v / 2;
}
return sb.ToString();
}
Demo:
string[] values = new string[] {
"00000010",
"11111111",
"00000001",
"11111110",
};
string report = string.Join(Environment.NewLine, values
.Select(x => $"{x} => {SignedIntegerValue(x).PadLeft(x.Length + 1)}"));
Console.Write(report);
Outcome:
00000010 => 00000010
11111111 => -00000001
00000001 => 00000001
11111110 => -00000010

recursion big o with log n

What would be the Big O of this function:
def foo(n):
if (n <= 1):
return 0
else:
return n + foo(n/2) + foo(n/2)
I think it might O(2^logn) because in each call, there are two other calls and n is divided by 2 until it gets to 1, thus the logn.
Yes, it is O(2logn), which really is equivalent to O(n).
You can analyse it as follows:
T(n) = 1 + 2T(n/2)
        = 1 + 2(1 + 2T(n/4)) = (2²-1) + 2²T(n/4)
        = (2²-1) + 2²(1 + 2T(n/8)) = (2³-1) + 2³T(n/8)
        ...
        = (2logn - 1) + 2logn
        = (n-1) + 2n
        = O(n)
This may be a surprising result, but a snippet measuring the fraction between n and the number of calls of foo, illustrates this time complexity:
let counter;
function foo(n) {
counter++;
if (n <= 1)
return 0;
else
return n + foo(n/2) + foo(n/2);
}
for (let n = 1; n < 100000; n*=2) {
counter = 0;
foo(n);
console.log(counter/n);
}
Moreover, you can use the master theorem as well (the first case). In your case as the recursive relation is T(n) = 2T(n/2) + 1, if we want to write the relation in the form of T(n) = aT(n/b) + f(n), we will have:
a = 2, b = 2, f(n) = 1
=> c_crit = log2(2) = 1
As f(n) = 1 = O(n^c) for all c > 0, we can find a 0 < c < 1 that c < c_crit = 1. Hence, the first case of the master theorem is satisfied. Therefore, T(n) = \Theta(n).

Verilog testbench outputs are x and z on a 16-bit carry adder

I've been trying to reproduce a 16-bit Adder, but I can't seem to get any results on my testbench. Any leads?
module adder(a,b,c,s,cout);
input a,b,c;
output s,cout;
xor #1
g1(w1,a,b),
g2(s,w1,c);
and #1
g3(w2,c,b),
g4(w3,c,a),
g5(w4,a,b);
or #1
g6(cout,w2,w3,w4);
endmodule
module sixteenbitAdder(x,y,s,cout,cin);
input [15:0] x,y;
output [15:0] s;
input cin;
output cout;
wire [15:0] c;
 adder f0 (x[0],y[0],cin,s[0],c[0]);
 adder f1 (x[1],y[1],c[0],s[0],c[1]);
 adder f2 (x[2],y[2],c[1],s[2],c[2]);
 adder f3 (x[3],y[3],c[2],s[3],c[3]);
 adder f4 (x[4],y[4],c[3],s[4],c[4]);
 adder f5 (x[5],y[5],c[4],s[5],c[5]);
 adder f6 (x[6],y[6],c[5],s[6],c[6]);
 adder f7 (x[7],y[7],c[6],s[7],c[7]);
 adder f8 (x[8],y[8],c[7],s[8],c[8]);
 adder f9 (x[9],y[9],c[8],s[9],c[9]);
 adder f10 (x[10],y[10],c[9],s[10],c[10]);
 adder f11 (x[11],y[11],c[10],s[11],c[11]);
 adder f12 (x[12],y[12],c[11],s[12],c[12]);
 adder f13 (x[13],y[13],c[12],s[13],c[13]);
 adder f14 (x[14],y[14],c[13],s[14],c[14]);
 adder f15 (x[15],y[15],c[14],s[15],cout);
endmodule
And here is my testbench. I don't know how wrong it is.
module test();
wire [15:0] x,y,s;
wire cin, cout;
 testAdder testt (x,y,s,cout,cin);
 sixteenbitAdder adderr (x,y,s,cout,cin);
endmodule
module testAdder(a,b,s,cout,cin);
input [15:0] s;
input cout;
output [15:0] a,b;
output cin;
reg [15:0] a,b;
reg cin;
initial
    begin
     $monitor($time,,"a=%d, b=%d, cin=%b, s=%d, cout=%b",a,b,cin,s,cout);
     $display($time,,"a=%d, b=%d, cin=%b, s=%d, cout=%b",a,b,cin,s,cout);
     #50  a=1; b=2; cin=0;
    end
endmodule
This is what I'm given back
                   0 a=    x, b=    x, cin=x, s=    z, cout=z
                   0 a=    x, b=    x, cin=x, s=    X, cout=x
                  50 a=    1, b=    2, cin=0, s=    X, cout=x
                  52 a=    1, b=    2, cin=0, s=    X, cout=0
                  53 a=    1, b=    2, cin=0, s=    X, cout=0
                  55 a=    1, b=    2, cin=0, s=    Z, cout=0
Your design has a bug. Change:
adder f1 (x[1],y[1],c[0],s[0],c[1]);
to:
adder f1 (x[1],y[1],c[0],s[1],c[1]);
//-------------------------^
Outputs:
0 a= x, b= x, cin=x, s= x, cout=x
50 a= 1, b= 2, cin=0, s= x, cout=x
52 a= 1, b= 2, cin=0, s= X, cout=0
53 a= 1, b= 2, cin=0, s= X, cout=0
55 a= 1, b= 2, cin=0, s= 3, cout=0
There is no need for $display

How to approach this two dimensional array problem?

Problem (THE QUESTION)
Strokes to paint
Alex wants to paint a picture. In one stroke, Alex can only paint the same colored cells which are joined via some edge.
Given the painting as a 2-dimensional array of letters indicating colors, determine the minimum number of strokes to completely paint the picture.
Example: The canvas height, h = 3 and width, w = 5 is to be painted with picture=["aabba", "aabba", "aaacb"]. The diagram below shows the 5 strokes needed to paint the canvas. It takes two strokes each for colors a and b, and one for c
a a b b a
a a b b a
a a a c b
Function Description Complete the function strokesRequired in the editor below. The function must return an integer, the minimum number of strokes required to paint the canvas.
strokesRequired has the following parameter(s): picture[picture[0],...picture[h-1]] an array of strings where each string represents one row of the picture to be painted
Constraints
1 <= h <= 10^5
1<= w <= 10^5
1 <= h*w <= 10^5
len(pictureffl) = w (where 0 <= i < h)
picture[i][j] <- (a, b, c) (where 0 <= i < h and 0 <= j < w)
Hello.. so i attended one company interview and they asked me this problem and iam not getting any ideas please help
class Paint:
def __init__(self, row, col, arr):
self.ROW = row
self.COL = col
self.arr = arr
def visit(self, i, j, visited):
ele = self.arr[i][j]
for k in range(i,self.ROW):
for l in range(j, self.COL):
if self.arr[k][l]==ele:
visited[k][l]=True
v=l
if l>0 and self.arr[k][l-1]==ele and not visited[k][l-1]:
self.visit(k, l-1, visited)
if k>0 and self.arr[k-1][l]==ele and not visited[k-1][l]:
self.visit(k-1, l, visited)
elif l>=v:
break
# 2D matrix
def count_cells(self):
# Make an array to mark visited cells.
# Initially all cells are unvisited
visited = [[False for j in range(self.COL)]for i in range(self.ROW)]
# Initialize count as 0 and travese
count = 0
for i in range(self.ROW):
for j in range(self.COL):
# If a cell value false then not visited yet
# then visit
if visited[i][j] == False:
# Visit all cells in the array
self.visit(i, j, visited)
print(visited)
count += 1
return count
arr = ["aabba", "aabba", "aaacb"]
row = len(arr)
col = len(arr[0])
p = Paint(row, col, arr)
print (p.count_cells())
function visit(picture, i, j, visitedBoxes) {
const currentElem = picture[i][j];
if (picture[i][j] === currentElem) {
visitedBoxes[i][j] = true;
// go in four directions
// south
if (i + 1 < picture.length && picture[i+1][j] === currentElem && visitedBoxes[i+1][j] === false) {
visit(picture, i+1, j, visitedBoxes);
}
// west
if (j+ 1 < picture[i].length && picture[i][j+1] === currentElem && visitedBoxes[i][j+1] === false) {
visit(picture, i, j+1, visitedBoxes);
}
// north
if (i > 0 && picture[i-1][j] === currentElem && visitedBoxes[i-1][j] === false) {
visit(picture, i-1, j, visitedBoxes);
}
// west
if (j > 0 && picture[i, j-1] === currentElem && visitedBoxes[i, j-1] === false) {
visit(picture, i, j-1, visitedBoxes);
}
}
}
function countStrokes(picture) {
const visitedBoxes = [];
for (let i = 0; i < picture.length; i++) {
visitedBoxes[i] = [];
for(let j = 0; j < picture[i].length; j++) {
visitedBoxes[i][j] = false;
}
}
let srokesCount = 0;
for (let i = 0; i < picture.length; i++) {
for (let j = 0; j < picture[i].length; j++) {
if (!visitedBoxes[i][j]) {
visit(picture, i, j, visitedBoxes);
srokesCount++;
}
}
}
console.log('Strokes Count', srokesCount);
}
countStrokes(['aaaba', 'ababa', 'aacba']);
This will output 5.
Also you can use
function printVisited(visitedBoxes) {
for (let i = 0; i < visitedBoxes.length; i++) {
let str = ''
for(let j = 0; j < visitedBoxes[i].length; j++) {
str += visitedBoxes[i][j] ? '1 ': '0 ';
}
console.log(str);
}
console.log('-------------');
}
to print after each loop.
Output
1 1 1 0 0
1 0 1 0 0
1 1 0 0 0
-------------
1 1 1 1 0
1 0 1 1 0
1 1 0 1 0
-------------
1 1 1 1 1
1 0 1 1 1
1 1 0 1 1
-------------
1 1 1 1 1
1 1 1 1 1
1 1 0 1 1
-------------
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
-------------
Strokes Count 5

`EnumDisplaySettings` repeating same Resolution Multiple Times

Here goes my code
DEVMODE dm;
int index = 0;
while(0 != EnumDisplaySettings(NULL, index++, &dm)){
qDebug() << index-1 << dm.dmPelsWidth << dm.dmPelsHeight;
Resolution* resolution = new Resolution(dm.dmPelsWidth, dm.dmPelsHeight);
}
Outputs
0 320 200
1 320 200
2 320 200
3 320 240
4 320 240
5 320 240
6 400 300
7 400 300
8 400 300
9 512 384
10 512 384
11 512 384
12 640 400
13 640 400
14 640 400
15 640 480
.....
25 640 480
26 640 480
27 800 600
.....
41 800 600
42 1024 768
50 1024 768
51 1152 864
....
62 1152 864
63 1280 600
I get only one thing in return that is 320x200 not even the 1600x900 which is my current Resolution.
EnumDisplaySettings gives you every possible combination of screen parameters.
The trick is knowing which fields of the DEVMODE structure to pay attention to.
These significant fields are:
dmDisplayFixedOutput
dmDisplayFrequency
dmPelsWidth
dmPelsHeight
dmBitsPerPel
For example, here are the first 14 legitimate settings for my monitor:
dmPelsWidth dmPelsHeight dmBitsPerPixel dmDisplayFrequence dmDisplayFixedOutput
640 480 8 59 Default
640 480 8 59 Stretch
640           480            8              59                  Center
640 480 8 60 Default
640 480 8 60 Stretch
640           480            8              60                  Center
640 480 8 75 Default
640 480 16 59 Default
640 480 16 59 Stretch
640           480            16             59                  Center
640 480 16 60 Default
640 480 16 60 Stretch
640           480            16             60                  Center
640 480 16 75 Default
(... etc ...)
You need to call it in a loop. My feeling is that replacing the if with a while will instantly solve this.

Resources