Search This Blog

Simplicity is the ultimate sophistication.” — Leonardo da Vinci
Contact me: sreramk360@gmail.com

Friday, 6 February 2015

Music chord generator



Music chord generator
 

The following is a simple implementation of music cord generator created by me and my friend Elanchezhian in c++11. The main task of this console CUI application is to get command line inputs like "C major" or "C minor 6" and display the respective notes that constitute that cords. Please excuse any spelling mistakes or improper variable, function, constants  naming. I haven't got the slightest idea of music, and that lead to making me use silly names for many data type declaration. Again, this program was developed JUST FOR FUN.

compiling this program:
you may compile this program by pasting the code under the specified file name. For example, the main.cpp contents should be under main.cpp, the Ui.h contents should be under the Ui.h. Now create a visual studio empty project and add all these files to it. Once you are done adding, compile the project. The resultant binary release will be the final output.    


/* main.cpp
*the musical chord generator computational method copyright (c) Elanchezhian 2015 algorithmic
* implementation in c++ and coding  copyright (c) 2015 K Sreram 
* this source is published without WITHOUT ANY WARRANTY of any sort.
*/
#include "UI.h"
#include "cordGenerator.h"
#include <stdlib.h>
int main()
{
    userInterface newUI;
    generateCord gen1;
    newUI.documentation();
    while (true)
    {
        newUI.getCommand();
        newUI.seperateCommands();
        gen1.getChordTypeAndChordFamily(newUI);
        if (gen1.exit_process)
            return 0;
        if (gen1.error_in_process)
            continue;
        gen1.generatetheChord();
        if (gen1.scaleOrCord)
            std::cout << "the chord :" << gen1.theChord << "\n";
        else
            std::cout << "the scale :" << gen1.theChord << "\n";
    }
    system("pause");
    return 0;
}

/* UI.h
*the musical chord generator computational method copyright (c) Elanchezhian 2015 algorithmic
* implementation in c++ and coding  copyright (c) 2015 K Sreram 
* this source is published without WITHOUT ANY WARRANTY of any sort.
*/#ifndef UI_H
#define UI_H
#include <vector>
#include <string>
#include <iostream>
#include <string.h>
class userInterface{
public:
    size_t data_size; // size of data. Same as commandList.size();
    std::string command; // the command given by the user
    std::vector<std::string> commandList; // list of words given as commands (neglets space)
    void getCommand(); // reserves command from the user
    void seperateCommands(); // seperates commands for checking
    userInterface(); // initializer
    void documentation(); // file documentaton output
private:
    std::string tempData;
   
};
#endif // UI_H

/* UI.cpp
*the musical chord generator computational method copyright (c) Elanchezhian 2015 algorithmic
* implementation in c++ and coding  copyright (c) 2015 K Sreram 
* this source is published without WITHOUT ANY WARRANTY of any sort.
*/
#include "UI.h"
userInterface::userInterface()
{
    this->data_size = 0;
}
void userInterface::getCommand()
{
    data_size = 0;
    command.clear();
    std::cout << "->";
    std::getline(std::cin, command);
}

void userInterface::seperateCommands()
{
    tempData.clear();
    commandList.clear();
    size_t index = 0;
    if (command.size() == 0)
        return;
    while (index < command.size())
    {
        if (command[index] != ' ')
            tempData.push_back(command[index]);
        else
        {
            commandList.push_back(tempData);
            ++data_size;
            tempData.clear();
        }
        ++index;
    }
    commandList.push_back(tempData);
    ++data_size;
}

void userInterface::documentation()
{
    std::cout << "the musical chord generator algorithm and computational methord \n copyright (c) Elanchezhian 2015\n"
                 <<"algorithamic implementation in c++ and coading \n compright (c) 2015 K Sreram \n";

}



/* cordGenerator.h
*the musical chord generator computational method copyright (c) Elanchezhian 2015 algorithmic
* implementation in c++ and coding  copyright (c) 2015 K Sreram 
* this source is published without WITHOUT ANY WARRANTY of any sort.
*/
#ifndef CORD_GENERATOR_H
#define CORD_GENERATOR_H
#include "UI.h"

