Sunday, 18 February 2018

Spring boot sample project with basic CRUD operations

This project demonstrates the basic spring boot project. This can serve as a good template for any project where you need to perform CRUD operations using REST services.

You can also download the sample project from start.spring.io

If you don't want to use the start.spring.io then you can simply create a simple maven project in eclipse and add the dependencies manually in pom.xml. This also works fine.

The important part is pom.xml where you specify all the dependencies. Including parent and specifying the version of spring-boot-starter-parent in pom.xml allows you not to bother about the version of dependencies that you include as they are automatically chosen by spring-boot framework (without you specifying the version of each dependency).

Don't forget to override the java.version property (see pom.xml below) as the default provided by spring-boot-starter-parent may be the one that you don't want.

  ___________________________________________________________________________

The following template project is for maintaining various subjects and performing CRUD operations.

I assume that each subject has an id, name and description. The id is used to uniquely identify a subject.

Note that I follow the general convention of sending the request type which is as follows:
  1. For getting all the subjects, send a GET request. 
  2. For adding a new subject, send a POST request.
  3. For updating an existing subject, send a PUT request.
  4. For deleting an existing subject, send a DELETE request.

Find the complete source code of this template project here on github.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

 <groupId>org.springboottest.com</groupId>
 <artifactId>subject-course-test</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>subject-course-test</name>
 <url>http://maven.apache.org</url>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <java.version>1.8</java.version>
 </properties>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.4.0.RELEASE</version>
 </parent>

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-actuator</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
 </dependencies>
 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>

</project>



Subject.java
package org.springboottest.com.subject;

public class Subject {

 private String id,name,description;

 public Subject() {
  
 }
 
 public Subject(String id, String name, String description) {
  super();
  this.id = id;
  this.name = name;
  this.description = description;
 }

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getDescription() {
  return description;
 }

 public void setDescription(String description) {
  this.description = description;
 }
 
 
}


SubjectController.java
package org.springboottest.com.subject;

import java.util.List;

import javax.websocket.server.PathParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SubjectController {

 @Autowired
 SubjectService subjectService;
 
 @RequestMapping("/subjects")
 public List<Subject> someFunction() {
  return subjectService.getAllSubjects();
 }
 
 @RequestMapping("/subject/{subjectId}")
 public Subject getSubjectById(@PathVariable String subjectId) {
  return subjectService.getSubjectById(subjectId);
 }
 
 @RequestMapping(method=RequestMethod.POST, value="/subjects")
 public void addSubject(@RequestBody Subject subject) {
  subjectService.getAllSubjects().add(subject);
 }
 
 @RequestMapping(method=RequestMethod.PUT, value="/subjects")
 public void updateSubject(@RequestBody Subject subject) {
  subjectService.updateSubject(subject);
 }
 
 @RequestMapping(method=RequestMethod.DELETE, value="/subject/{subjectId}")
 public void deleteSubject(@PathVariable String subjectId) {
  subjectService.deleteSubjectById(subjectId);
 }
 
}


SubjectService.java
package org.springboottest.com.subject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.stereotype.Component;

@Component
public class SubjectService {

 List<Subject> subjects = new ArrayList<>(Arrays.asList(
   new Subject("AI","Artificial Intelligence", "Artificial Intelligence description"),
   new Subject("ML","Machine Learning", "Machine Learning description"),
   new Subject("Algo","Algorithms and Complexity", "Algorithms and Complexity description"),
   new Subject("DS","Data Structures", "Data Structures description")
   ));
 
 public List<Subject> getAllSubjects(){
  return subjects;
 }
 public Subject getSubjectById(String id) {
  return subjects.stream().filter(s->s.getId().equals(id)).findFirst().get();
 }
 public void updateSubject(Subject subject) {
  for(int i=0;i<subjects.size();i++) {
   if(subjects.get(i).getId().equals(subject.getId())) {
    subjects.set(i, subject);
    return;
   }
  }
 }
 public void deleteSubjectById(String subjectId) {
  subjects.removeIf(s->s.getId().equals(subjectId));
 }
 
}


App.java
package org.springboottest.com;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class App {
 public static void main(String[] args) {
  ApplicationContext context = SpringApplication.run(App.class, args);
 }
}

Saturday, 23 December 2017

Using Ant build.xml for dependency management

Steps:
  1. Right click on the project in project explorer in Eclipse --> new 'Ant Files'. This will generate a template file (.xml and a .properties file). 
  2. Create a Ivy.xml file by right clicking on the project --> new 'Ivy File'.
  3. Now you have 3 files in your project structure. the contents of these files are as follows:
axix_bujava.xml

<?xml version="1.0"?>

<project xmlns:ivy="antlib:org.apache.ivy.ant" default="retrieve-dependencies" basedir=".">

 <echo message="pulling in property files"/>
 <property file="axis_bujava.properties"/>
 
 <echo message="calling the web services generation ant task: axis_bujava"/>
 
 <target name="retrieve-dependencies" description="Retrieve dependencies with Apache IVY">
     <ivy:retrieve type="jar" />
 </target>
 
</project>

ivy.xml
<?xml version="1.0" encoding="ISO-8859-1"?>

<ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
    <info
        organisation="com.test"
        module="Test"
        status="integration">
 </info>
 <dependencies>
    <dependency org="commons-validator" name="commons-validator" rev="1.3.1"/>
    
    <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
  <dependency org="commons-logging" name="commons-logging" rev="1.2"/>
    
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
  <dependency org="org.springframework" name="spring-context" rev="5.0.2.RELEASE"/>
    
 </dependencies>
</ivy-module>


axis_bujava.properties
###############################################################################
# Copyright (c) 2008, 2014 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
#     IBM Corporation - initial API and implementation
###############################################################################
!-- ScenarioType REQUIRED. Differentiates from "client" scenario.
ScenarioType=service

!-- InitialSelection REQUIRED.  Workspace relative URI to the input WSDL or Java
InitialSelection=/dynamicWebProjectName/src/packagename/myService.java

!--Utility property values - use these to list valid values for the following properties:
!-- Service.RuntimeId, Service.ServerId 
ListRuntimes=true
ListServers=true
!-- Verbose will list informational messages as well as errors if set to true
Verbose=true

