Algorithm – Check if there is a single type with the given word

Given a dictionary list and a input word, return true if the input word has a single typo with the same length as the vocabulary in the dictionary.

dictionary = ["apple", "testing", "computer"];
singleType(dictionary, "adple") // true
singleType(dictionary, "addle") // false
singleType(dictionary, "apple") // false
singleType(dictionary, "apples") // false

I proposed a solution that runs in linear time, if we ignore the pre-process time needed for the hashmap.

O(k*26) => O(k), where k = length of the input word

My linear solution goes like, convert the dictionary list into a hash-map, where the key is the word and the value is a boolean, then loop through every character in the input word, and replace every character with 1 of the 26 alphabet and check if it maps to the hash-map.

But they say I could do better than O(k*26), but how?

Calculating percentage between 2 Swift Date objects

I have an app with a timer that shows percentage between the creation date of a reminder to the end date.

I have 2 parameters (for example):

creationDate : 2018-02-16 17:06:10 UTC
‘endDate’ : 2018-02-16 15:07:09 UTC

The timer should show how much percent has passed between the 2 Dates.

I’ve tried:

let duration = self.creationDate.timeIntervalSince(self.endDate)
let timePassed = self.creationDate.timeIntervalSinceNow
let percent = (timePassed * 100) / duration

but the information I got was incorrect.

Does anybody know what’s wrong with my algorithm? Thanks!

Move part of file to another file [on hold]

I have file with few lines:

Lines1

Lines2

Lines3

….

LinesN

I have following code:

My code

while ((line = streamReader.ReadLine()) != null)
{ 
    var str = GetData(line);
    if(str == "Fatal Error")
    {
    }
}    

During GetData I can throw some exception. In this case, I would like to move remaining lines to another file. How can I do this?
Should I declare positionCount? Or is there more smart way?

Efficient way of merging ranges (intervals) within a given threshold

I’d like to know if there is an efficient way of computing ranges distance and combine them for a given distance. For example, given ranges and distance of d=10:

1   2
4   7
12  15
32  36
38  41
...

First iteration would be: (4-2) -> 2 -> 2 < 10 -> OK -> (1,7)

1   7
12  15
32  36
38  41
...

(12-7) -> 5 -> 5 < 10 -> OK -> (1,15)

1   15
32  36
38  41
...

(32-15) -> 17 -> 17 < 10 -> KO

1   15
32  36
38  41
...

(38-36) -> 2 -> 2 < 10 -> OK -> (32,41)

Desired (resulting) data set:

1   15
32  41
...

Cost of this algorithm (lists, tuples, loops) could put in risk the main program if its not implemented efficiently.

Thank you in advance!!

std::max_element compile error, C++

Please see the following 2 examples:

#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
    int n;
    std::cin>>n;
    std::vector<int> V(n);
    // some initialization here
    int max = *max_element(&V[0], &V[0]+n);
}

This gives the following compiling error:

error C3861: ‘max_element’: identifier not found

But when I replace the call of *max_element(&V[0], &V[0]+n); to *max_element(V.begin(), V.end()); it does compile:

#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
    int n;
    std::cin>>n;
    std::vector<int> V(n);
    // some initialization here
    int max =*max_element(V.begin(), V.end());
}

Could somebody explain me why the two are different?

The algorithm is based on the public API to check the payment to the bitcoin address

I want to implement an algorithm (based on the public API) that will check whether a transaction is made from the bitcoin address btc_address to the destination address dest_btc_address.

I was interested in the functionality of Blockchain API.

My idea is to listen transactions of dest_btc_address using Single Address. For example, after a certain time interval to receive an array of transactions and look for the presence in the inputs address btc_address.

But in my opinion this is not an optimal algorithm. Is it possible to improve the algorithm? Are there other simpler ways?

CLRS Quicksort – Not working correctly

I am trying to implement the Quicksort algorithm as given in the classic CLRS book. I have implemented it exactly line-by-line in my C# program. But the output is unsorted. The following is my code in it’s entirety, along with the output:

using System;