enum cordFamily{
    major,    sus_2,
    sus_4,    diminished,    major_add_9,
    argumented,    dominant_11, dominant_13,    /// argumented is augumented
    dominant_7,    dominant_9,
    power_cord_5, major_7, minor, minor_6,
    minor_7, minor_9,
    major_cord_family, minor_chord_family, major_9, major_6,
    diminished_7
};

enum notes_sharp{
    C_, C_sharp, D_, D_sharp,
    E_, F_, F_sharp, G_,
    G_sharp, A_, A_sharp, B_
};

enum notes_flat{
    C, D_flat, D, E_flat,
    E, F, G_flat, G,
    A_flat, A, B_flat, B
};
union chordType
{
    notes_flat flat;
    notes_sharp sharp;
};
enum CH_type{sharp_, flat_};
class generateCord{
public:
    bool scaleOrCord;
    bool exit_process;
    bool error_in_process; // shows error
    std::string theChord; // the result
    chordType type; // which chord? eg, C chord or D chord...
    cordFamily chord_family; // type of chord used
    CH_type t_type; // sharp_ or flat_
    generateCord();
    void getChordTypeAndChordFamily(userInterface& newUI); // extracts information from the command
    void generatetheChord(); // provides the result
private:
    bool search_string(std::vector<std::string> strList, std::string str); // searches for string
    bool find_words(std::vector<std::string> strList1, std::vector<std::string> theseWords, std::vector<std::string> notThesewords);
};

extern const std::vector<std::vector<int>> control;
extern const notes_sharp notes_sharp_Order[12];
extern const notes_flat notes_flat_Order[12];
extern const std::vector<std::string> notes_sharp_chr;
extern const std::vector<std::string> notes_flat_chr;
extern const size_t size_of_notes_series;
#endif



/* cordGenerator.cpp
*the musical chord generator computational method copyright (c) Elanchezhian 2015 algorithmic
* implementation in c++ and coding  copyright (c) 2015 K Sreram 
* this source is published without WITHOUT ANY WARRANTY of any sort.
*/
#include "cordGenerator.h"
const std::vector<std::vector<int>> control = {  //indexed by chord_family
    {  4, 3 }, {  2, 5 }, { 5, 2}, { 3, 3},
    {  4, 3, 7 }, {  4, 4 }, { 4, 3, 3, 4, 3},
    {  4, 3, 3, 4, 7 }, {  4, 3, 3 }, { 4, 3, 3, 4},
    {  7 }, {  4, 3, 4 }, {  3, 4 }, { 3, 4, 2},
    { 3, 4, 3 }, { 4, 3, 2, 5 }, { 2, 2, 1, 2, 2, 2, 1 },
    { 2, 1, 2, 2, 1, 2, 2 }, { 4, 3, 4, 3 }, { 4, 3, 2 }, {3, 3, 3}
};

const notes_sharp notes_sharp_Order[] = { C_, C_sharp, D_, D_sharp,
                                    E_, F_, F_sharp, G_,
                                    G_sharp, A_, A_sharp, B_ };

const notes_flat notes_flat_Order[] = { C, D_flat, D, E_flat,
                                        E, F, G_flat, G,
                                        A_flat, A, B_flat, B };

const std::vector<std::string> notes_sharp_chr = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"};
const std::vector<std::string> notes_flat_chr = { "C", "D_b", "D", "E_b", "E", "F", "G_b", "G", "A_b", "A", "B_b", "B"};
const size_t size_of_notes_series = 12;