!--  Service.RuntimeId - ID of web service runtime 
Service.RuntimeId=org.eclipse.jst.ws.axis.creation.axisWebServiceRT
!-- Service.ServerId -  ID of target server 
Service.ServerId=org.eclipse.jst.server.tomcat.80
!-- Service.TypeId - Java Bean is default for both Top Down and Bottom Up
!-- Service.TypeId=Java Bean

!-- ServiceProjectName - !--type:String - name of Service project - this property can be used to give the service project a different name than the project containing the initial selection.  type: String    
!--ServiceProjectName=serviceProjectName
!-- ServiceEarProjectName - !--type:String - name of Service EAR project - this property can be used to give the service EAR project a different name than the EAR project already associated with the service project.  type: String
!--ServiceEarProjectName=serviceEarProjectName

!-- Mappings
!-- Top down or bottom up scenario. Workspace relative URI to property file containing mappings.
!-- Top Down: Mappings are used to override the default package names of the generated Java template classes.
!-- The content of the properties file must be of the format namespace=package  
!-- Bottom Up: Mappings are used to override the default namespace names in the generated WSDL.
!-- The content of the properties file must be of the format package = namespace 
!--Mappings=/testProj/mappings/mappings.txt

!-- JavaOutput
!-- Top down - String: the workspace relative URI for a Java source folder for the generated Java code - must be existing workspace source folder
!--JavaOutput=/projectName/JavaSource

!-- Methods
!-- Bottom up - space delimited string of method signatures (i.e. method1(parmType1) method2(parmType2)) to be exposed in output WSDL.  If no list is provided, all methods are exposed.
!-- Methods=

!-- Style
!-- Bottom up - String: one of: RPC, DOCUMENT, WRAPPED
!--Style=DOCUMENT

!-- Use
!-- Bottom up - String: one of: LITERAL, ENCODED 
!--Use=LITERAL

!--OverwriteFilesEnabled - set to true to overwrite files that already exist. type:boolean 
!-- note for non-interactive mode it is recommended that this be set to true
!--OverwriteFilesEnabled=true

!--CreateFoldersEnabled - set to true create folders necessary during file generation type:boolean
!-- note for non-interactive mode it is recommended that this be set to true
!--CreateFoldersEnabled=true

!--CheckoutFilesEnabled - set to true to check out files with no warning to the user type:boolean
!-- note for non-interactive mode it is recommended that this be set to true
!--CheckoutFilesEnabled=true


Now right-click on axix_bujava.xml --> Run As --> Ant Build

First Eclipse project using Apache Ivy

For installation of IvDE plugin in eclipse refer to this post.

In this post I'll discuss getting started with first project using Ivy.

Steps:
  • Create a new project in eclipse. (In the usual way)
  • Right click on the project in project explorer and then click on new --> other and search for 'ivy file'. Create a new Ivy file. You will get a template file.
Modify the contents of this file so that it looks like this:

<?xml version="1.0" encoding="ISO-8859-1"?>

<ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
    <info
        organisation="com.test"
        module="Test"
        status="integration">
 </info>
 <dependencies>
    <dependency org="commons-validator" name="commons-validator" rev="1.3.1"/>
 </dependencies>
</ivy-module>


  • This says that we have one dependency on "commons-validator". Search your dependencies on the maven repo and add it to your ivy file.
  • Once you have added all the dependencies, right click on the ivy.xml file and click add Ivy Library. This will add all the dependencies to your project transitively.
  • Create a Test class in com.test package in your project which has following contents:

package com.test;

import org.apache.commons.validator.GenericValidator;

public class Test {

 public static void main(String[] args) {
  if (GenericValidator.isEmail("lavishkothari004@gmail.com")) {
   System.out.println("the entered Email is valid.");
  } else {
   System.out.println("the entered email is not valid");
  }
 }

}


Run the project using Ctrl+F11.

What is Ivy? Installing Ivy on Eclipse

What is Ivy?
Apache Ivy is a dependency manager. Or to put it elaborately, Ivy is a dependency manager (basically an Ant extension) to manage external libraries in an agile manner during development.

Benefits of using Ivy:
  • Suppose you want to use some external Java library during development and you end up adding all the resources as external JARs. (In eclipse you can manually add external JARs to your project by right-clicking on the project in project explorer --> build path --> configure build path... --> go to libraries Tab and click on 'Add External JARs'). Note that before adding these external JARs you need to go to the painstaking task of downloading them.
    • And in the case when you decide to use some other version of existing external library, you again need to go and download and manually add the JARs. This is no doubt, a clumsy and error-prone task.
  • Suppose the JARs that you download have transitive dependencies, you will have to go and manually add all the libraries which are missing and repeat this process forever until all the dependencies are resolved transitively. Apache Ivy helps us in resolving transitive dependencies with no pain.
  • Suppose you want to add your project on GitHub and someone else clones the project for reference, he/she will not get all the external libraries that your project is dependent on and will end up adding all the dependencies. This is horrible. Ivy lets you specify the dependencies and downloads it for you automatically at a click. :)
 And this list goes on. See this for more details.

But I think these points are enough to make you feel trying your hands on Ivy.

Installing Ivy plugin on eclipse
This is very simple. Go to Help --> Install new Software --> click on Add button
Name: IvyDE
Click OK.

IvDE will install after this and you will be prompted to restart eclipse.

Tuesday, 20 June 2017

Hash Functions and Encoding and Decoding of Integer in Crypto++

/*
	This program shows encoding of an integer into a byte array
	and again decoding the byte array into integer.

	This encoding and decoding is basically used when we need to give a byte array to SHA256 or SHA512
*/

#include <iostream>
using std::cout;
using std::endl;
using std::cin;

#include <cryptopp/integer.h>
using CryptoPP::Integer;

#include <cryptopp/sha.h>
using CryptoPP::SHA512;


Integer hashOfInteger(const Integer &a) // {0,1}* -> Zp*
{
	cout<<"Finding hash of "<<a<<endl;
	// using SHA512 here
	int byteCount=a.BitCount()/8;
	if(a.BitCount()%8!=0)
		byteCount++;
	byte byteArray[byteCount];	
	byte digest[SHA512::DIGESTSIZE];
	a.Encode(byteArray,byteCount);
	
	// now byte array contains bytes corresponding to the Integer a

	SHA512().CalculateDigest(digest,byteArray,byteCount);

	Integer result;
	result.Decode(digest,SHA512::DIGESTSIZE);
	return result;
}

int main()
{

	int n;
	cin>>n;
	cout<<"result  = "<<hashOfInteger(Integer::Power2(n))<<endl;
	return 0;
}

