I am trying to populate a 2D array vertically or horizontally from a given coordinate, if the indexes are in range.
Below is the program I can think about as of now.
I just want to know if there is any other optimized way to perform this logical operation.
public static void Main()
{
var arr = new string[10,10];
int x = 0;
int y = 1;
int len = 5;
string somevalue = "x";
string align = "vertical";
int i = x;
int j = y;
try
{
while(len > 0)
{
arr[i,j] = somevalue;
if(align == "vertical")
j++;
else
i++;
len--;
}
}
catch(IndexOutOfRangeException ex)
{
Console.WriteLine(ex);
}
}
Related
I was trying to solve below problem:
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Here is my code:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* intersect(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){
for(int i=0; i<nums1Size-1; i++){
if(nums1[i]>nums1[i+1]){
int temp = nums1[i];
nums1[i] = nums1[i+1];
nums1[i+1] = temp;
i = -1;
}
}
for(int i=0; i<nums2Size-1; i++){
if(nums2[i]>nums2[i+1]){
int temp = nums2[i];
nums2[i] = nums2[i+1];
nums2[i+1] = temp;
i = -1;
}
}
int i = 0;
int j = 0;
int* res = (int*)malloc(10* sizeof(int));
int k = 0;
if(!(nums1Size > nums2Size)){
int * temp = nums1;
nums1 = nums2;
nums2 = temp;
int tempint = nums1Size;
nums1Size = nums2Size;
nums2Size = tempint;
}
while(i<nums1Size && j<nums2Size){
if(nums1[i] > nums2[j]){
j++;
}
else if(nums1[i] < nums2[j]){
i++;
}
else{
res[k++] = nums1[i];
i++; j++;
}
}
*returnSize = sizeof(res)/sizeof(res[0]);
return res;
}
To simplify the problem you have to solve, let's first write a helper function that counts the number of occurrences of a particular element inside an array:
int count_elem(int* arr, int n, int elem) {
int count = 0;
for (int i = 0; i < n; i += 1) {
if (arr[i] == elem) {
count += 1;
}
}
return count;
}
Now, let's try to solve the problem following the problem description:
int* intersect(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize) {
// here we allocate `res` with size of the biggest array, because that's the worst case we'll have
int* res = malloc(sizeof(int) * ((nums1Size > nums2Size) ? nums1Size : nums2Size));
// just to be sure `malloc()` did not return an error
if (res == NULL) {
return NULL;
}
// we'll keep track of how many elements we actually put inside `res`
*returnSize = 0;
// let's loop through all elements of `nums1`
for (int i = 0; i < nums1Size; i += 1) {
int elem = nums1[i];
// if we already put the element inside `res`, we skip this cycle
int count_res = count_elem(res, *returnSize, elem);
if (count_res > 0) {
continue;
}
// let's count the occurrences in both arrays
int count1 = count_elem(nums1, nums1Size, elem);
int count2 = count_elem(nums2, nums2Size, elem);
// let's calculate how many times the element must be present inside `res`
// i.e.: the same number of times of the array with the fewer occurrences of it
// NOTE: if `nums1` or `nums2` do not include the element, we also don't include it inside `res`
int count_min = (count1 < count2) ? count1 : count2;
// now let's put inside `res` as many times as we previously calculated
for (int i = 0; i < count_min; i += 1) {
res[*returnSize] = elem;
*returnSize += 1;
}
}
return res;
}
Let's try if it works:
int main(void) {
int arr1[] = {1, 2, 2, 1};
int arr2[] = {2, 2};
int res_size;
int* res = intersect(arr1, sizeof(arr1) / sizeof(arr1[0]), arr2, sizeof(arr2) / sizeof(arr2[0]), &res_size);
// let's print the result of `intersect()`
for (int i = 0; i < res_size; i += 1) {
printf("%d\n", res[i]);
}
return 0;
}
Output:
2
2
NOTE: the function is not optimized for speed nor for memory efficiency. This will be left as an exercise for the reader.
UPDATE
The previous version of the answer was wrong (sorry again). Now it should be correct.
I attempted the first LeetCode Problem: Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
However, I keep getting a similar runtime error:
Finished in N/A
java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
at line 67, Solution.sortArr
at line 11, Solution.twoSum
I am not very used to using multidimensional arrays and saw this as the perfect opportunity to use them and learn. I've provided my code, could anyone help me figure out why this is failing?
class Solution {
public int[] twoSum(int[] nums, int target)
{
int[] targetIndex = {0,0};
int arrEndIndex = nums.length - 1;
int[][] copyArr = new int[nums.length][];
copyArr = copyArrWithIndex(nums);
int[][] sortedArr = new int[nums.length][];
sortedArr = sortArr(copyArr);
int firstIndex = 0;
int secondIndex = arrEndIndex;
int firstElement = 0;
int secondElement = 0;
while(firstIndex != secondIndex)
{
firstElement = sortedArr[firstIndex][0];
secondElement = sortedArr[secondIndex][0];
if(firstElement + secondElement == target)
{
targetIndex[0] = sortedArr[firstIndex][1];
targetIndex[1] = sortedArr[secondIndex][1];
break;
}
else if(firstElement + secondElement < target)
{
firstIndex++;
}
else
{
secondIndex--;
}
}
return targetIndex;
}
/*
This function sorts a 2D array of ints from least to greatest based
on the values in the first column and returns a 2D array of ints
*/
private int[][] sortArr(int[][] arr)
{
int temp = 0;
int firstIndex = 0;
int secondIndex = 1;
int firstElement = 0;
int secondElement = 0;
int i = 0;
while(i < arr[0].length)
{
firstElement = arr[firstIndex][0];
secondElement = arr[secondIndex][0];
if(firstElement < secondElement)
{
firstIndex++;
secondIndex++;
}
else /*if(firstElement > secondElement)*/
{
temp = firstElement;
arr[firstIndex][0] = secondElement;
arr[secondIndex][0] = temp;
temp = firstIndex;
arr[firstIndex][1] = secondIndex;
arr[secondIndex][1] = temp;
if(firstIndex != 0)
{
firstIndex--;
secondIndex--;
}
else
{
firstIndex++;
secondIndex++;
}
}
}
return(arr);
}
/*
This function accepts a 1D array and returns a 2D array of ints with the index int in the first
column and the original index of the presorted number adjacently in the second
column
*/
private int [][] copyArrWithIndex(int[] arr)
{
int[][] copyArr = new int [arr.length][2];
for(int i = 0; i < arr.length; i++)
{
copyArr[i][0] = arr[i];
copyArr[i][1] = i;
}
return(copyArr);
}
}
My question concerns creating an array of moving objects. The goal is to have each created "symbol" starts at x=200 when created and then moves along the x-axis. This is possible by creating individual objects, though when I try to make them appear in an array they just appear on top of each other (made the balls transparent so you can see them stack). Is there a way to create an array of individual array objects so that this doesn't happen.
int numSymbols = 100;
int symbolXPos;
int i;
Symbol[] symbols = new Symbol[numSymbols];
void setup(){
for(int i = 0; i < numSymbols; i++){
symbols[i] = new Symbol();
}
size(748,1024);
}
void draw(){
background(255,255,255);
i++;
if(i > 10){
symbols[1].addSymbol(i);
}
if(i > 100){
symbols[2].addSymbol(i);
}
if(i > 200){
symbols[3].addSymbol(i);
}
}
int symbolY = 748-2*6-89-180;
int symbolX = 200;
int symbolPos;
boolean firstLoop = true;
int xSpeed;
class Symbol{
void addSymbol(int xSpeed){
if(firstLoop == true){
symbolXPos = xSpeed;
firstLoop = false;
}else{
xSpeed = symbolX + (xSpeed - symbolXPos);
fill(0,0,0,20);
noStroke();
rect(xSpeed,symbolY, 36, 36, 18);
}
}
}
The first part that looks strange is that you have these properties that seem related to a Symbol instance, and not to the main scope:
int symbolY = 748-2*6-89-180;
int symbolX = 200;
int symbolPos;
boolean firstLoop = true;
int xSpeed;
perhaps you meant something like this:
int numSymbols = 100;
int symbolXPos;
int i;
Symbol[] symbols = new Symbol[numSymbols];
void setup() {
for (int i = 0; i < numSymbols; i++) {
symbols[i] = new Symbol();
}
size(748, 1024);
}
void draw() {
background(255, 255, 255);
i++;
if (i > 10) {
symbols[1].addSymbol(i);
}
if (i > 100) {
symbols[2].iaddSymbol(i);
}
if (i > 200) {
symbols[3].addSymbol(i);
}
}
class Symbol {
int symbolY = 748-2*6-89-180;
int symbolX = 200;
int symbolPos;
boolean firstLoop = true;
int xSpeed;
void addSymbol(int xSpeed) {
if (firstLoop == true) {
symbolXPos = xSpeed;
firstLoop = false;
} else {
xSpeed = symbolX + (xSpeed - symbolXPos);
fill(0, 0, 0, 20);
noStroke();
rect(xSpeed, symbolY, 36, 36, 18);
}
}
}
Even so, it feels like the code is more complex than it should be and there is some confusion regarding classes and objects/instances.
Let's assume you're simply going to move symbols horizontally. You could use a class as simple as this:
class Symbol{
//position
float x;
float y;
//speed
float speedX;
void updateAndDraw(){
//update position
x += speedX;
//reset to 0 if out of bounds
if(x > width) x = 0;
//draw
rect(x, y, 8, 8, 18);
}
}
It has an x,y and just a speedX for now. The x property is incremented by the speed, and the updated position is used to render the symbol on screen.
Here's a basic sketch using the above class:
int numSymbols = 100;
Symbol[] symbols = new Symbol[numSymbols];
void setup(){
size(748, 1024);
fill(0, 0, 0, 64);
noStroke();
for (int i = 0; i < numSymbols; i++) {
symbols[i] = new Symbol();
//use different speeds to easily tell the symbols appart
symbols[i].speedX = 0.01 * (i+1);
//increment y position so symbols don't overlap
symbols[i].y = 10 * i;
}
}
void draw(){
background(255);
for (int i = 0; i < numSymbols; i++) {
symbols[i].updateAndDraw();
}
}
class Symbol{
//position
float x;
float y;
//speed
float speedX;
void updateAndDraw(){
//update position
x += speedX;
//reset to 0 if out of bounds
if(x > width) x = 0;
//draw
rect(x, y, 8, 8, 18);
}
}
The key points are:
using properties related to a Symbol within the class, not outside (which would mean the global scope)
using different positions so Symbol instances don't overlap
Be sure to check out Daniel Shiffman's Objects tutorial, it provides a nice and easy intro to Object Oriented Programming
I'm taking a computer science class at my high school, and we learned a lesson on selection sort today. I wrote a program (it's probably clumsy, but please bear with me, I'm learning) and it works in that it sorts, but sometimes it throws an ArrayIndexOutOfBoundsException. Only sometimes. I don't know how this is possible, because I deal with the same array throughout the entire program and arrays have a fixed length. If anyone has some insight it would be extremely helpful.
I think the error has something to do with int first = y[movedVariable];. However, I don't understand how movedVariable can be out of bounds, because I'm pretty sure I wrote my program so that it would be < the length of the array.
public class selectionSort
{
public static int[] array;
public static int movedVariable = 0;
public static void main()
{
array = new int[10];
int x;
for (int count = 0; count < array.length; count++)
{
if (count == 0)
{
x = (int)(Math.random()*100+2);
array[count] = x;
}
else
{
x = (int)(Math.random()*100+2);
for (int y = 0; y < count; y++)
{
while(x == array[y])
{
x = (int)(Math.random()*100+2);
}
}
array[count] = x;
}
}
sort(array);
}
public static void sort(int[] x)
{
int thing = 0;
for(int hello = 0; hello < x.length; hello++)
{
int part = x[thing];
for ( int count = thing; count < x.length-1; count++)
{
if( part > x[count+1] )
{
part = x[count+1];
}
}
thing++;
swap( x, part);
}
int f = 0;
String output = "";
for( int val : x )
{
if (f%10 == 0)
{output += "\n";}
output += val + " ";
f++;
}
System.out.print(output);
}
public static int[] swap(int [] y, int num)
{
int count = 0;
int index = 0;
for ( count = 0; count < y.length; count++)
{
if (y[count] == num)
{index = count;}
}
int first = y[movedVariable];
y[movedVariable] = y[index];
y[index] = first;
movedVariable++;
return y;
}
}
For fun, I ran your code for 1,000,000 iterations and no out of bounds exception, unless I did not clear the static movedVariable to 0 before each iteration.
Since movedVariable is static after the first 10 calls to swap() it will be 10 and if another call is made to swap you'll get the index out of bounds. However, this can only happen if you call sort() more than once per run. Only use static for values that need to be preserved between instances of your class. Non statics that are part of the your instance state. Local variables for everything else. Otherwise your are creating a mine field of bugs just waiting to happen.
I refactored your class to remove variables that have the same functionality. For example your thing and your movedVariable and your hello variable in sort() can be just one variable. Try to eliminate multiple variables that do the same thing, like the plague. It is a source of non obvious bugs.
Also, you are passing the value in the array to swap then looking for it in the array to get the index, this is a waste of time. Just pass in the index to swap. It also creates a problem for your sort function when you have the same value at two different places. Swap will use the last one it finds. sort() should handle duplicate values in the array. That explains why you initialized your array with unique values. You should not have to do that. Actually you should test your code with duplicates explicitly added to make sure your function works.
I moved printing of the array out of sort into its own method. It is useful for debugging at intermediate steps not just when the sort is done.
I tried to leave variable names the same and the logic unchanged so you can follow the changes.
public class Main
{
public static void sort(int[] x)
{
for (int movedVariable = 0; movedVariable < x.length; movedVariable++)
{
int part = x[movedVariable];
int index = movedVariable;
for (int count = movedVariable; count < x.length - 1; count++)
{
if (part > x[count + 1])
{
part = x[count + 1];
index = count + 1;
}
}
swap(x, index, movedVariable);
}
printArray(x);
}
private static void printArray(int[] x)
{
int f = 0;
String output = "";
for (int val : x)
{
if (f % 10 == 0)
{
output += "\n";
}
output += val + " ";
f++;
}
System.out.print(output);
}
public static int[] swap(int[] y, int index, int movedVariable)
{
int first = y[movedVariable];
y[movedVariable] = y[index];
y[index] = first;
return y;
}
public static void main(String[] args)
{
int[] array = new int[10];
int x = 0;
for (int count = 0; count < array.length; count++)
{
for (int y = count; --y >= 0; )
{
do
{
x = (int) (Math.random() * 100 + 2);
}
while (x == array[y]);
}
array[count] = x;
}
printArray(array);
sort(array);
}
}
I need an idea how to effectively find areas below marked with 0 in two-dimensional array. It should be noted that there are other areas, such as this picture shows one of two who owns coordinate (0.0) and the other owns coordinate (21.3).
00000000000111110000111
00000000001111110000111
00000000011111100000111
00000000000111000001101
00000000011100000011101
00000001111100001111001
00000111111111011111001
00000001111100001111001
00000000010000000011001
00000000000000000001111
Of course a real array will be much larger.
Recursive version that goes to all sides and stops at mark 1 or array side isn't fast enough.
It looks like you're looking for a flood-fill algorithm. The wikipedia page I linked lists a few algorithms which may be faster than the obvious recursive method.
Flood-fill will be a good match if the areas you're looking for are small compared to the entire array, and you don't need to search for all of them. If you need to know about most or all of them, then computing them all in a single shot using a union-merge based connected component labeling algorithm may be a better choice. Here's some code that implements such an algorithm (note that I've altered it to run in a single pass):
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <map>
const char *data[] = {
"00000000000111110000111",
"00000000001111110000111",
"00000000011111100000111",
"00000000000111000001101",
"00000000011100000011101",
"00000001111100001111001",
"00000111111111111111001",
"00000001111100001111001",
"00000000010000000011001",
"00000000000000000001111",
NULL
};
struct label {
private:
int index;
int rank;
label *parent;
public:
label ()
: index(-1), rank(0), parent(this)
{ }
int getIndex(int &maxIndex) {
if (parent != this)
return find()->getIndex(maxIndex);
if (index < 0)
index = maxIndex++;
return index;
}
label *find() {
if (parent == this)
return this;
parent = parent->find();
return parent;
}
label *merge(label *other)
{
label *xRoot = find();
label *yRoot = other->find();
if (xRoot == yRoot)
return xRoot;
if (xRoot->rank > yRoot->rank) {
yRoot->parent = xRoot;
return xRoot;
} else {
xRoot->parent = yRoot;
if (xRoot->rank == yRoot->rank)
yRoot->rank++;
return yRoot;
}
}
};
int width, height;
int main() {
for (int i = 0; data[0][i]; i++)
width = i + 1;
for (int i = 0; data[i]; i++) {
height = i + 1;
}
std::vector<std::vector<unsigned short> > lblinfo;
lblinfo.resize(height, std::vector<unsigned short>(width, 0));
std::vector<label *> labels;
labels.push_back(NULL); // 0 is used as an unassigned flag
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (data[y][x] == '1')
continue;
// Try to find a neighboring label
unsigned short lblid = 0;
if (x != 0 && lblinfo[y][x-1] != 0)
lblid = lblinfo[y][x-1];
// merge with cells above
if (y != 0) {
for (int x2 = x - 1; x2 <= x + 1; x2++) {
if (x2 < 0)
continue;
if (x2 >= width)
continue;
unsigned short otherid = lblinfo[y - 1][x2];
if (!otherid)
continue;
if (!lblid)
lblid = otherid;
else {
labels[lblid]->merge(labels[otherid]);
}
}
}
if (!lblid) {
// assign a new label
lblid = labels.size();
labels.push_back(new label);
}
lblinfo[y][x] = lblid;
}
}
// Assign indices to the labels by set and print the resulting sets
int maxindex = 0;
static const char chars[] = "abcefghijklmnopqrstuvwxyz";
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
unsigned short labelid = lblinfo[y][x];
if (labelid == 0) {
putchar(data[y][x]);
continue;
}
label *label = labels[labelid];
int idx = label->getIndex(maxindex);
if (idx >= sizeof(chars) - 1) {
printf("\n\n Too many labels to print!\n");
exit(1);
}
putchar(chars[idx]);
}
printf("\n");
}
return 0;
}