generateCord::generateCord()
{
    error_in_process = false;
    exit_process = false;
    scaleOrCord = true; // chord is true
}
bool generateCord::search_string(std::vector<std::string> strList, std::string str)
{
    size_t i;
    for (i = 0; i < strList.size(); i++)
        if (strList[i] == str)
            return true;
    return false;
}
bool generateCord::find_words(std::vector<std::string> strList1, std::vector<std::string> theseWords, std::vector<std::string> notThesewords)
{ // <<<<<<<<"not used yet:: to be used in future releases"-K Sreram>>>>>>>>>>>>>>>>>>
    const size_t theseWords_size = theseWords.size();
    const size_t notTheseWords_size = notThesewords.size();
    const size_t strList1_size = strList1.size();
    size_t i;
    for (i = 0; i < theseWords_size; i++)
    {
        if (!search_string(strList1, theseWords[i]))
            return false;
    }
    for (i = 0; i < notTheseWords_size; i++)
    {
        if (search_string(strList1, notThesewords[i]))
            return false;

    }
    return true;

}
void generateCord::getChordTypeAndChordFamily(userInterface& newUI)
{// extracts information from the command
    scaleOrCord = true;
    size_t i;
    bool trigger = true;
    error_in_process = false;
    exit_process = false;
    /// chord type
    for (i = 0; i < 12; i++)
    {
        if (search_string(newUI.commandList, notes_sharp_chr[i]))
        {
            type.sharp = (notes_sharp)i; // records the chord
            t_type = sharp_;
            trigger = false;
            break;
        }
       
    }
    if (trigger) /// ie the search failed
        for (i = 0; i < 12; i++)
        {
            if (search_string(newUI.commandList, notes_flat_chr[i]))
            {
                type.flat = (notes_flat)i;// records the chord
                t_type = flat_;
                trigger = false;
                break;
            }
           
        }
    if (search_string(newUI.commandList, "exit"))
    {
        exit_process = true;
        return;
    }
    else if (trigger)
    {
        std::cout << "\nerror: the command,\"" << newUI.command << "\" is unidentifiable\n";
        error_in_process = true;
        return;
    }

    if (search_string(newUI.commandList, "major"))
    {
        if ((search_string(newUI.commandList, "add")) &&
            (search_string(newUI.commandList, "9")))
        {
            chord_family = major_add_9;
        }
        else if ((search_string(newUI.commandList, "add")) &&
            (search_string(newUI.commandList, "7")))
        {
            chord_family = major_7;
        }
        else if (search_string(newUI.commandList, "major") &&
            search_string(newUI.commandList, "scale"))
        {
            scaleOrCord = false;
            chord_family = major_cord_family;
        }
        else if (search_string(newUI.commandList, "9"))
        {
            chord_family = major_9;
        }
        else if (search_string(newUI.commandList, "6"))
        {
            chord_family = major_6;
        }
        else // for only major
            chord_family = major;
    }
    else if (search_string(newUI.commandList, "sus"))
    {
        if (search_string(newUI.commandList, "2"))
            chord_family = sus_2;
        else if (search_string(newUI.commandList, "4"))
            chord_family = sus_4;
        else
        {
            std::cout << "\nerror: the command,\"" << newUI.command << "\" is unidentifiable\n";
            error_in_process = true;
        }
    }
    else if (search_string(newUI.commandList, "diminished"))
    {
        if (search_string(newUI.commandList, "7"))
            chord_family = diminished_7;
        else
            chord_family = diminished;
    }
    else if (search_string(newUI.commandList, "major") &&
        (search_string(newUI.commandList, "add")) &&
        (search_string(newUI.commandList, "9"))&&
        !(search_string(newUI.commandList, "7")))
    {
        chord_family = major_add_9;
    }
    else if (search_string(newUI.commandList, "augumented"))
    {
        chord_family = argumented;
    }
    else if (search_string(newUI.commandList, "dominant"))
    {
        if (search_string(newUI.commandList, "11"))
            chord_family = dominant_11;
        else if (search_string(newUI.commandList, "13"))
            chord_family = dominant_13;
        else if (search_string(newUI.commandList, "7"))
            chord_family = dominant_7;
        else if (search_string(newUI.commandList, "9"))
            chord_family = dominant_9;
        else
        {
            std::cout << "\nerror: the command,\"" << newUI.command << "\" is unidentifiable\n";
            error_in_process = true;
        }
    }
    else if (search_string(newUI.commandList, "power") &&
        search_string(newUI.commandList, "chord") &&
        search_string(newUI.commandList, "5"))
    {
        chord_family = power_cord_5;
    }
    else if (search_string(newUI.commandList, "minor"))
    {
        if (search_string(newUI.commandList, "scale"))
        {
            scaleOrCord = false;
            chord_family = minor_chord_family;
        }
        else if (search_string(newUI.commandList, "6"))
        {
            chord_family = minor_6;
        }
        else if (search_string(newUI.commandList, "7"))
        {
            chord_family = minor_7;
        }
        else if (search_string(newUI.commandList, "9"))
        {
            chord_family = minor_9;
        }
        else
        {
            chord_family = minor;
        }
    }
    else
    {
        std::cout << "\nerror: the command,\"" << newUI.command << "\" is unidentifiable\n";
        error_in_process = true;
    }
}