Scalar Multiplication in Elliptic curve in Crypto++

#include<bits/stdc++.h>
using std::cout;
using std::endl;

#include <cryptopp/ecp.h>
#include <cryptopp/asn.h>
#include <cryptopp/integer.h>
using CryptoPP::Integer;

#include <cryptopp/eccrypto.h>
using CryptoPP::ECP;    // Prime field
using CryptoPP::ECPPoint;
using CryptoPP::DL_GroupParameters_EC;

#include <cryptopp/asn.h>
#include <cryptopp/oids.h>
namespace ASN1 = CryptoPP::ASN1;

int main()
{
	DL_GroupParameters_EC<ECP> groupParameter = ASN1::secp160r1();

	
	cout << "Modulus: "<< groupParameter.GetCurve().GetField().GetModulus() << endl;
	cout << "Cofactor: "<< groupParameter.GetCofactor() << endl;
		    
	cout << "Coefficients" << endl;
	cout << "  A: "<< groupParameter.GetCurve().GetA() << endl;
	cout << "  B: "<< groupParameter.GetCurve().GetB() << endl;
	
	ECP curve=groupParameter.GetCurve();
	
	Integer y = groupParameter.GetSubgroupGenerator().x;
	Integer x = groupParameter.GetSubgroupGenerator().y;
	
	ECPPoint P=ECPPoint(x,y);
	cout<<"P = "<<P.x<<" , "<<P.y<<endl;

	ECPPoint R = curve.ScalarMultiply(P,Integer(2));

	cout<<"R = "<<R.x<<" , "<<R.y<<endl;

	return 0;
}



Basic Elliptic Curve Parameters in Crypto++

#include<bits/stdc++.h>
using std::cout;
using std::endl;

#include <cryptopp/ecp.h>
#include <cryptopp/asn.h>
#include <cryptopp/integer.h>
using CryptoPP::Integer;

#include <cryptopp/eccrypto.h>
using CryptoPP::ECP;    // Prime field
using CryptoPP::ECPPoint;
using CryptoPP::DL_GroupParameters_EC;

#include <cryptopp/asn.h>
#include <cryptopp/oids.h>
namespace ASN1 = CryptoPP::ASN1;

int main()
{
	DL_GroupParameters_EC<ECP> groupParameter = ASN1::secp160r1();

	
	cout << "Modulus: "<< groupParameter.GetCurve().GetField().GetModulus() << endl;
	cout << "Cofactor: "<< groupParameter.GetCofactor() << endl;
		    
	cout << "Coefficients" << endl;
	cout << "  A: "<< groupParameter.GetCurve().GetA() << endl;
	cout << "  B: "<< groupParameter.GetCurve().GetB() << endl;
	
	ECP curve=groupParameter.GetCurve();
	
	Integer y = groupParameter.GetSubgroupGenerator().x;
	Integer x = groupParameter.GetSubgroupGenerator().y;
	
	ECPPoint P=ECPPoint(x,y);
	cout<<"P = "<<P.x<<" , "<<P.y<<endl;

        return 0;
}



Random number Generation in Crypto++

#include<iostream>
using std::cout;
using std::endl;

#include<cryptopp/integer.h>
using CryptoPP::Integer;

#include<cryptopp/osrng.h>
using CryptoPP::AutoSeededRandomPool;

int main()
{
	// Illustration of generating a random number using AutoSeededRandomPool
	AutoSeededRandomPool rng;
	cout<<Integer(rng,Integer(400),Integer(500))<<endl;
	return 0;
}


Basics about Integer class in Crypto++

// refer this documentation - https://www.cryptopp.com/docs/ref/class_integer.html
// http://www.cryptopp.com/docs/ref561/class_integer.html
#include<iostream>
#include<cryptopp/integer.h>
using CryptoPP::Integer;
using std::cout;
using std::endl;

int main()
{
	// example showing calculation of 2^x for really big x
	cout<<"2**30000 = "<<Integer::Power2(30000)<<endl; // Power2 is a static member function of class. 
	

	// addition, subtraction, multiplication, division of two big numbers
	Integer i1=Integer::Power2(100); 
	Integer i2=Integer::Power2(50);

	cout<<"2**100 + 2**50 = "<<i1+i2<<endl;
	cout<<"2**100 - 2**50 = "<<i1-i2<<endl;
	cout<<"2**100 * 2**50 = "<<i1*i2<<endl;
	cout<<"2**100 / 2**50 = "<<i1/i2<<endl;
	
	// example showing use of modular operator
	Integer i3=Integer::Power2(1024);
	Integer i4(501);

	cout<<"2**1024 % 501 = "<<i3%i4<<endl;

	// example showing calculation of modular inverse
	Integer i5(3628800);
	Integer i6(2431);
	cout<<"modular inverse of 3628800 wrt 2431 = "<<i5.InverseMod(i6)<<endl;
	
	// example showing GCD of two numbers
	cout<<"GCD("<<i5<<","<<i6<<") = "<<Integer::Gcd(i5,i6)<<endl;

	Integer a,b,c;
	a=Integer(10241024);
	b=Integer(10241024);
	c=Integer(1000000007);

	// modular Multiplication 
	cout<<a_times_b_mod_c(a,b,c)<<endl;
	// modular Exponentiation
	cout<<a_exp_b_mod_c(a,b,c)<<endl;


	return 0;
}


Integer XOR in Crypto++

#include<iostream>
#include<algorithm>
using std::cout;
using std::cin;
using std::endl;

#include<cryptopp/integer.h>
using CryptoPP::Integer;


Integer XOR(Integer &a,Integer &b)
{
	Integer result=0;
	if(a>b)
	{
		for(int i=a.BitCount()-1;i>=b.BitCount();i--)
			result=result*2 + a.GetBit(i);
		for(int i=b.BitCount()-1;i>=0;i--)
			result=result*2 + (a.GetBit(i) ^ b.GetBit(i));
	}
	else
	{
		for(int i=b.BitCount()-1;i>=a.BitCount();i--)
			result=result*2 + b.GetBit(i);
		for(int i=a.BitCount()-1;i>=0;i--)
			result=result*2 + (a.GetBit(i) ^ b.GetBit(i));
	}

	return result;
}
void printBits(Integer &a)
{	
	for(int i=a.BitCount()-1;i>=0;i--)
		cout<<a.GetBit(i);
	cout<<endl;
}
int main()
{
	int x,y;
	cin>>x>>y;
	Integer a(Integer::Power2(x));
	Integer b(Integer::Power2(y));

	cout<<XOR(a,b)<<endl;
	return 0;
}