namespace clrs
{
    class MainClass
    {

        public static void Main (string[] args)
        {
            int[] numbers = { 2, 1, 4 };
            Console.WriteLine("unsorted: " + string.Join(",", numbers));
            quicksort (numbers, 0, numbers.Length-1);
            Console.WriteLine("sorted: " + string.Join(",", numbers));
            Console.WriteLine("");

            numbers = new int[]{ 7, 2, 1, 6, 1 };
            Console.WriteLine("unsorted: " + string.Join(",", numbers));
            quicksort (numbers, 0, numbers.Length-1);
            Console.WriteLine("sorted: " + string.Join(",", numbers));
            Console.WriteLine("");

            numbers = new int[]{ 2,8,7,1,3,5,6,4 };
            Console.WriteLine("unsorted: " + string.Join(",", numbers));
            quicksort (numbers, 0, numbers.Length-1);
            Console.WriteLine("sorted: " + string.Join(",", numbers));
            Console.WriteLine("");

            numbers = new int[]{ 2, 33, 6, 9, 8, 7, 1, 2, 5, 4, 7 };    
            Console.WriteLine("unsorted: " + string.Join(",", numbers));
            quicksort (numbers, 0, numbers.Length-1);
            Console.WriteLine("sorted: " + string.Join(",", numbers));
            Console.WriteLine("");
        }

        public static void quicksort(int[] a, int p, int r){
            int q;

            if (p < r){
                q = partition (a, p, r);
                quicksort(a, p, q-1);
                quicksort(a, q+1, r);
            }
        }

        public static int partition(int[] a, int p, int r){
            int x = a[r];
            int i = p - 1;

            for (int j=p; j<r-1; j++){
                if(a[j] <= x){
                    i = i + 1;

                    int temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
            }
            int temp1 = a[i+1];
            a[i+1] = a[r];
            a[r] = temp1;

            return (i+1);
        }
    }
}

The output is:

unsorted: 2,1,4
sorted: 2,4,1

unsorted: 7,2,1,6,1
sorted: 1,1,2,7,6

unsorted: 2,8,7,1,3,5,6,4
sorted: 2,3,1,4,5,7,8,6

unsorted: 2,33,6,9,8,7,1,2,5,4,7
sorted: 1,2,5,6,7,2,7,8,9,33,4

I have implemented quicksort exactly as it is given in CLRS, 3rd edition. My code compiles but the output is not completely sorted.

What am I doing wrong? Or is there a bug in the CLRS psuedocode (highly unlikely)?

Please HELP!

Can an optimal algorithm be not complete?

A complete algorithm is an algorithm which finds a solution if there is any.
A optimal algorithm is an algorithm which any solution its returns is optimal or in other words there exist no better solution than the returned one.

That means optimality is based on completness, right?
Which means an algorithm can not be optimal but not complete. Or did i get it wrong?

IFFT generated ocean waves in OpenGL [on hold]

I’m trying to implement IFFT in OpenGL with C++. I kinda did something but waves texture appears somewhat fragmented (see the picture). In fact I’ve tried to use abs() value in shaders and the result was, that in black zones the RGBA values are negative. Maybe the Gaussian random numbers are the culprits, but I have no idea in total and can’t fix it.

Also butterfly shader appears little weird (pic2). While other people’s implementations appear blockier, mine looks like that

enter image description here

Also butterfly shader appears little weird. While other people's implementations appear blockier, mine looks like that

h0 and h0minus shader:

    #version 430 core
    #define M_PI 3.1415926535897932384626433832795

    layout (local_size_x = 32, local_size_y = 32, local_size_z = 1) in;

    layout (binding = 1, rgba32f) writeonly uniform image2D tilde_h0k;