void generateCord::generatetheChord()
{
    size_t index;
    size_t index_temp = 0;
    const size_t size_control= control[chord_family].size(); // common for both
    theChord.clear();
    /// the main generator
    if (t_type == sharp_)
    {
            index_temp = type.sharp;
            theChord = notes_sharp_chr[type.sharp]; // store the initial cord (no. 1 is default)
            for (index = 0; index < size_control; index++)
            {
                index_temp += (control[chord_family][index]); //i.e (type.sharp + 1 + control[chord_family][index]+1) -1
                theChord += " ";
                theChord += notes_sharp_chr[(index_temp) % size_of_notes_series]; // add to the result
            }
    }
    else if (t_type == flat_)
    {
        index_temp = type.flat;
        theChord = notes_flat_chr[type.flat]; // store the initial cord (no. 1 is default)
        for (index = 0; index < size_control; index++)
        {
            index_temp += (control[chord_family][index] ) % size_of_notes_series;
            theChord += " ";
            theChord += notes_flat_chr[(index_temp) % size_of_notes_series]; // add to the result
        }
    }
    else
    {
        std::cout << "error: variable t_type is uninitialised. consider calling getChordTypeAndChordFamily() before calling generatetheChord()\n";
    }
}

About my blog

Tuesday, 27 January 2015

Why do we need mathematics?

Why do we need mathematics? And what is the use of mathematics in our everyday life?

K Sreram

 There are many who keep themselves unclarified form this doubt and convince themselves with some solution that does not actually hold well optimally. The common answer a random person would give is: “mathematics is a subject that involves heavy reasoning and IQ skills which could later be used for general reasoning in everyday life and people who are good at it can be labeled: genius”. But I differ from this view! I want to point out that mathematics is a unique discipline separate from social life skills and an expert mathematician cannot become a skillful survivor in his social life consequently. Before going any further with this article, let me make it clear that I am just a computer science student and don’t have any prior knowledge on general psychology or social psychology or pedagogical psychology (though stuff I am going to talk about topics that can be classified into these subjects) or any other related subject. All that I put forth in this article are my own views on these subjects and might contain facts that are wrong (excuse me for that).

Mathematics is a subject which has unique applications in our everyday life. Whenever mathematics is referred to, people tend to imagine it to be a subject filled with numbers and calculations. But let me tell you, mathematics is not such a subject. Schools and universities teach us how to solve problems instead of letting us solve those problems ourselves. People have misunderstood the phrase “solution to mathematical problems” (especially in schools in universities); they believe that formulating a solution is same as learning a “universal algorithm” to obtain the solution to a family of problems. That’s not what mathematics is about. It’s about finding an optimal solution for a problem and not just learn an existing algorithm to solve that problem. Mathematical intelligence requires two main intellectual qualities: creativity and calculative ability, like we humans need two eyes to perceive an extra dimension in space (with only one eye we just perceive just two dimensions, but with 2 eyes we see the third dimension: depth).