Printing the same character n number of times in Vim

Many times you need to type the same character many times and for that you need to long press that character and this wastes time. Well, there is a smarter way to do this in Vim.

Suppose you need to type _(underscore) 50 times.

So to do this, go in command mode by pressing Esc key and type the following:
50i_<Esc>

The moment you press <Esc>, the one undersocre that appears on the screen will be repeated 50 times, and now you can see 50 underscores on the screen one after the other.

Running python code from Vim and replacing the code with output

It is possible to write python code in vim and then execute the code. The output of the code will be placed in place of the python code. Let me illustrate you an example so that it becomes more clear.

Example:
Suppose that you have a string "Lavish" and you want to put each character of this string into a new line. We can write python code to do this.

for i in "Lavish":
    print i

Now select the above two lines by going in visal mode and then execute the following commmand:
:'<,'>!python

This will replace the python code with following lines:
L
a
v
i
s
h

Now, you may not see the real difference when the string is small, but as the string goes bigger, the power of vim becomes more visible.

Similarly, as an another example, say you want to print the following thing in a text file

1 Lavish
2 Lavish
3 Lavish
4 Lavish
5 Lavish

I'm sure, you must have figured it out that the python code for this will be:

for i in range(1,6):
    print str(i)+" Lavish"

and then follow the same thing again as described above. Similarly to the above mentioned examples, there is a lot of cool stuff that you can try out and make yourself more productive and efficient.

I hope this was interesting and you learned something from this. :)

Automatic Indentation of Code in Vim

Indentation is very important as it increases the readability of the codea and is considered to be a good programming practice. But a lot of times you may have to get some code that is not indented, and it is really irritating to mannualy indent each line. Vim provides a very eays way to indent your code just with unbelievably few keystrokies.

gg=G

is will indent your code from beginning of the file till the end of the file. Note that here gg means go to the starting of the file and = means to indent and G is for the end of the file. Puting it together we can read it as "indent the code from first line till the last line."

Similarly, to order to indent the current line, just place your cursor anywhere in that line and press
==
This will indent the current line.

Moving to the matching paranthesis in Vim

A lot of times while programming, we need to move to the matching paranthesis/braces. Place your cursor under one of the paranthesis in normal mode and press % the cursor will move to the corresponding matching paranthesis, bracket or brace what so ever it is. This is an efficient way of moving around functions in programming languages.

Saving and Quiting in Vim (shortcut Method)

Normal way to save and quit a file in vim is using :wq in vim. This is used by most of the user, but this involves three different keystrokes. But there is another way to do this saving and quiting. Just press ZZ in the normal mode and the file will be written and then vim will exit. I personally think that this is more efficient because it involves only one keystroke and it does all the things. Hope you also find this way of saving and quiting easier.

Thursday, 27 April 2017

Pattern making - Spirograph - Javascript - using array of rods

In the previous post we saw how to create two rods and make them rotate relative to each other, with each rod having different speed and different length. In this post we will extend the previous code so as to make more than two rods rotate relative to the previous rod, and we will also trace the trajectory of end point of the last rod as done in previous post.

The following is the code:

HTML Code

<html>
 <title>Rakshit</title>
 <script type="text/javascript" src="a.js"></script>
 <body>
  <canvas id="mycanvas" width="500" height="500"></canvas>
  <canvas id="desingcanvas" width="500" height="500"></canvas>
  <button id="stopButton">Stop</button>
  <button id="resumeButton">Resume</button>
  <button id="restartButton">Restart</button>

 </body>

</html>

Javascript Code
/*
    Taking array of rods.
*/

var width=0;
var height=0;
var interval;

var rods=[];
var drawing=false; // a global variable that keeps track of whether we are drawing or not.

window.onload = function(){
    var cns = document.getElementById("mycanvas");

    width = cns.width;
    height = cns.height;
    var designContext =  document.getElementById("desingcanvas").getContext("2d");
    var context = cns.getContext("2d");
    rod1=Rod.create(250,250,100,0,10.0,"#0000FF");
    rod2=Rod.create(rod1.endx,rod1.endy,70,Math.PI,60.0,"#FF0000");
    rod3=Rod.create(rod2.endx,rod2.endy,50,Math.PI,30.0,"#00FF00");
    rod4=Rod.create(rod3.endx,rod3.endy,20,Math.PI,10.0,"#0F00F0");

    rods.push(rod1);
    rods.push(rod2);
    rods.push(rod3);
    rods.push(rod4);

    interval = setInterval(function(){draw(context,designContext);},1);

    var stopButton = document.getElementById("stopButton");
    stopButton.addEventListener("click",stopButtonClicked,false);
    var resumeButton = document.getElementById("resumeButton");
    resumeButton.addEventListener("click",resumeButtonClicked,false);
    var restartButton = document.getElementById("restartButton");
    restartButton.addEventListener("click",restartButtonClicked,false);

};

function stopButtonClicked()
{
    if(drawing)
    {
        clearInterval(interval);
        drawing=false;
    }
}
function resumeButtonClicked()
{
    if(drawing===false)
    {
        var context = document.getElementById("mycanvas").getContext("2d");
        var designContext =  document.getElementById("desingcanvas").getContext("2d");
        interval = setInterval(function(){draw(context,designContext);},1);
    }
}
function restartButtonClicked()
{
    if(drawing===true)
        clearInterval(interval);
    var canvas1 = document.getElementById("mycanvas");
    var canvas2 = document.getElementById("desingcanvas");
    var context = canvas1.getContext("2d");
    var designContext =  canvas2.getContext("2d");

    context.clearRect(0,0,canvas1.width,canvas1.height);
    designContext.clearRect(0,0,canvas2.width,canvas2.height);

    interval = setInterval(function(){draw(context,designContext);},1);
}

