slips
November 30, 2023

SLIP24

Q.1 Write a Java Program to implement Singleton pattern for multithreading.

public class Singleton {
    // Declare the volatile instance variable to ensure visibility across threads
    private static volatile Singleton instance;

    // Private constructor to prevent instantiation from other classes
    private Singleton() {
        // Initialize the instance as needed
    }

    // Double-Checked Locking to ensure only one instance is created
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

    // Add other methods or attributes as needed
    public void showMessage() {
        System.out.println("Hello from Singleton!");
    }

    public static void main(String[] args) {
        // Create multiple threads to access the Singleton
        Thread thread1 = new Thread(() -> {
            Singleton singleton = Singleton.getInstance();
            singleton.showMessage();
        });

        Thread thread2 = new Thread(() -> {
            Singleton singleton = Singleton.getInstance();
            singleton.showMessage();
        });

        // Start the threads
        thread1.start();
        thread2.start();
    }
}

Q.2 Write a python program to implement simple Linear Regression for predicting house price.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

data = pd.read_csv('./csv/Housing.csv')
X = data['area'].values.reshape(-1, 1)
y = data['price'].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
slope = model.coef_[0]
intercept = model.intercept_
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f"Linear Regression Equation: price = {slope:.2f} * area + {intercept:.2f}")
print(f"Mean Squared Error: {mse:.2f}")
print(f"R-squared: {r2:.2f}")
plt.scatter(X_test, y_test, color='blue', label='Actual Data')
plt.plot(X_test, y_pred, color='red', linewidth=2, label='Regression Line')
plt.xlabel('Area (sqft)')
plt.ylabel('Price ($)')
plt.title('House Price Prediction')
plt.legend()
plt.show()

Q.3 Print below array elements using map: a. let fruits1 = ["apple", "banana"]; b. let fruits2 = ["cherry", "orange"]; c. Merge both fruits array and print it

Paste the FruitsList.jsx In src Folder

import React from 'react';
const FruitsList = () => {
  let fruits1 = ["apple", "banana"];
  let fruits2 = ["cherry", "orange"];
  // Merge both arrays
  let allFruits = [...fruits1, ...fruits2];
  return (
    <div>
      <h1>Merged Fruits List</h1>
      <ul>
        {allFruits.map((fruit, index) => (
          <li key={index}>{fruit}</li>
        ))}
      </ul>
    </div>
  );
};
export default FruitsList;