There are people with just one such ability: creativity or calculative ability. In schools and institutions, we are taught to master the calculation part. Creativity is rarely acknowledged in our dynamic social lives, and in our educational institutions. People with just creativity and no calculative ability tend to get involved more into arts like music, drawing, poetry, authoring stories. People who are good at being calculative end-up becoming engineers and engineering subject teachers. But people with both these qualities end up becoming physicist or mathematicians.

Before I go about answering the main questions, let me tell you that by using the word “ability” I don’t mean that that person has to be born with it. I believe that any person can cultivate any talent or ability by investing rigorous work effort in doing so for an extended period of time. We don’t get something we don’t work for.

Let me answer the questions given as this article’s title. Why do we need mathematics? We need mathematics (which is an enormous collection of solutions to various unique and unimaginably breath taking problems built up from several centuries of human life) to solve problems. So as simple as that, why do we need to learn mathematics if we are actually going to solve a problem ourselves (ground-up)? The answer to this questions is that we don’t need to solve a problem from the scratch. Because if we were to do that, it would take centuries! Imaging a mathematical subject like vector geometry; the underlying concepts that were used to create that subject dates back to several centuries. Human lifespan is short; we can’t waste our lifetime “re-inventing the wheel” (but taking up small challenges is not wrong). So we use the concepts human have developed before to analyze and obtain our solution to most problems. The main requirement of mathematics is to quantize our nature and prove or derive physical or chemical or biological scenarios. Why do we need to quantize? Though our common sense can predict theories to some precision, it loses to scenarios that are so in-differentiable. For example, Isaac Newton discovered that the same force of gravity that pulls the apple to the ground (and that hurt his head!) Pulls the planets in our solar system towards the sun. But our common sense says: “no! How is that possible! If the sun was to pull our Earth like how Earth pulls the apples, then should our earth be pulled into the sun?” That’s not actually true and yet the scientists in Newton’s time rejected his work refusing to accept his theory. But Newton did not give up, he created a set of mathematical formulations that proves that Earth doesn’t have to go into the sun!

Newton laid down certain mathematical proofs to state that the planet moves in elliptical orbit because the sun pulls the earth towards it and also because at any point in time, the earth has a particular amount of potential energy and a particular amount of kinetic energy. At all times, the sum of the potential energy and the kinetic energy equals a constant value. Let me omit the proof here to maintain the lucidity of this article. You might ask how Newton came to know about that (that the gravitational force is responsible for the elliptical movement) without using the mathematical derivations himself. Newton was smart enough to understand that without needing any math. But when he wanted to convey his findings to the scientists in his time, he cannot just be talking about his imagination and say: “hello everyone! In my imaginary simulation of the planetary system I can picture our Earth moving tangentially when it’s closest to the sun (as we all know from our observation). As it’s pulled towards the sun, its tangential velocity pushes it away! And again in my imaginary simulation it changes direction towards the sun following a curvilinear path and forms an elliptical orbit!” (I made this up myself. Newton did not speak these words). Scientists don’t need vague stories and imaginations, they want the precise description or proofs for the proposed theory. They want you to express every detail there is to express. Conveying such critical details becomes hectic using an ordinary language, so a language like maths is needed!

So let me go to the last part of the question. Is maths required for our everyday life? The straight forward answer is no. But indirectly, yes. The basic underlying principles in our technologies that we use today dates from the beginning of mathematics! Of course if the law of gravity and the Newton mechanics was not accepted by the scientific community, we won’t have any of these technologies we enjoy today. Does this mean that mathematics is just a mere language used to satisfy scientists and not more than that? As I said before, mathematical expressions define the system while any explanation written in an ordinary language only shows the viewpoints of the author. So to put it elegantly mathematical formulations proving your findings record more information than you intend to record. And this information will be hidden under your own derivations and equations and it could take a while to get reviled; either by you or someone else. So more than acting as a language, it acts as the best method to capture complex situations thoroughly.

About my blog

copyright (c) 2015 K Sreram, all rights reserved. 

Featured post

Why increasing complexity is not good?

“ Simplicity is the ultimate sophistication.” — Leonardo da Vinci Why is complicating things wrong ? - K Sr...