var Rod={
    startx:0,
    starty:0,
    endx:0,
    endy:0,
    length:0,
    angle:0,
    speed:100,
    color:"#000000",
    create:function(startx,starty,length,angle,speed,color)
    {
        var obj=Object.create(this);
        obj.startx=startx;
        obj.starty=starty;
        obj.length=length;
        obj.angle=angle;
        obj.speed=speed/500.0;

        obj.color=color;

        obj.endx=startx+length*Math.cos(angle);
        obj.endy=starty+length*Math.sin(angle);
        return obj;
    },

    update:function(startx,starty)
    {
        this.startx=startx;
        this.starty=starty;
        this.angle+=this.speed;
        if(this.angle>2*Math.PI)
            this.angle=0;
        this.endx=this.startx+this.length*Math.cos(this.angle);
        this.endy=this.starty+this.length*Math.sin(this.angle);
    },

    drawRod:function(context)
    {
        context.strokeStyle = this.color;
        context.lineWidth = 2;
        context.beginPath();
        context.moveTo(this.startx,this.starty);
        context.lineTo(this.endx,this.endy);
        context.stroke();
        context.closePath();
    }

};


function draw(context,designContext)
{
    var n=rods.length; // n is the number of rods.
    drawing=true;
    designContext.strokeStyle="#FF0000";
    designContext.lineWidth=0.25;
    designContext.beginPath();
    designContext.moveTo(rods[n-1].endx,rods[n-1].endy);

    context.clearRect(0,0,width,height);

    for(var i=0;i<n;i++)
    {
        if(i===0)
        {
            rods[i].drawRod(context);
            rods[i].update(rods[i].startx,rods[i].starty);
        }
        else {
            rods[i].drawRod(context);
            rods[i].update(rods[i-1].endx,rods[i-1].endy);
        }
    }

    designContext.lineTo(rods[n-1].endx,rods[n-1].endy);
    designContext.stroke();
    designContext.closePath();
}


The following animation is the illustration of the above mentioned code. You can try changing the length and speed of each rod and generate some really amazing patterns. You can also try adding more rods, or removing some of the rods so as to get something interesting.



Please feel free to comment if have any problem, or if you find any other thing that is interesting in this context. Also feel free to point any mistakes in the code.

Pattern Making - Spirograph - JavaScript

This post contains an illustration of making a spirograph using HTML5 and Javascript. Note that down there, we have three small buttons for you to play with the animation. The concept used here is that I have two rods/arms attached back to back and I'm plotting the trajectory of end-point of the last rod. See the below animation to get a clear idea.



Note that the code mentioned above is not easily extendable but the coming posts in this series will show how you can create an array of rods, and loop over all the rods to track the path traced by the end point of the last rod.
You can always right click and go to view page source to view the code behind construction of the above spirograph, but for the sake of simplicity and cutting off all the dirty code, here is the clean code used to make the above spirograph.
HTML Code
<html>
<title>Rakshit</title>
<script type="text/javascript" src="a.js"></script>
<body>
    <canvas id="mycanvas" width="500" height="500"></canvas>
    <canvas id="desingcanvas" width="500" height="500"></canvas>
    <button id="stopButton">Stop</button>
    <button id="resumeButton">Resume</button>
    <button id="restartButton">Restart</button>

</body>

</html>


Javascript Code
/*
    This program adds two rotating rods, representing robotic arm

    This is a simple program that just adds 2 rods
    and gives the trajectory of the end point of the second rod
*/
var width=0;
var height=0;
var interval;
var rod1,rod2;
var drawing=false; // a global variable that keeps track of whether we are drawing or not.
window.onload = function(){
    var cns = document.getElementById("mycanvas");

    width = cns.width;
    height = cns.height;
    var context = cns.getContext("2d");
    var designContext =  document.getElementById("desingcanvas").getContext("2d");
    rod1=Rod.create(250,250,80,0,10.0,"#0000FF");
    rod2=Rod.create(rod1.endx,rod1.endy,130,Math.PI,80.0,"#FF0000");

    interval = setInterval(function(){draw(context,designContext);},1);

    var stopButton = document.getElementById("stopButton");
    stopButton.addEventListener("click",stopButtonClicked,false);
    var resumeButton = document.getElementById("resumeButton");
    resumeButton.addEventListener("click",resumeButtonClicked,false);
    var restartButton = document.getElementById("restartButton");
    restartButton.addEventListener("click",restartButtonClicked,false);

};

function stopButtonClicked()
{
    if(drawing)
    {
        clearInterval(interval);
        drawing=false;
    }
}
function resumeButtonClicked()
{
    if(drawing===false)
    {
        var context = document.getElementById("mycanvas").getContext("2d");
        var designContext =  document.getElementById("desingcanvas").getContext("2d");
        interval = setInterval(function(){draw(context,designContext,rod1,rod2);},1);
    }
}
function restartButtonClicked()
{
    if(drawing===true)
        clearInterval(interval);
    var canvas1 = document.getElementById("mycanvas");
    var canvas2 = document.getElementById("desingcanvas");
    var context = canvas1.getContext("2d");
    var designContext =  canvas2.getContext("2d");

    context.clearRect(0,0,canvas1.width,canvas1.height);
    designContext.clearRect(0,0,canvas2.width,canvas2.height);

    interval = setInterval(function(){draw(context,designContext,rod1,rod2);},1);
}

var Rod={
    startx:0,
    starty:0,
    endx:0,
    endy:0,
    length:0,
    angle:0,
    speed:100,
    color:"#000000",
    create:function(startx,starty,length,angle,speed,color)
    {
        var obj=Object.create(this);
        obj.startx=startx;
        obj.starty=starty;
        obj.length=length;
        obj.angle=angle;
        obj.speed=speed/500.0;

        obj.color=color;

        obj.endx=startx+length*Math.cos(angle);
        obj.endy=starty+length*Math.sin(angle);
        return obj;
    },

    update:function(startx,starty)
    {
        this.startx=startx;
        this.starty=starty;
        this.angle+=this.speed;
        if(this.angle>2*Math.PI)
            this.angle=0;
        this.endx=this.startx+this.length*Math.cos(this.angle);
        this.endy=this.starty+this.length*Math.sin(this.angle);
    },

    drawRod:function(context)
    {
        context.strokeStyle = this.color;
        context.lineWidth = 2;
        context.beginPath();
        context.moveTo(this.startx,this.starty);
        context.lineTo(this.endx,this.endy);
        context.stroke();
        context.closePath();
    }

};