    layout (binding = 2, rgba32f) writeonly uniform image2D tilde_h0minusk;

layout (binding = 3, rgba32f) readonly uniform image2D noise;

int N = 256; // 256
int L = 1000; //1000
float A = 4; //20
vec2 w = vec2(1,0); //(1,0)
float windspeed = 26; //26

const float g = 9.81;

// Box-Muller-Method

vec4 gaussRND()
{   
    ivec2 texCoord = ivec2(gl_GlobalInvocationID.xy);

    float noise00 = clamp(imageLoad(noise, texCoord).r, 0.00001, 1);
    float noise01 = clamp(imageLoad(noise, texCoord).g, 0.00001, 1);
    float noise02 = clamp(imageLoad(noise, texCoord).b, 0.00001, 1);
    float noise03 = clamp(imageLoad(noise, texCoord).a, 0.00001, 1);

    float u0 = 2.0*M_PI*noise00;
    float v0 = sqrt(-2.0 * log(noise01));
    float u1 = 2.0*M_PI*noise02;
    float v1 = sqrt(-2.0 * log(noise03));

    vec4 rnd = vec4(v0 * cos(u0), v0 * sin(u0), v1 * cos(u1), v1 * sin(u1));

    return rnd;
}


void main(void)
{
    vec2 x = vec2(gl_GlobalInvocationID.xy) - float(N)/2.0;

    vec2 k = vec2(2.0 * M_PI * x.x/L, 2.0 * M_PI * x.y/L);

    float L_ = (windspeed * windspeed)/g;
    float mag = length(k);
    if (mag < 0.0001) mag = 0.0001;
    float magSq = mag * mag;

    //sqrt(Ph(k))/sqrt(2)
    float h0k = clamp(sqrt((A/(magSq*magSq)) * pow(dot(normalize(k), normalize(w)), 8.0) * exp(-(1.0/(magSq * L_ * L_))) * exp(-magSq*pow(L/2000.0,2)))/ sqrt(2.0), -4000, 4000);

    //sqrt(Ph(-k))/sqrt(2)
    float h0minusk = clamp(sqrt((A/(magSq*magSq)) * pow(dot(normalize(-k), normalize(w)), 8.0) * exp(-(1.0/(magSq * L_ * L_))) * exp(-magSq*pow(L/2000.0,2)))/ sqrt(2.0), -4000, 4000);

    vec4 gauss_random = gaussRND();

    imageStore(tilde_h0k, ivec2(gl_GlobalInvocationID.xy), vec4(gauss_random.xy * h0k, 0, 1));

    imageStore(tilde_h0minusk, ivec2(gl_GlobalInvocationID.xy), vec4(gauss_random.zw * h0minusk, 0, 1));
}

h0kt shader:

#version 430
#define PI 3.1415926535897932384626433832795

layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in;

layout (binding = 0, rgba32f) writeonly uniform image2D tilde_hkt_dy;
layout (binding = 1, rgba32f) readonly uniform image2D h0k;
layout (binding = 2, rgba32f) readonly uniform image2D h0k_minus;

uniform int L;
uniform float time;

float N = 256;

struct complex
{   
    float real;
    float im;
};

complex mul(complex c0, complex c1)
{
    complex c;
    c.real = c0.real * c1.real - c0.im * c1.im;
    c.im   = c0.real * c1.im + c0.im * c1.real;
    return c;
}

complex add(complex c0, complex c1)
{
    complex c;
    c.real = c0.real + c1.real;
    c.im   = c0.im   + c1.im;
    return c;
}

complex conj(complex c)
{
    complex c_conj = complex(c.real, -c.im);

    return c_conj;
}

void main() {
    vec2 x = ivec2(gl_GlobalInvocationID.xy) - float(N)/2.0;

    vec2 k = vec2(2.0 * PI * x.x/L, 2.0 * PI * x.y/L);

    float magnitude = length(k);
    if(magnitude < 0.00001) magnitude = 0.00001;

    float w = sqrt(9.81 * magnitude);

    complex tilde_h0k = complex(imageLoad(h0k, ivec2(gl_GlobalInvocationID.xy)).r, 
                            imageLoad(h0k, ivec2(gl_GlobalInvocationID.xy)).g);

    complex tilde_h0minuskconj = conj(complex(imageLoad(h0k_minus, ivec2(gl_GlobalInvocationID.xy)).r, 
                                imageLoad(h0k_minus, ivec2(gl_GlobalInvocationID.xy)).g));

    float cosinus = cos(radians(w * time));
    float sinus = sin(radians(w * time));

    complex exp_iwt = complex(cosinus, sinus);
    complex exp_iwt_inv = complex(cosinus, -sinus);

    complex h_k_t_dy = add(mul(tilde_h0k, exp_iwt), (mul(tilde_h0minuskconj, exp_iwt_inv)));

    imageStore(tilde_hkt_dy, ivec2(gl_GlobalInvocationID.xy), vec4(h_k_t_dy.real, h_k_t_dy.im, 0, 1));
    //imageStore(tilde_hkt_dy, ivec2(x), vec4(exp_iwt.real, exp_iwt.im, 0, 1));
}

twiddle indices texture:

#version 430 core
#define M_PI 3.1415926535897932384626433832795

layout (local_size_x = 1, local_size_y = 16) in;

layout (binding = 3, rgba32f) writeonly uniform image2D twiddleIndices;

layout (std430, binding = 8) buffer indices {
    int j[];
} bit_reversed;

struct complex
{   
    float real;
    float im;
};

float N = 256;

void main(void)
{
    vec2 x = gl_GlobalInvocationID.xy;
    float a = mod(x.y * (float(N)/ pow(2,x.x+1)), N);
    //int a = int(mod(x.y, pow(2, x.x+1)) * N / pow(2, x.x+1));
    /*if(x.x > 0) {
        a = int(mod(int(x.y),2));
    } else {
        a = int(mod(int(x.y), pow(2, x.x+1))) * int(N / x.x);
    }*/
    complex twiddle = complex( cos(2.0*M_PI*a/float(N)), sin(2.0*M_PI*a/float(N)));

    int butterflyspan = int(pow(2, x.x));

    int butterflywing;

    if (mod(x.y, pow(2, x.x + 1)) < pow(2, x.x))
        butterflywing = 1;
    else butterflywing = 0;

    // first stage, bit reversed indices
    if (x.x == 0) {
        // top butterfly wing
        if (butterflywing == 1)
            imageStore(twiddleIndices, ivec2(x), vec4(twiddle.real, twiddle.im, bit_reversed.j[int(x.y)], bit_reversed.j[int(x.y + 1)]));
        // bot butterfly wing
        else    
            imageStore(twiddleIndices, ivec2(x), vec4(twiddle.real, twiddle.im, 0, bit_reversed.j[int(x.y)]));
    }
    // second to log2(N) stage
    else {
        // top butterfly wing
        if (butterflywing == 1)
            imageStore(twiddleIndices, ivec2(x), vec4(twiddle.real, twiddle.im, x.y, x.y + butterflyspan));
        // bot butterfly wing
        else
            imageStore(twiddleIndices, ivec2(x), vec4(twiddle.real, twiddle.im, x.y - butterflyspan, x.y));
    }
}

butterfly operations texture:

#version 430
#define PI 3.1415926535897932384626433832795

layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in;

layout(binding = 0, rgba32f) uniform image2D pingpong0;
layout(binding = 3, rgba32f) uniform image2D twiddleIndices;
layout(binding = 4, rgba32f) uniform image2D pingpong1;

uniform int stage;
uniform int pingpong;
uniform int direction;

float N = 256;

struct complex
{   
    float real;
    float im;
};

complex mul(complex c0, complex c1)
{
    complex c;
    c.real = c0.real * c1.real - c0.im * c1.im;
    c.im   = c0.real * c1.im + c0.im * c1.real;
    return c;
}

complex add(complex c0, complex c1)
{
    complex c;
    c.real = c0.real + c1.real;
    c.im   = c0.im   + c1.im;
    return c;
}

complex conj(complex c)
{
    complex c_conj = complex(c.real, -c.im);

    return c_conj;
}

void horizontalButterflies() {
    complex H;
    ivec2 x = ivec2(gl_GlobalInvocationID.xy);

    if(pingpong == 0) {
        vec4 data = imageLoad(twiddleIndices, ivec2(stage, x.x)).rgba;
        vec2 p_ = imageLoad(pingpong0, ivec2(data.z, x.y)).rg;
        vec2 q_ = imageLoad(pingpong0, ivec2(data.w, x.y)).rg;
        vec2 w_ = vec2(data.x, data.y);

        complex p = complex(p_.x, p_.y);
        complex q = complex(q_.x, q_.y);
        complex w = complex(w_.x, w_.y);

        H = add(p, mul(w, q));

        imageStore(pingpong1, x, vec4(H.real, H.im, 0, 1));
    } else if(pingpong == 1)/**/ {
        vec4 data = imageLoad(twiddleIndices, ivec2(stage, x.x)).rgba;
        vec2 p_ = imageLoad(pingpong1, ivec2(data.z, x.y)).rg;
        vec2 q_ = imageLoad(pingpong1, ivec2(data.w, x.y)).rg;
        vec2 w_ = vec2(data.x, data.y);

        complex p = complex(p_.x, p_.y);
        complex q = complex(q_.x, q_.y);
        complex w = complex(w_.x, w_.y);

        H = add(p, mul(w, q));

        imageStore(pingpong0, x, vec4(H.real, H.im, 0, 1));
    }/**/
}

void verticalButterflies() {
    complex H;
    ivec2 x = ivec2(gl_GlobalInvocationID.xy);

    if(pingpong == 0) {
        vec4 data = imageLoad(twiddleIndices, ivec2(stage, x.y)).rgba;
        vec2 p_ = imageLoad(pingpong0, ivec2(x.x, data.z)).rg;
        vec2 q_ = imageLoad(pingpong0, ivec2(x.x, data.w)).rg;
        vec2 w_ = vec2(data.x, data.y);

        complex p = complex(p_.x, p_.y);
        complex q = complex(q_.x, q_.y);
        complex w = complex(w_.x, w_.y);

        H = add(p, mul(w, q));

        imageStore(pingpong1, x, vec4(H.real, H.im, 0, 1));

    } else if(pingpong == 1)/**/ {
        vec4 data = imageLoad(twiddleIndices, ivec2(stage, x.y)).rgba;
        vec2 p_ = imageLoad(pingpong1, ivec2(x.x, data.z)).rg;
        vec2 q_ = imageLoad(pingpong1, ivec2(x.x, data.w)).rg;
        vec2 w_ = vec2(data.x, data.y);

        complex p = complex(p_.x, p_.y);
        complex q = complex(q_.x, q_.y);
        complex w = complex(w_.x, w_.y);

        H = add(p, mul(w, q));

        imageStore(pingpong0, x, vec4(H.real, H.im, 0, 1));
    }
}

void main() {
    if(direction == 0)
        horizontalButterflies();
    else if(direction == 1)/**/ verticalButterflies();

    /*ivec2 x = ivec2(gl_GlobalInvocationID.xy);
    vec4 c = imageLoad(twiddleIndices, x);
    imageStore(pingpong1, x, c);*/
}

And I do inversion in vertex shader: (It’s commented for colors to be brighter)

    void main() {
   vec3 pos0 = position;

    /*/ dx
    complex dx = complex(0.0,-k.x/magnitude);
    complex h_k_t_dx = mul(dx, h_k_t_dy);

    // dz
    complex dy = complex(0.0,-k.y/magnitude);
    complex h_k_t_dz = mul(dy, h_k_t_dy);*/

   vec4 worldMatrix = transformMatrix * vec4(pos0, 1.0);
   vec4 positionRelative2Camera = viewMatrix * worldMatrix;
   gl_Position = projectionMatrix * positionRelative2Camera;

   if(pingpong == 0) {
     float h = texture(pingpong0, texCoords).g;
     //h = h/(256.0);
     color = vec4(h, h, h, 1);
   }
   if(pingpong == 1) {
     float h = texture(pingpong1, texCoords).g;
     //h = h/(256.0);
     color = vec4(h, h, h, 1);
   }