filename stringlengths 7 140 | content stringlengths 0 76.7M |
|---|---|
code/search/src/fibonacci_search/fibonacci_search.py | """
Part of Cosmos by OpenGenus Foundation
"""
def fibonacci_search(arr, x):
length = len(arr)
fib_m2 = 0
fib_m1 = 1
fib_m = fib_m2 + fib_m1
while fib_m < length:
fib_m2 = fib_m1
fib_m1 = fib_m
fib_m = fib_m2 + fib_m1
offset = -1
while fib_m > 1:
i = min(o... |
code/search/src/fibonacci_search/fibonacci_search.swift | /* Part of Cosmos by OpenGenus Foundation */
// fibonacci_search.swift
// Created by erwolfe on 11/17/2017
/**
Fibonacci Search looks through an array for an element and returns it if its found otherwise -1 is returned.
- parameters:
- numberArray: An array of ints that is being traversed to find an element... |
code/search/src/fuzzy_search/fuzzy_search.js | //
// A node module that executes the Fuzzy Search algorithm
//
// Usage:
// const fs = require('./fuzzySearch');
// console.log(fs('A', 'ACC'))
//
"use strict";
function fuzzySearch(needle, haystack) {
var haystack_length = haystack.length;
var needle_length = needle.length;
if (needle_length > haystack_length... |
code/search/src/fuzzy_search/fuzzy_search.php | <?php
/* Part of Cosmos by OpenGenus Foundation */
/* Usage:
echo (fuzzySearch('B', 'ACC')) ? 'true' : 'false';
*/
function fuzzySearch($needle, $haystack)
{
if (strlen($needle) > strlen($haystack)) {
return false;
}
if (strlen($needle) === strlen($haystack)) {
return $needle === $haystack;
}
for ($i ... |
code/search/src/interpolation_search/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/search/src/interpolation_search/interpolation_search.c | #include <stdio.h>
// Part of Cosmos by OpenGenus Foundation
int interpolationSearch(int* array, int n, int key){
int high = n-1;
int low = 0;
int mid;
while ( (array[high] != array[low]) && (key >= array[low]) && (key <= array[high])) {
mid = low + (int)( ((float)(high-low) / (array[high] - ar... |
code/search/src/interpolation_search/interpolation_search.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*
* interpolation search synopsis
*
* warning: in order to follow the convention of STL, the interface is [begin, end) !!!
*
* // [begin, end)
* template<typename _Random_Access_Iter,
* typename _Type = typename std::iterator_traits<_Random_Access_Iter>::val... |
code/search/src/interpolation_search/interpolation_search.go | package main
import "fmt"
func interpolationSearch(array []int, key int) int {
min, max := array[0], array[len(array)-1]
low, high := 0, len(array)-1
for {
if key < min {
return low
}
if key > max {
return high + 1
}
var guess int
if high == low {
guess = high
} else {
size := high -... |
code/search/src/interpolation_search/interpolation_search.java |
public class Interpolation {
static int arr[] = new int[]{10, 12, 13, 15, 17, 19, 20, 21, 22, 23,
24, 33, 35, 42, 49};
public static int interpolationSearch(int x)
{
// Find indexes of two corners
int lo = 0, hi = (arr.length - 1);
... |
code/search/src/interpolation_search/interpolation_search.js | // implementation with looping
function interpolationSearchRecursion(
arr,
value,
low = 0,
high = arr.length - 1
) {
if (arr.length === 0 || (arr.length === 1 && arr[0] !== value)) {
return -1;
}
let mid =
low +
parseInt(((value - arr[low]) / (arr[high] - arr[low])) * (arr.length - 1));
if ... |
code/search/src/interpolation_search/interpolation_search.php | <?php
/**
* Part of Cosmos by OpenGenus Foundation
*
* @param array $array
* @param int $search
*
* @return int
*/
function interpolationSearch(array $array, $search)
{
list ($low, $high) = [0, count($array) - 1];
while (($array[$high] !== $array[$low]) && ($search >= $array[$low]) && ($search <= $arr... |
code/search/src/interpolation_search/interpolation_search.py | def interpolation_search(arr, x):
lo = 0
hi = len(arr) - 1
while lo <= hi and x >= arr[lo] and x <= arr[hi]:
m = lo + int(float(hi - lo) / (arr[hi] - arr[lo] + 1) * (x - arr[lo]))
if arr[m] == x:
return m
if arr[m] < x:
lo = m + 1
else:
... |
code/search/src/jump_search/README.md | # Cosmos

# Jump Search
Jump Search is a searching algorithm for sorted arrays. The idea is to skip some elements by jumping head in the array. In order of time complexity: Linear Search O(n) < Jump Search O(√n) < Binary Search O(Log n). However, Jump Search has an advan... |
code/search/src/jump_search/jump_search.c | #include <stdio.h>
#include <math.h>
#define MAX 100
int find_element(int element);
int arr[MAX],n;
int main()
{
int i,element,result;
printf("\nEnter the number of elements: ");
scanf("%d",&n);
printf("\nEnter the elements of array: \n");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
p... |
code/search/src/jump_search/jump_search.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*
* jump search synopsis
*
* warning: in order to follow the convention of STL, the interface is [begin, end) !!!
*
* namespace jump_search_impl
* {
* template<typename _Random_Access_Iter,
* typename _Tp = typename std::iterator_traits<_Random_Access_Iter>... |
code/search/src/jump_search/jump_search.go | package main
import (
"fmt"
"math"
)
// Part of Cosmos by OpenGenus Foundation
func jumpSearch(arr []int, x int) int {
var left, right int
length := len(arr)
jump := int(math.Sqrt(float64(length)))
for left < length && arr[left] <= x {
right = min(length-1, left+jump)
if arr[left] <= x && arr[right] >= x {... |
code/search/src/jump_search/jump_search.java |
public class JumpSearch {
// Java program to implement Jump Search.
public static int SearchJump(int[] arr, int x) {
int n = arr.length;
// block size through which jumps take place
int step = (int) Math.floor(Math.sqrt(n));
// search in the block
int prev = 0;
while (arr[Math.min(step, n) - 1] < x) {... |
code/search/src/jump_search/jump_search.js | let array = [0, 1, 2, 5, 10, 15, 20, 25, 30, 33];
let wanted = 2;
pos = jumpSearch(array, wanted);
if (pos == -1) {
console.log("Value not found");
} else {
console.log(`Value ${wanted} on position ${pos}`);
}
function jumpSearch(array, wanted) {
const arrayLength = array.length;
const block = getValueBlockS... |
code/search/src/jump_search/jump_search.php | <?php
/**
* Part of Cosmos by OpenGenus Foundation
*
* @param array $array
* @param int $search
*
* @return int
*/
function jumpSearch(array $array, $search)
{
list ($count, $step, $previous) = [$count = count($array), (int) sqrt($count), 0];
while ($array[min($step, $count) - 1] < $search) {
... |
code/search/src/jump_search/jump_search.py | """
Part of Cosmos by OpenGenus Foundation
"""
import math
def jump_search(arr, x):
n = len(arr)
jump = int(math.sqrt(n))
left, right = 0, 0
while left < n and arr[left] <= x:
right = min(n - 1, left + jump)
if arr[left] <= x and arr[right] >= x:
break
left += jum... |
code/search/src/jump_search/jump_search.rs | // Part of Cosmos by OpenGenus Foundation
use std::cmp::min;
fn jump_search(arr: Vec<i32>,n :i32) -> i32 {
let mut step = (arr.len() as f64).sqrt() as usize;
let len = arr.len();
let mut prev: usize = 0;
//Jumps
while arr[min(step, len)-1] < n {
prev = step;
step += step;
... |
code/search/src/jump_search/jump_search.swift | import Foundation
func jumpSearch<T: Comparable>(_ a: [T], for key: T) -> Int? {
let count = a.count
var step = Int(sqrt(Double(count)))
var previous = 0
while a[min(step, count) - 1] < key {
previous = step
step += Int(sqrt(Double(count)))
if previous >= count {
re... |
code/search/src/linear_search/LINEAR_SEARCH.ASM | ; Author: SYEED MOHD AMEEN
; Email: [email protected]
;----------------------------------------------------------------;
; LINEAR SEARCH SUBROUTINE ;
;----------------------------------------------------------------;
;-------------------------------------------------... |
code/search/src/linear_search/README.md | # Linear search
The linear search is the simplest of the searching algorithms.
The goal of the algorithm is check for existence of an element in the given array.
# How it works
Linear search goes through each element of the given array until either the element to be searched is found or we have reached the end of the... |
code/search/src/linear_search/linear_search.c | #include <stdio.h>
/*
* Part of Cosmos by OpenGenus Foundation
*/
/*
* Input: an integer array with size in index 0, the element to be searched
* Output: if found, returns the index of the element else -1
*/
int search(int arr[], int size, int x)
{
int i=0;
for (i=0; i<size; i++)
if (arr[i] == x)
return i... |
code/search/src/linear_search/linear_search.clj | ; generally in list processing languages we
; we don't work with indices but just in case
; you wanted to find position of element from list head
(defn linear-search-list
"Returns the position of the list element from head"
([tlist elem] ;tlist is a linked list
... |
code/search/src/linear_search/linear_search.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*
* linear search synopsis
*
* warning: in order to follow the convention of STL, the interface is [begin, end) !!!
*
* namespace linear_search_impl
* {
* template<typename _Input_Iter,
* typename _Tp = typename std::iterator_traits<_Input_Iter>::value_type... |
code/search/src/linear_search/linear_search.cs | // Part of Cosmos by OpenGenus
public class LinearSearch
{
public static void Main(string[] args)
{
int[] items = new int[] { 10, 12, 52, 634, 24, 743, 234, 7, 25, 742, 76, 25};
int itemToFind = 634;
int itemIndex = linearSearch(items, itemToFind);
if(itemIndex != -1)
... |
code/search/src/linear_search/linear_search.go | package main
import (
"fmt"
)
func main() {
arr := []int{1, 3, 45, 56, 8, 21, 7, 69, 12}
find := 56
index := search(arr, find)
if index != -1 {
fmt.Printf("%d found at index %d", find, index)
} else {
fmt.Printf("%d not found!", find)
}
}
func search(arr []int, x int) int {
for i, n := range arr {
if ... |
code/search/src/linear_search/linear_search.hs | linearsearch :: (Eq a) => [a] -> a -> Maybe Int
linearsearch [] _ = Nothing
linearsearch (x:xs) y = if x == y then Just 0 else (1 +) <$> linearsearch xs y
|
code/search/src/linear_search/linear_search.java | /*
* Part of Cosmos by OpenGenus Foundation
*
*/
// A possible (imaginary) package.
package org.opengenus.cosmos.search;
import java.util.Scanner;
/**
* The {@code LinearSearch} class is the simplest of the searching
* algorithm. The goal of the algorithm is to check the existence of an
* element in the given ... |
code/search/src/linear_search/linear_search.js | /*
* Part of Cosmos by OpenGenus Foundation
*/
/*
* Input : An integer array and the element to be searched
* Output : If found returns the index of element or else -1
* Example :
* var index = linearSearch([1, 2, 3, 4, 7, 8], 8);
*
*/
function linearSearch(arr, element) {
for (var i =... |
code/search/src/linear_search/linear_search.kt | // Part of Cosmos by OpenGenus Foundation
fun <T> linearSearch(array: Array<T>, key: T): Int? {
for (i in 0 until array.size) {
if (array[i] == key) {
return i
}
}
return null
}
fun main(args: Array<String>) {
val sample: Array<Int> = arrayOf(13, 17, 19, 23, 29, 31, 37, 41,... |
code/search/src/linear_search/linear_search.ml | (* Part of Cosmos by OpenGenus Foundation *)
let rec linear_search x = function
| [] -> -1
| hd :: tl when hd == x -> 0
| hd :: tl -> 1 + (linear_search x tl);;
|
code/search/src/linear_search/linear_search.nim | proc linear_search[T](collection: seq[T], item: T): T =
for i in 0..(collection.len() - 1):
if collection[i] == item:
return i
return -1
let s = @[42, 393, 273, 1239, 32]
echo linear_search(s, 273) # prints "2"
echo linear_search(s, 32) # prints "4"
echo linear_search(s, 1) # prints "-1"... |
code/search/src/linear_search/linear_search.php | <?php
/**
* Part of Cosmos by OpenGenus Foundation
*
* @param array $array
* @param int $search
*
* @return int
*/
function linearSearch(array $array, $search)
{
$count = count($array);
for ($i = 0; $i < $count; $i++) {
if ($array[$i] === $search) {
return $i;
}
}
r... |
code/search/src/linear_search/linear_search.py | def linear_search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
|
code/search/src/linear_search/linear_search.rb | # Part of Cosmos by OpenGenus Foundation
items = [5, 10, 34, 18, 6, 7, 45, 67]
target = 7
##
# Returns a boolean that indicates whether the target item is contained within
# the given list.
def linear_search(list, target)
# Iterate over each item in the list
list.each do |item|
return true if item == target
... |
code/search/src/linear_search/linear_search.re | let rec linearSearch = x =>
fun
| [] => (-1)
| [hd, ...tl] when hd === x => 0
| [hd, ...tl] => 1 + linearSearch(x, tl);
|
code/search/src/linear_search/linear_search.rs | fn search(vec: &[i32], n: i32) -> i32 {
for i in 0..vec.len() {
if vec[i] == n {
return i as i32; // Element found return index
}
}
return -1; // If element not found return -1
}
fn main() {
let arr = vec![1, 3, 45, 56, 8, 21, 7, 69, 12];
let num = 56;
let index = s... |
code/search/src/linear_search/linear_search.scala | /* Part of Cosmos by OpenGenus Foundation */
object LinearSearch extends App {
def linearSearch[A: Equiv](list: List[A], element: A): Option[Int] = {
list match {
case Nil => None
case head :: tail => if (head == element) Some(0) else (linearSearch(tail, element).map(_ + 1))
}
}
val list = ... |
code/search/src/linear_search/linear_search.swift | //
// linear_search.swift
// test
//
// Created by Kajornsak Peerapathananont on 10/14/2560 BE.
// Copyright © 2560 Kajornsak Peerapathananont. All rights reserved.
// Part of Cosmos by OpenGenus Foundation
import Foundation
/*
Input : array of item and the element that want to be search
Output : index of elem... |
code/search/src/linear_search/sentinellinearsearch.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*/
/*
* Author: Visakh S
* Github: visakhsuku
* Input: The number of elements in an array, The element to be searched, An integer array.
* Output: if found returns "found" else "not found", using the sentinel linear search algorithm.
*/
#include <iostream>
#include <... |
code/search/src/ternary_search/README.md | # Ternary search
The ternary search algorithm is used for finding a given element in a sorted array.
## Procedure
1. Find where the array divides into two thirds
2. Compare the value of both the thirds elements with the target element.
3. If they match, it is returned the index.
4. If the value is less than the first... |
code/search/src/ternary_search/ternary_search.c | #include <stdio.h>
// Function to perform Ternary Search
int ternarySearch(int array[], int left, int right, int x)
{
if (right >= left) {
// Find the leftmid and rightmid
int intvl = (right - left) / 3;
int leftmid = left + intvl;
int rightmid = leftmid + intvl;
// Check if ele... |
code/search/src/ternary_search/ternary_search.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*
* Ternary Search Uses Divide And Conquer Technique
*
* ternary search synopsis
*
* namespace ternary_search_impl
* {
* template<typename _RandomAccessIter,
* typename _ValueType = typename std::iterator_traits<_RandomAccessIter>::value_type,
* t... |
code/search/src/ternary_search/ternary_search.go | package main
import (
"fmt"
)
// Part of Cosmos by OpenGenus Foundation
func ternarySearch(data []int, left int, right int, value int) int {
if right >= left {
mid1 := left + (right-left)/3
mid2 := right - (right-left)/3
if data[mid1] == value {
return mid1
}
if data[mid2] == value {
return mid2
... |
code/search/src/ternary_search/ternary_search.java | public static void main(String[] args) {
//declare a string array with initial size
String[] songs = {"Ace", "Space", "Diamond"};
System.out.println("\nTest binary (String):");
System.out.println(search(songs, "Ace", 0, 3));
}
public static int search(String[] x, String target, int start, int end) {... |
code/search/src/ternary_search/ternary_search.js | /*
* Part of Cosmos by OpenGenus Foundation
*/
function ternarySearch(givenList, left, right, absolutePrecision) {
while (true) {
if (Math.abs(right - left) < absolutePrecision) {
return (left + right) / 2;
}
var leftThird = left + (right - left) / 3;
var rightThird = right - (right - left) ... |
code/search/src/ternary_search/ternary_search.kt | // Part of Cosmos by OpenGenus Foundation
fun <T : Comparable<T>> ternarySearch(a: Array<T>, target: T, start: Int = 0, end: Int = a.size): Int {
if (start < end) {
val midpoint1 : Int = start + (end - start) / 3
val midpoint2 : Int = start + 2 * (end - start) / 3
return when (target) {
... |
code/search/src/ternary_search/ternary_search.php | <?php
/**
* Part of Cosmos by OpenGenus Foundation
*
* @param array $array
* @param int $low
* @param int $high
* @param int $search
*
* @return int
*/
function ternarySearch(array $array, $low, $high, $search)
{
if ($high >= $low) {
list($lowMiddle, $highMiddle) = [$low + ($high - $low) / 3... |
code/search/src/ternary_search/ternary_search.py | def ternary_search(arr, to_find):
left = 0
right = len(arr) - 1
while left <= right:
temp2 = left + (right - left) // 3
temp3 = left + 2 * (right - left) // 3
if to_find == arr[left]:
return left
elif to_find == arr[right]:
return right
elif to... |
code/search/src/ternary_search/ternary_search.rs | // Part of Cosmos by OpenGenus Foundation
fn main() {
let nums = vec![1, 3, 5, 7, 9];
let ele = 5;
println!("Sample input list: {:?}", nums);
println!("Searched for {} and found index {}", ele, ternary_search(&nums, 0, nums.len(), ele));
}
fn ternary_search(nums: &Vec<i64>, left: usize, right: usize, x... |
code/search/test/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/search/test/test_search.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*/
#define CATCH_CONFIG_MAIN
#include "../../../test/c++/catch.hpp"
#include <list>
#include <vector>
#include <iterator>
#include <algorithm>
#include "../src/binary_search/binary_search.cpp"
#include "../src/exponential_search/exponential_search.cpp"
#include "../src/fib... |
code/search/test/test_search.py | import sys
import os
sys.path.insert(0, os.path.realpath(__file__ + "/../../"))
import bisect
import random
import src.linear_search.linear_search
import src.binary_search.binary_search
import src.fibonacci_search.fibonacci_search
import src.ternary_search.ternary_search
import src.jump_search.jump_search
import src.i... |
code/selection_algorithms/src/README.md | # QuickSelect
It is a selection algorithm to find the k-th smallest element in an unordered list. It is related to the quick sort sorting algorithm.
## Complexity
O(n) (with a worst-case of O(n^2))
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Founda... |
code/selection_algorithms/src/median_of_medians/median_of_medians.c | // Part of OpenGenus/cosmos
// Author : ABDOUS Kamel
// The median of medians algorithm.
// Deterministic select algorithm that executes
// in O(n) in the worst case.
#include <stdio.h>
#define MEDIAN_GROUPS_SIZE 5
int partition(int array[], int beg, int end, int pivotIndex)
{
int pivotValue = array[pivotIndex];
... |
code/selection_algorithms/src/median_of_medians/median_of_medians.hs | import Data.List
median :: (Show a, Ord a) => [a] -> a
median xs = select ((length xs) `div` 2) xs
select :: (Show a, Ord a) => Int -> [a] -> a
select i xs
| n <= 5 = (sort xs) !! i
| lengthLower == i = medianOfMedians
| lengthLower < i = select (i - lengthLower - 1) upperPartition
|... |
code/selection_algorithms/src/median_of_medians/median_of_medians.py | def select(A, i):
if len(A) <= 5:
return sorted(A)[i]
chunks = [A[i : i + 5] for i in range(0, len(A), 5)]
medians = [select(chunk, len(chunk) // 2) for chunk in chunks]
medianOfMedians = select(medians, len(medians) // 2)
lowerPartition, upperPartition = (
[a for a in A if a < media... |
code/selection_algorithms/src/quick_select.java | // Part of Cosmos by OpenGenus Foundation
//Find kith largest element is equivalent to find (n - k)th smallest element in array.
//It is worth mentioning that (n - k) is the real index (start from 0) of an element.
public class Solution {
public int findKthLargest(int[] nums, int k) {
int start = 0, end = n... |
code/selection_algorithms/src/quick_select.kt | const val MAX = Int.MAX_VALUE
val rand = java.util.Random()
fun partition(list:IntArray, left: Int, right:Int, pivotIndex: Int): Int {
val pivotValue = list[pivotIndex]
list[pivotIndex] = list[right]
list[right] = pivotValue
var storeIndex = left
for (i in left until right) {
if (list[... |
code/selection_algorithms/src/quick_select.swift | import Foundation
public func kthLargest(_ a: [Int], _ k: Int) -> Int? {
let len = a.count
if k > 0 && k <= len {
let sorted = a.sorted()
return sorted[len - k]
} else {
return nil
}
}
public func random(min: Int, max: Int) -> Int {
assert(min < max)
return min + Int(arc4random_uniform(UInt32(... |
code/selection_algorithms/src/quickselect.cpp | // This algorithm is similar to quicksort because it
// chooses an element as a pivot and partitions the
// data into two based on the pivot. However, unlike
// quicksort, quickselect only recurses into one side
// - the side with the element it is searching for.
#include <iostream>
#include <vector>
#include <cmath>
#... |
code/selection_algorithms/src/quickselect.go | package main
import (
"math/rand"
)
func quickselect(list []int, item_index int) int {
return selec(list,0, len(list) - 1, item_index)
}
func partition(list []int, left int, right int, pivotIndex int) int {
pivotValue := list[pivotIndex]
// move pivot to end
list[pivotIndex], list[right] = list[right], list[pi... |
code/selection_algorithms/src/quickselect.py | def quickselect(items, item_index):
def select(lst, l, r, index):
# base case
if r == l:
return lst[l]
# choose random pivot
pivot_index = random.randint(l, r)
# move pivot to beginning of list
lst[l], lst[pivot_index] = lst[pivot_index], lst[l]
... |
code/selection_algorithms/src/quickselect_stl.cpp | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> v(n);
for (int i = 0; i < n; i++)
cin >> v[i];
int k;
cin >> k;
nth_element(v.begin(), v.begin() + k, v.end());
cout << v[k] << endl;
return 0;
}
|
code/selection_algorithms/test/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/shell_script/Looping/README.md | # Looping Structures in Shell Scripting
Loops are used to implement same problem logic multiple times with slight variation.
Looping structures provided in Shell Scripts are while loop and for loop.
In Shell, following looping structures are available:
[1. For Loop](for_loop)
[2. While loop](while_loop)
|
code/shell_script/Looping/for_loop/for_break.sh | #!/bin/bash
i=1; #initialize variable to 1
for (( ; ; )) #infinite loop
do
echo "$i"
i=$(($i+1))
if [ $i -eq 10 ]
then
break;
fi
done
|
code/shell_script/Looping/for_loop/for_continue.sh | #!/bin/bash
for i in 1 2 3 4 5
do
if [ $i -eq 3 ]
then
continue;
fi;
echo "$i";
done
|
code/shell_script/Looping/for_loop/for_ctype.sh | #!/bin/bash
for (( i=0; i<10; i++ ))
do
echo "$i";
done
|
code/shell_script/Looping/for_loop/for_increment.sh | #!/bin/bash
for i in {1..10}
do
echo "This is $i increment"
done
|
code/shell_script/Looping/for_loop/for_infinite.sh | #!/bin/bash
for (( ; ; ))
do
echo "Infinite loop";
done
|
code/shell_script/Looping/for_loop/for_items.sh | for i in Hello World "Hello World" Bye
do
echo "$i"
done
|
code/shell_script/Looping/for_loop/for_jump.sh | #!/bin/bash
for i in {1..10..2}
do
echo "This is $i";
done
|
code/shell_script/Looping/for_loop/for_seq.sh | #!/bin/bash
for i in `seq 1 10`
do
echo "This is $i increment"
done
|
code/shell_script/Looping/for_loop/forloop_tuple.sh | #!/bin/bash
for i in 1 2 3 4 5 6 7 8
do
echo "This is loop $i";
done
|
code/shell_script/Looping/while_loop/while_basics.sh | #!/bin/bash
i=1
while [ $i -le 5 ]
do
echo "$i";
i=$(($i+1));
done
|
code/shell_script/Looping/while_loop/while_infinite.sh | #!/bin/bash
while :
do
echo "infinite loop";
done
|
code/shell_script/README.md | # Shell Scripting
# Table Of Contents
[1. Basic Shell Scripts](basic_scripts)
[2. Control Structures In Shell](control_structures)
[3. Functions](functions)
[4. Looping structures](Looping)
[5. Make and Makefile](make_and_makefile)
Shell Scripting comprises of two terms:
**Shell:** In Linux OS, Shell is the int... |
code/shell_script/basic_scripts/README.md | # Basic Shell Scripts
[1. Hello World Code](src/HelloWorld.sh)
[2. Variable Declaration](src/variable.sh)
[3. Taking input from User](src/readvar.sh)
[4. Standard Input and Output example](src/inout.sh)
[5. Unsetting variables](src/deletevar.sh)
[6. Special Variables](src/specialvar.sh)
[7. Command line argument... |
code/shell_script/basic_scripts/src/HelloWorld.sh | #!/bin/bash
echo "Hello World"
|
code/shell_script/basic_scripts/src/arithmetic.sh | #!/bin/bash
echo "Arithmetic Operations on Shell";
read -p "Enter an Real value: " val1
read -p "Enter another Real value: " val2
echo "Addition: $(($val1+$val2))"
echo "Subtraction: $(($val1-$val2))"
echo "Multiplication: $(($val1*$val2))"
div=$(($val1/$val2))
echo "Division: ${div}"
|
code/shell_script/basic_scripts/src/commandlineargument.sh | #!/bin/bash
echo "Command Line Arguments"
echo "File name: $0";
echo "First Argument: $1";
echo "Second Argument: $2";
echo "Number of Arguments sent: $#";
echo "All arguments in same quotes: $*";
echo "All arguments in individual quotes: $@";
|
code/shell_script/basic_scripts/src/deletevar.sh | #!/bin/bash
var1="Variable to be deleted!";
echo "$var1";
unset var1;
echo "Printing unset variable: $var1";
# Trying unset keyword on readonly
readonly var2="Readonly var";
echo $var2;
unset var2;
echo $var2;
|
code/shell_script/basic_scripts/src/inout.sh | #!/bin/bash
echo "Hello $(whoami)! I am your assistant!"
read -p "Enter your real name: " name
echo "Hello $name"
|
code/shell_script/basic_scripts/src/readvar.sh | #!/bin/bash
# This is how you add comments
# Reading variable without promptings users
read var1
echo "$var1"
# Reading variable by prompting user
read -p "Enter a value: " var2
echo "$var2"
# Reading a silent variable by prompting user
read -sp "Enter a value: " var3
echo "" # By default it has an endline attached
ec... |
code/shell_script/basic_scripts/src/specialvar.sh | #!/bin/bash
echo "Current File Name: $0"
echo "Process number of current Shell: $$"
echo "Process Number of last background command: $!"
echo "Exit ID of last executed command: $?"
|
code/shell_script/basic_scripts/src/variable.sh | #!/bin/bash
# creating a normal variable
var1="Variable 1"; # No spacing between variable name and value else error
echo $var1;
# Changing value of variable 1
var1="Variable 1 updated";
echo $var1;
# Creating readonly variable
readonly var2="Readonly var";
echo $var2;
var2="Can I change?";
echo $var2;
|
code/shell_script/control_structures/README.md | # Control Structures in Shell Scripting
Control structures are structures that are used in decision making.
A condition is checked and different execution paths can be defined based on whether the condition is true or false.
In Shell Scripts, we have two control structures:
1. If Elif Else fi
2. Switch cases
|
code/shell_script/control_structures/src/if_elif_else.sh | #!/bin/bash
echo "Enter two numbers"
read num1
read num2
if [ $num1 -gt $num2 ]
then
echo "$num1 is greater than $num2"
elif [ $num1 -eq $num2 ]
then
echo "Both numbers are equal"
else
echo "$num2 is greater than $num1"
fi
|
code/shell_script/control_structures/src/if_else.sh | #!/bin/bash
read -p "Enter username: " name
if [ $name == "admin" ]
then
echo "Access Granted"
else
echo "Access Denied"
fi
|
code/shell_script/control_structures/src/switch_case.sh | #!/bin/bash
read -p "Enter your name: " name
case $name in
admin) echo "Access Granted! Welcome Admin" ;;
root) echo "Access Granted! Welcome root" ;;
*) echo "Access Denied" ;;
esac
|
code/shell_script/deleting_old_archives.sh | #!bin/bash
cd /home/kshitiz/archives
rm $(find -mtime +2 -name "*.tar")
rm $(find -mtime +2 -name "*.tar.gz")
rm $(find -mtime +2 -name "*.tar.bz2")
|
code/shell_script/functions/README.md | # Functions in Shell Scripting
Functions are subsets of a code that implement an independent programming logic.
For example, to create a four function calculator, independent programming logic are:
1. Addition function
2. Multiplication function
3. Division function
4. Subtraction function
Function allows us to divid... |
code/shell_script/functions/src/func_parameters.sh | #!/bin/bash
function1()
{
echo "Parameter 0 (File Name): $0"
echo "Parameter 1: $1"
echo "Parameter 2: $2"
}
function1 p1 p2;
|
code/shell_script/functions/src/function.sh | #!/bin/bash
# Create function
function1()
{
echo "Inside Function body";
}
# Invoke Function using function name
function1
|
code/shell_script/functions/src/multicall.sh | #!/bin/bash
add()
{
return $(($1+$2))
}
multiply()
{
return $(($1*$2))
}
# Call Addition for 3 and 4 == 7
add 3 4
echo "$?"
# Call multiplication for 3 and 4 == 12
multiply 3 4
echo "$?"
# Call Addition for 5 and 4 == 9
add 5 4
echo "$?"
|
code/shell_script/functions/src/multiplefunctioncall.sh | #!/bin/bash
add()
{
return $(($1+$2))
}
multiply()
{
return $(($1*$2))
}
# Call Addition for 3 and 4 == 7
add 3 4
# Call multiplication for 3 and 4 == 12
multiply 3 4
# Call Addition for 5 and 4 == 9
add 5 4
# Store answer (always stores final function call returned value)
ans=$?
echo "$ans"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.