function draw(context,designContext)
{
    drawing=true;
    designContext.strokeStyle="#FF0000";
    designContext.lineWidth=0.25;
    designContext.beginPath();
    designContext.moveTo(rod2.endx,rod2.endy);

    context.clearRect(0,0,width,height);

    rod1.drawRod(context);
    rod1.update(rod1.startx,rod1.starty);
    rod2.drawRod(context);
    rod2.update(rod1.endx,rod1.endy);

    designContext.lineTo(rod2.endx,rod2.endy);
    designContext.stroke();
    designContext.closePath();
}

Please bear with me as I am new to javascript and comment if you have any new idea or find anything wrong in this post.

Saturday, 31 December 2016

Disjoint Set Data Structure

This post will illustrate the basic implementation of Disjoint-set data structure. We will use the two popular heuristics:
1. Union by rank
2. Path Compression

Refer this TopCoder tutorial for detailed explanation of this data structure.

To illustrate with example, we solve this problem on hackerrank.

The basic implementation using class is as follows:

#include <bits/stdc++.h>
using namespace std;


// heuristics:
//    1. Union by rank
/// 2. Path compression
class DisjointSet
{
public:
    class Node
    {
    public:
        Node*parent;
        int rank; // used for union by rank
        int associatedNodes; // maintaining the number of nodes in a group (for representative element)

        Node()
        {    
            rank = 1;
            associatedNodes = 1;
            parent = this;
        }
    };

    vector<Node*>nodes;
    DisjointSet(int n)
    {
        nodes=vector<Node*>(n);
        for(int i=0;i<n;i++)
            nodes[i]=new Node();
    }
    Node*find(Node*node) // returns the representative element of node
    {
        if(node->parent != node)
            node->parent = find(node->parent); // path compression
        return node->parent;
    }
    void merge(Node*n1,Node*n2)
    {
        Node*pn1 = find(n1);
        Node*pn2 = find(n2);
        if(pn1!=pn2)
        {
            if(pn1->rank > pn2->rank)
            {
                pn2->parent = pn1;
                pn1->associatedNodes += pn2->associatedNodes;
            }
            else 
            {
                pn1->parent = pn2;
                pn2->associatedNodes += pn1->associatedNodes;
            }
            if(pn1->rank == pn2->rank)
                pn2->rank++;
        }
    }

};

int main()
{
    int n;
    cin>>n;
    DisjointSet ds(n);

    int q;
    cin>>q;
    while(q--)
    {
        char ch;
        cin>>ch;
        if(ch=='M')
        {
            int a,b;
            cin>>a>>b;
            ds.merge(ds.nodes[a-1],ds.nodes[b-1]);
        }
        else if(ch=='Q')
        {
            int num;
            cin>>num;
            cout<<ds.find(ds.nodes[num-1])->associatedNodes<<endl;
        }
    }
    return 0;
}
But that's too much of hassle
The following code illustrates a clever implementation of Disjoint set data structure.
#include <bits/stdc++.h>
using namespace std;
#define MAXN 100010

vector<int>parent(MAXN),size(MAXN);

int find(int n) {
    if(parent[n]==n) return n;
    else return parent[n] = find(parent[n]);
}

void merge(int a,int b) {
    int pa = find(a);
    int pb = find(b);
    if(pa!=pb) {
        if(size[pa]>size[pb]) {
            parent[pb]=pa;
            size[pa]+=size[pb];
        }
        else {
            parent[pa]=pb;
            size[pb]+=size[pa];
        }
    }
}

int main()
{

    for(int i=0;i<MAXN;i++)
        parent[i] = i, size[i] = 1;

    int q,n,a,b,num;
    cin>>n>>q;

    while(q--) {
        char ch;
        cin>>ch;
        if(ch=='M') {
            cin>>a>>b;
            merge(a-1,b-1);
        }
        else if(ch=='Q') {
            cin>>num;
            cout<<size[find(num-1)]<<endl;
        }
    }
    return 0;
}

Thursday, 29 December 2016

Snake Game in C++


// use following command to run : 
// g++ -std=c++14 snake.cpp -lpthread

#include <bits/stdc++.h>
#include <thread>
#include <unistd.h>
#include <termios.h>
using namespace std;

enum direction { LEFT, RIGHT, UP, DOWN };
enum tileConf { EMPTY, BLOCKED, OCCUPIED, FOOD };
enum gameState { RUNNING, OVER };

////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Tile
{
public:
 tileConf conf;
 Tile(tileConf);
};

