Skip to content

Instantly share code, notes, and snippets.

@avanishgiri
avanishgiri / robot_movements.cpp
Last active December 28, 2015 03:58
This program uses backtracking to count the number of paths from [1][1] to [N][N] in an NxN array.
#include <iostream>
using namespace std;
#define N 4
#define LEGAL 1
#define ILLEGAL 0
int counter = 0;
void count_paths(int x, int y, int n, int m, int array[N+2][N+2]){
if(x == n && y == m){
@avanishgiri
avanishgiri / frequencies.rb
Created November 12, 2013 08:03
Returning the k most frequent words in a string
def word_frequencies(string, k)
words = string.split(/\s/) # O(n) ## delimit by whitespace
max = 0
min = Float::INFINITY
# create hash table for word --> frequency #
frequencies = words.inject(Hash.new(0)) do |hash,word| # O(n)
occurrences = hash[word] += 1
max = occurrences if occurrences > max
#include <iostream>
using namespace std;
void print_combos(string s){
int len = s.length();
int iterations = 1 << len; //this makes iterations 2 to the power of length
for(int i = 0; i < iterations; i++){
@avanishgiri
avanishgiri / como.cpp
Created November 8, 2013 01:15
combo.cpp
#include <iostream>
using namespace std;
void combos(string soFar, string rest, string full){
if(rest == ""){
int len = full.length();
for(int i = 0, j = 0; i < len; i++)
{
if(i == (int)(soFar[j] - '0')){
@avanishgiri
avanishgiri / NQueens.java
Last active December 25, 2015 20:49
This program prints out every solution the N-Queens puzzle. ------- http://en.wikipedia.org/wiki/Eight_queens_puzzle
public class NQueens
{
final static int N = 12;
private static boolean possibleQueen(boolean[][] board, int row, int column){
for(int i = 0; i < N; i++)
if(board[row][i] && i != column)
return false;
for(int i = 0; i < N; i++)
public class NQueens
{
final static int N = 15;
private static boolean possibleQueen(boolean[][] board, int row, int column){
for(int i = 0; i < N; i++)
if(board[row][i] && i != column)
return false;
for(int i = 0; i < N; i++)
@avanishgiri
avanishgiri / find_pivot.rb
Last active December 24, 2015 13:39
Solution to find pivot in linear time
def find_pivot(array)
return -1 if array.empty?
left = 0
right = array[1..-1].inject(0,:+)
for i in 0...array.length
return i if left == right
left += array[i]
right -= array[i+1] || 0
class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.string :title
t.integer :seller_id
t.timestamps
end
end
end
#include <iomanip>
#include <iostream>
using namespace std;
void bottomLeft(int** array, int x1, int y1, int x2, int y2);
void topRight(int **array, int x1, int y1, int x2, int y2){
for(int i = x1; i<= x2; i++){
cout << array[y1][i] << " ";
}
class Integer
def printMySquare
print self * self
print "\t"
return self
end
end
puts 4.printMySquare