Tile::Tile(tileConf tc)
{
 conf = tc;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Screen
{
public:
 int WIDTH,HEIGHT;
 vector< vector<Tile> >matrix;

 Screen();
 void print(int,int,int,int,int);
};

Screen::Screen()
{
 HEIGHT = 20;
 WIDTH = 50;
 Tile tile(EMPTY);
 matrix = vector< vector<Tile> >(HEIGHT,vector<Tile>(WIDTH,tile));
 /*
 for(int i=0;i<WIDTH;i++)
  matrix[HEIGHT-1][i].conf = matrix[0][i].conf = BLOCKED;
 for(int i=0;i<HEIGHT;i++)
  matrix[i][WIDTH-1].conf = matrix[i][0].conf = BLOCKED;
 */
}

void Screen::print(int score,int level,int snakex,int snakey,int snakeLength)
{
 system("clear");
 for(int i=0;i<WIDTH+2;i++)
  cout<<"@";
 cout<<endl;
 for(int i=0;i<HEIGHT;i++)
 {
  cout<<"@";
  for(int j=0;j<WIDTH;j++)
  {
   if(matrix[i][j].conf == OCCUPIED)
    cout<<'o';
   if(matrix[i][j].conf == BLOCKED)
    cout<<'#';
   if(matrix[i][j].conf == EMPTY)
    cout<<' ';
   if(matrix[i][j].conf == FOOD)
    cout<<'F';

  }
  cout<<"@"<<endl;
 }
 for(int i=0;i<WIDTH+2;i++)
  cout<<"@";
 cout<<endl;
 cout<<"SCORE : "<<score<<endl;
 cout<<"LEVEL : "<<level<<endl;
 cout<<"Snake_Length : "<<snakeLength<<endl;
 cout<<"Snake_head (X,Y) : "<<snakex<<","<<snakey<<endl;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Food
{
public:
 pair<int,int>coordinates;
 Food(Screen&);
};

Food::Food(Screen&screen)
{
 int x,y;
 do{
  x = rand()%screen.HEIGHT;
  y = rand()%screen.WIDTH;
 }while(screen.matrix[x][y].conf!=EMPTY);
 coordinates = make_pair(x,y);
 screen.matrix[x][y] = FOOD;
 cout<<x<<" "<<y<<endl;
 //exit(0);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Snake
{
public:
 pair<int,int>head,tail;
 list< pair<int,int> >body;
 int currentLength;
 volatile direction headDirection;
 int speed;

 Snake(Screen&);
 Snake();

 void moveHeadLeft(Screen&,int&);
 void moveHeadRight(Screen&,int&);
 void moveHeadDown(Screen&,int&);
 void moveHeadUp(Screen&,int&);
 void moveTail(Screen&);

 void move(Screen&,int&);
 
 void eat(Screen&,int&);
 bool bitesItself(); // bites itself
 bool hitsWall(Screen&);
};



Snake::Snake()
{

}
Snake::Snake(Screen&screen)
{
 int startx = screen.HEIGHT/2;
 int starty = screen.WIDTH/2;
 int endx = startx;
 int endy = starty+2;

 head = make_pair(endx,endy);
 tail = make_pair(startx,starty);
 pair<int,int>intermediate = make_pair(startx,starty+1);

 body.push_back(head);
 body.push_back(intermediate);
 body.push_back(tail);

 currentLength = 3;
 headDirection = RIGHT;
 speed = 1;

 screen.matrix[head.first][head.second].conf = OCCUPIED;
 screen.matrix[intermediate.first][intermediate.second].conf = OCCUPIED;
 screen.matrix[tail.first][tail.second].conf = OCCUPIED;
}

void Snake::moveTail(Screen&screen)
{
 screen.matrix[tail.first][tail.second]=EMPTY;
 body.pop_back();
 tail = body.back();
}

void Snake::moveHeadLeft(Screen&screen,int &score)
{
 int newx = head.first;
 int newy = head.second-1;
 if(newy<0)
  newy+=screen.WIDTH;
 tileConf tc = screen.matrix[newx][newy].conf;
 if(tc==FOOD)
  eat(screen,score);
 else if(tc==BLOCKED || tc==OCCUPIED)
  exit(0);
 screen.matrix[newx][newy]=OCCUPIED;
 head = make_pair(newx,newy);
 body.push_front(head);
}

void Snake::moveHeadRight(Screen&screen,int &score)
{
 int newx = head.first;
 int newy = head.second+1;
 if(newy>=screen.WIDTH)
  newy%=screen.WIDTH;
 tileConf tc = screen.matrix[newx][newy].conf;
 if(tc==FOOD)
  eat(screen,score);
 else if(tc==BLOCKED || tc==OCCUPIED)
  exit(0);
 screen.matrix[newx][newy]=OCCUPIED;
 head = make_pair(newx,newy);
 body.push_front(head);
}

void Snake::moveHeadDown(Screen&screen,int &score)
{
 int newx = head.first+1;
 int newy = head.second;
 if(newx>=screen.HEIGHT)
  newx%=screen.HEIGHT;
 tileConf tc = screen.matrix[newx][newy].conf;
 if(tc==FOOD)
  eat(screen,score);
 else if(tc==BLOCKED || tc==OCCUPIED)
  exit(0);
 screen.matrix[newx][newy]=OCCUPIED;
 head = make_pair(newx,newy);
 body.push_front(head);
}

void Snake::moveHeadUp(Screen&screen,int &score)
{
 int newx = head.first-1;
 int newy = head.second;
 if(newx<0)
  newx = newx + screen.HEIGHT;
 tileConf tc = screen.matrix[newx][newy].conf;
 if(tc==FOOD)
  eat(screen,score);
 else if(tc==BLOCKED || tc==OCCUPIED)
  exit(0);
 screen.matrix[newx][newy]=OCCUPIED;
 head = make_pair(newx,newy);
 body.push_front(head);
}

void Snake::move(Screen &screen,int &score)
{
 
 if(headDirection == RIGHT)
  moveHeadRight(screen,score);
 else if(headDirection == LEFT)
  moveHeadLeft(screen,score);
 else if(headDirection == UP)
  moveHeadUp(screen,score);
 else if(headDirection == DOWN)
  moveHeadDown(screen,score);
 moveTail(screen);
}

void Snake::eat(Screen&screen,int &score)
{
 pair<int,int>tail1,tail2;
 tail1 = body.back();
 body.pop_back();
 tail2 = body.back();
 body.push_back(tail);

 direction tailDirection;
 int x1,y1,x2,y2;
 x1 = tail1.first;
 y1 = tail1.second;
 x2 = tail2.first;
 y2 = tail2.second;

 if(y1+1==y2)
 {
  body.push_back(make_pair(x1,y1-1));
  tail = body.back();
  screen.matrix[x1][y1-1].conf=OCCUPIED;
 }
 else if(y1==y2+1)
 {
  body.push_back(make_pair(x1,y1+1));
  tail = body.back();
  screen.matrix[x1][y1+1].conf=OCCUPIED;
 }
 else if(x1==x2+1)
 {
  body.push_back(make_pair(x1+1,y1));
  tail = body.back();
  screen.matrix[x1+1][y1].conf=OCCUPIED;
 }
 else if(x1+1==x2)
 {
  body.push_back(make_pair(x1-1,y1));
  tail = body.back();
  screen.matrix[x1-1][y1].conf=OCCUPIED;
 }

 currentLength++;
 score+=10;
 Food f(screen);
}

bool Snake::bitesItself()
{
 return false;
}

bool Snake::hitsWall(Screen&s)
{
 return false;
}


////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Game
{
public:
 gameState state;
 int score;
 int level;
 Snake snake;
 Screen screen;

 Game();
 void run();
 void keepSnakeMoving(Snake&,Screen&);
};
Game::Game()
{
 state = RUNNING;
 score = 0; 
 level = 1;

 screen = Screen();
 snake = Snake(screen);
}
void Game::keepSnakeMoving(Snake &snake,Screen &screen)
{
 Food f(screen);
 while(true)
 //for(int i=0;i<10;i++)
 {
  usleep(100000);
  //cout<<"here"<<endl;
  snake.move(screen,score);
  screen.print(score,level,snake.head.first,snake.head.second,snake.currentLength);
 }
}

char getch() {
    char buf = 0;
    struct termios old = {0};
    if (tcgetattr(0, &old) < 0)
            perror("tcsetattr()");
    old.c_lflag &= ~ICANON;
    old.c_lflag &= ~ECHO;
    old.c_cc[VMIN] = 1;
    old.c_cc[VTIME] = 0;
    if (tcsetattr(0, TCSANOW, &old) < 0)
            perror("tcsetattr ICANON");
    if (read(0, &buf, 1) < 0)
            perror ("read()");
    old.c_lflag |= ICANON;
    old.c_lflag |= ECHO;
    if (tcsetattr(0, TCSADRAIN, &old) < 0)
            perror ("tcsetattr ~ICANON");
    return (buf);
}
void Game::run()
{
 thread th(&Game::keepSnakeMoving,this,std::ref(snake),std::ref(screen));
 
 while(true)
 {
  char ch = getch();
  if((ch=='w' || ch=='8') && snake.headDirection!=DOWN)
   snake.headDirection = UP;
  else if((ch=='d' || ch=='6') && snake.headDirection!=LEFT)
   snake.headDirection = RIGHT;
  else if((ch=='s' || ch=='5') && snake.headDirection!=UP)
   snake.headDirection = DOWN;
  else if((ch=='a' || ch=='4') && snake.headDirection!=RIGHT)
   snake.headDirection = LEFT;
 }
 th.join();
}


int main()
{
 srand((unsigned)time(0)); 
 Game g;
 g.run();
 return 0;
}



Friday, 30 September 2016

Ulam Spiral

The following post shows the distribution of primes when numbers are arranged in a spiral format as depicted below:



The above shown grid is a 7x7 grid.

If similarly we have a grid of 251x251 elements and highlight the primes withe red pixel, the image will look like the following:


And similarly if we randomly put a 0 or 1 on every pixel of 251x251 grid, we will get an image that will be somewhat like this:


We can clearly see that there is a pattern visible in case of Ulam Spiral where many prime numbers are present along different diagonals, where as random numbers follow no specific patterns.

If you are interested into the code of generating this ulam spiral and getting the above plots, have a look at below mentioned code. Basically I have used C++ to get a 2-D matrix where 1 represents that number is prime and 0 represents that it is composite. This all data is written into a file called ulam.txt and random data is written into random.txt.

Now these two file can be fed to the scilab code to get the above plots.

C++ code that will generate random.txt and ulam.txt :

#include<bits/stdc++.h>
#include<bits/stdc++.h>
#include<stdlib.h>
#include<stdlib.h>
using namespace std;
#define MAX 10000000
bitset<MAX+1>isPrime;

void getPrimes()
{
    isPrime.reset();
    isPrime.flip();
    isPrime[0]=isPrime[1]=0;
    for(int i=2;i*i<=MAX;i++)
        if(isPrime[i])
            for(int j=i*i;j<=MAX;j+=i)
                isPrime[j]=0;
}

int**getUlamSpiral(int N)
{
    int **M;
    M=new int*[2*N+1];
    for(int i=0;i<2*N+1;i++)
        M[i]=new int[2*N+1];

    int r,c,current,counter;
    
    M[N][N]=1;
    r=N;
    c=N+1;
    counter=2;
    current=2;

    for(int j=0;j<N;j++,counter+=2)
    {
        for(int i=0;i<counter;i++)
            M[r--][c]=current++;
        r++;
        c--;
        for(int i=0;i<counter;i++)
            M[r][c--]=current++;
        c++;
        r++;
        for(int i=0;i<counter;i++)
            M[r++][c]=current++;
        r--;
        c++;
        for(int i=0;i<counter;i++)
            M[r][c++]=current++;
    }

    return M;
}
void printUlamSpiral(int **M,int N)
{
    for(int i=0;i<2*N+1;i++)
    {
        for(int j=0;j<2*N+1;j++)
            cout<<M[i][j]<<"\t";
        cout<<endl;
    }
}
int**filterPrimes(int**M,int N)
{
    int **M01;
    M01=new int*[2*N+1];
    for(int i=0;i<2*N+1;i++)
        M01[i]=new int[2*N+1];

    for(int i=0;i<1+2*N;i++)
    {
        for(int j=0;j<1+2*N;j++)
        {
            if(isPrime[M[i][j]])
                M01[i][j]=1;
            else M01[i][j]=0;
        }
    }
    return M01;
}
void writeToFile(string fileName,int**M,int N)
{
    FILE*fp;
    fp=fopen(fileName.c_str(),"w");
    if(fp)
    {
        fprintf(fp,"%d\n",N);
        for(int i=0;i<1+2*N;i++)
        {
            for(int j=0;j<1+2*N;j++)
            {
                fprintf(fp,"%d ",M[i][j]);
            }
            fprintf(fp,"\n");
        }
    }
    else cout<<"there is an error in opening the file\n";
}
int**fillRandom(int N)
{
    int **m;
    m=(int**)malloc(sizeof(int*)*(2*N+1));
    for(int i=0;i<2*N+1;i++)
        m[i]=(int*)malloc(sizeof(int)*(2*N+1));
    srand(time(NULL));
    for(int i=0;i<2*N+1;i++)
        for(int j=0;j<2*N+1;j++)
            m[i][j]=rand()%2;
    return m;
}
int main()
{
    int N;
    getPrimes();
    cin>>N;
    int **M=getUlamSpiral(N);
    //printUlamSpiral(M,N);
    int **M01=filterPrimes(M,N);
    int**R01=fillRandom(N);
    writeToFile("ulam.txt",M01,N);
    writeToFile("random.txt",R01,N);
    return 0;
}

Scilab Code
function DrawSpiral(filename)
    fid=mopen(filename,"r");
    [num_read,N]=mfscanf(fid, "%d");
    N
    M = hypermat([2*N+1 2*N+1]);
    for i=1:1+2*N
        for j=1:1+2*N
            [num_read,M(i,j)]=mfscanf(fid, "%d");
        end
    end
    mclose(fid);
    
    clf();
    ax = gca();//get current axes handle
    ax.data_bounds = [0, 0; 100, 100]; //set the data_bounds
    ax.box = 'on'; //draw a box
    Matplot1(M*20, [0,0,100,100])
endfunction


DrawSpiral('ulam.txt')



Steps of Execution :
First of all save the C++ code and compile it and then run it. The code will ask you to input a number N and it will create 2*N+1 by 2*N+1 matrix.

Now run the Scilab code to get the required plots.
You need to call DrawSpiral function 2 times, once with 'ulam.txt' and then with 'random.txt'.