Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,152,942 members, 7,817,767 topics. Date: Saturday, 04 May 2024 at 06:59 PM

Coding Challenge 6: Working With Arrays - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / Coding Challenge 6: Working With Arrays (1395 Views)

Mini Web Application Coding Challenge For Programmers / Java Coding Challenge: Task Scheduler / Coding Challenge 5: Substring Generator (2) (3) (4)

(1) (Reply) (Go Down)

Coding Challenge 6: Working With Arrays by Fayimora(m): 8:22pm On Jul 16, 2011
Write a static method which takes an array of integers and an integer (the “target”) and returns the integer in the array which is closest to the target.
Let array be {19, 9, 30, 47, 5, 10, 20, 36, 21, 11, 13}
So if the target is 25 and the array is the method should return 21.

A lil bit intermediate: Please only attempt if you have gotten the one above,
Write one method that does this constructively and another that does it destructively
Re: Coding Challenge 6: Working With Arrays by naijaswag1: 10:51pm On Jul 16, 2011
I donno what you mean by constructively and destructively(I guess I have to check those out later);I decided to fine tune my algorithm skills,am at the beginning of a book and still doing arrays and I used a HighArray class I added a getMax method,HighArray and TksiliconArrayApp below solves the problem

public class TksliliconArrayApp {

static int targetInteger(int[] arr,int target){
HighArray hr = new HighArray(arr.length);
for(int i=0;i<arr.length;i++){
if(arr[i]< target) {  
  hr.insert(arr[i]);
}
}
return hr.getMax();
}
public static void main(String[] args){

int[] fayimoraArray = {1, 9, 30, 47, 5, 10, 20, 36, 21, 11, 13};
int toUse = 25;
int targetInteger = targetInteger(fayimoraArray,toUse);
System.out.println("The nearest integer to " + toUse + " is " + targetInteger );

}

}

package arrays;

public class HighArray {
private int[] a; // ref to array a
private int nElems; // number of data items
//-----------------------------------------------------------
public HighArray(int max) {// constructor

a = new int[max]; // create the array
nElems = 0; // no items yet
}
public void insert(int value){ // put element into array

a[nElems] = value; // insert it
nElems++; // increment size
}

//added by tksilicon
public int getMax(){
if(a.length == 0)
return new Integer(-1);

int j = 0;
int max = a[j];
for(j=1;j<nElems;j++){
if(a[j] > max)
max = a[j];
}
return new Integer(max);

}

}
Re: Coding Challenge 6: Working With Arrays by Fayimora(m): 12:59am On Jul 17, 2011
Constructively - dont change the initial object;
Destructively - you can destroy and rebuild the initial object;

by object here am referring to the array,

Also theres a lot of redundancies in ur code, You are supposed to just supply a method that takes an array and number as parameters. Nothing more!
Re: Coding Challenge 6: Working With Arrays by tundebabzy: 1:20am On Jul 17, 2011
Python doesn't have arrays. Python's similar data structure is called Lists and the difference is that objects of different kinds can be stored in one list.

In python, a static method can be created easily by using the "staticmethod" decorator so that a method - static() in a class - F can be called without instantiating the class like this: F.static()

Anyway this is my solution:
destructive (and by far fastest:

class C:
    @staticmethod
    def load_shed(l, num):
        """
        C.load_shed([3,4,5,6,7],7) ----> 6
        This function takes a list and an integer and returns the number closest
        to the given number.
        """
       
        l = sorted(l)   #sort ascending to make things easier
        cache = l
        for count in range(len(l)):
            size = len(cache)   #needed so the list can be divided into 2
            up = cache[sadsize/2)] # The first half of the list
            down = cache[size/2:]   #The second half of the list
           
            # If the highest num in up is less than the least num in down
            # and if the least num in down is greater than the given int,
            if max(up) < min(down) and min(down) >= num:
                return max(up)
           
            elif max(up) > num:
                cache = up      # Shed the 2nd half of the list
               
            else:
                cache = down    # Shed the 1st half of the list


For the constructive (very inefficient because it loops through the whole list):

class C:
    """
    C.load_shed_d(3,4,5,6,7],7)------>6
    This function takes a list and an integer and returns the number closest
    to the given number.
    """
   
    @staticmethod   
    def load_shed_d(l, num):
        highest = 0
        for x in range(len(l)):
            if l[x] > highest and l[x] < num:
                highest = l[x]

        return highest
Re: Coding Challenge 6: Working With Arrays by naijaswag1: 4:14am On Jul 17, 2011
Fayimora:

Constructively - dont change the initial object;
Destructively - you can destroy and rebuild the initial object;

by object here am referring to the array,

Also theres a lot of redundancies in your code,  You are supposed to just supply a method that takes an array and number as parameters. Nothing more!
Since I started reading programming books last year,one of the cardinal things I have read many authors emphasize over and over is to get the problem solved before looking for elegant solutions.And they are absolutely right, you want a problem solved,you have to get a solution that works first before beautifying and trying to make your code work fast.What I posted solves the problem,you can now analyze it to know whether it is doing the second part of what you wanted.

This is one of the reasons I tend to shun Nairaland coding challenges.In the first place,does the code solve the problem? If yes,algorithmically and conciseness comes second.

I remember having issues with you about assisting others not telling them psuedocode that will do them no good.I am not even posting anymore and I will not participate in future ones,I have better things to do.
Re: Coding Challenge 6: Working With Arrays by Nobody: 5:16am On Jul 17, 2011
Re: Coding Challenge 6: Working With Arrays by tundebabzy: 7:27am On Jul 17, 2011
Nairaland has to train its spambot. It kicked me out again yesterday. And at least nairaland could give a helpful less annoying reason instead of 'reason: you were blocked by anti-spam bot, '

Anyway, My solution using python. First of all, python does not have arrays. Its data structure similar to arrays is Lists and the difference is that objects of different types including other types of data structures can be stored in a single lists.
Also, python allows you to create static methods by using the 'staticmethod' decorator.

I've commented my code so it should be easy to understand

Constructive (extremely inefficient and has the potential to run for ages):

class C:
@staticmethod
def load_shed_d(l, num):
"""
C.load_shed_d(3,4,5,6,7],7)------>6
This function takes a list and an integer and returns the number closest
to the given number.
"""

highest = 0
for x in range(len(l)):
if l[x] > highest and l[x] < num:
highest = l[x]

return highest

since its a static method, you can run thus: C.load_shed_d(list, int). With the example given it runs in 0.0 second

For the efficient (destructive) solution:

class C:
@staticmethod
def load_shed(l, num):
"""
C.load_shed([3,4,5,6,7],7) ----> 6
This function takes a list and an integer and returns the number closest
to the given number.
"""

l = sorted(l) #sort ascending to make things easier
cache = l
for count in range(len(l)):
size = len(cache) #needed so the list can be divided into 2
up = cache[sadsize/2)] # The first half of the list
down = cache[size/2:] #The second half of the list

# If the highest num in up is less than the least num in down
# and if the least num in down is greater than the given int,
if max(up) < min(down) and min(down) >= num:
return max(up)

elif max(up) > num:
cache = up # Shed the 2nd half of the list

else:
cache = down # Shed the 1st half of the list

With the example given runs in 0.0 seconds


omo_to_dun:

but I want a community where we can help one another to become better programmers, not better copy and paste geniuses. And yes, naija_swag, NL needs your expertise. Please, come back.
+1
Re: Coding Challenge 6: Working With Arrays by KoolPitt(m): 9:23am On Jul 17, 2011
I think this should be on the constructive side.

private static int GetClosest(int[] array, int target)
{
ArrayList difference = new ArrayList();
for (int i = 0; i < array.Length; i++)
{
difference.Add(Math.Abs(array[i] - target));
}

return array[difference.IndexOf(difference.ToArray().Min())];
}
Re: Coding Challenge 6: Working With Arrays by Fayimora(m): 12:01pm On Jul 17, 2011
@naija_swag. Just like omo_to_dun said I wasn't looking for a working solution.  The question specifically said 1 method and if you don't supply one method then you havent answered the question.

Here is a possible solution:Its done destructively so would still leave the constructive part to anyone.
static int closestNum(int[] numbers, int target)
{
int currentClosest=numbers[0];
int lowest = Math.abs(target - currentClosest);

for(int i=1; i<numbers.length; i++)
{
int difference = Math.abs(target - numbers[i]);
if(difference == 0)
return numbers[i];
if(difference < lowest){
currentClosest = numbers[i];
lowest = difference;
}
}
return currentClosest;
}
Re: Coding Challenge 6: Working With Arrays by Fayimora(m): 12:02pm On Jul 17, 2011
KoolPitt:

I think this should be on the constructive side.

private static int GetClosest(int[] array, int target)
{
ArrayList difference = new ArrayList();
for (int i = 0; i < array.Length; i++)
{
difference.Add(Math.Abs(array[i] - target));
}

return array[difference.IndexOf(difference.ToArray().Min())];
}
Don't know if this works(havent tested) but the question says using arrays cheesy. An ArrayList wouldn't be appropriate here,
Re: Coding Challenge 6: Working With Arrays by tundebabzy: 12:59pm On Jul 17, 2011
can someone explain to me how to avoid being blocked by nairaland's s.t.u.p.i.d. bot
Re: Coding Challenge 6: Working With Arrays by Nobody: 3:54pm On Jul 17, 2011
Re: Coding Challenge 6: Working With Arrays by candylips(m): 2:35pm On Jul 18, 2011
Constructively

private static int findTheNearest(int[] arrays, int target)
{
int nearest = Integer.MAX_VALUE;
int lowestDifference = Integer.MAX_VALUE;
for (int i = 0; i < arrays.length; i++)
{
int difference = Math.abs(arrays[i] - target);
if (difference < lowestDifference)
{
nearest = arrays[i];
lowestDifference = difference;
}
}
return nearest;
}
Re: Coding Challenge 6: Working With Arrays by Fayimora(m): 2:44pm On Jul 18, 2011
dats destructive, jst as mine above is cheesy. To have a constructive solution, then the object should be messed with
Re: Coding Challenge 6: Working With Arrays by candylips(m): 3:54pm On Jul 18, 2011
.
Re: Coding Challenge 6: Working With Arrays by solomon201(m): 4:55pm On Jul 18, 2011
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Cha
{
class Program
{
static int absolute(int n)
{
if(n<0)
return ((n+(n*-2)));
else return n;
}

static int FindNearest(int[] n, int target)
{
int nearest=target;
int initial = absolute(n[0] - target);
foreach (int x in n)
if (absolute(x - target) < initial)
nearest = x;
return nearest;
}




static void Main(string[] args)
{
int[] numbers = { 19, 9, 30, 47, 5, 10, 20, 36, 21, 11, 13 };
int answer = FindNearest(numbers, 25);
Console.WriteLine(answer);
}
}
}
Re: Coding Challenge 6: Working With Arrays by tundebabzy: 7:49pm On Jul 18, 2011
omo_to_dun:

Try posting your code without using the code command. It stopped banning me when I did that. This is the freaking programming section, the bot shouldn't be acting this dumb.
My posts that initially got me banned have shown up on the thread:-
tundebabzy:

Nairaland has to train its spambot. It kicked me out again yesterday. And at least nairaland could give a helpful less annoying reason instead of 'reason: you were blocked by anti-spam bot, '

Anyway, My solution using python. First of all, python does not have arrays. Its data structure similar to arrays is Lists and the difference is that objects of different types including other types of data structures can be stored in a single lists.
Also, python allows you to create static methods by using the 'staticmethod' decorator.

I've commented my code so it should be easy to understand

Constructive (extremely inefficient and has the potential to run for ages):

class C:
@staticmethod
def load_shed_d(l, num):
"""
C.load_shed_d(3,4,5,6,7],7)------>6
This function takes a list and an integer and returns the number closest
to the given number.
"""

highest = 0
for x in range(len(l)):
if l[x] > highest and l[x] < num:
highest = l[x]

return highest

since its a static method, you can run thus: C.load_shed_d(list, int). With the example given it runs in 0.0 second

For the efficient (destructive) solution:

class C:
@staticmethod
def load_shed(l, num):
"""
C.load_shed([3,4,5,6,7],7) ----> 6
This function takes a list and an integer and returns the number closest
to the given number.
"""

l = sorted(l) #sort ascending to make things easier
cache = l
for count in range(len(l)):
size = len(cache) #needed so the list can be divided into 2
up = cache[sadsize/2)] # The first half of the list
down = cache[size/2:] #The second half of the list

# If the highest num in up is less than the least num in down
# and if the least num in down is greater than the given int,
if max(up) < min(down) and min(down) >= num:
return max(up)

elif max(up) > num:
cache = up # Shed the 2nd half of the list

else:
cache = down # Shed the 1st half of the list

With the example given runs in 0.0 seconds

+1

, maybe dumb-bot got a query
Re: Coding Challenge 6: Working With Arrays by tundebabzy: 8:15pm On Jul 18, 2011
Fayimora:

@naija_swag. Just like omo_to_dun said I wasn't looking for a working solution.  The question specifically said 1 method and if you don't supply one method then you havent answered the question.

Here is a possible solution:Its done destructively so would still leave the constructive part to anyone.
static int closestNum(int[] numbers, int target)
{
int currentClosest=numbers[0];
int lowest = Math.abs(target - currentClosest);

for(int i=1; i<numbers.length; i++)
{
int difference = Math.abs(target - numbers[i]);
if(difference == 0)
return numbers[i];
if(difference < lowest){
currentClosest = numbers[i];
lowest = difference;
}
}
return currentClosest;
}



Guys, please a little education for me. A destructive method is one that alters the attributes of a given object. In the challenge, the particular object was not given so I assumed the destructive method should alter the array object given as the argument. If that's true then the above method (function) is not destructive since the initial object for the function is the array object supplied as an argument. The int (int target) is a literal which in java isn't an object (if I remember my java right).
Re: Coding Challenge 6: Working With Arrays by Fayimora(m): 11:58pm On Jul 18, 2011
A destructive method changes the object. As i said, in this case let the object be the array. This example might be a little bit difficult explaining by typing down words so i would use an easier one. [b]Consider writing a method that returns an array in which each element is `n` times the corresponding element in the array that was passed.[/b]So lets write 2 methods, one to do it destructively and another to do it constructively.

A constructive way
static int[] getAfterC(int[] numbers, int n)
{
int[] b = new int[numbers.length];
for(int i=0; i<b.length; i++)
b[i] = numbers[i]*n;
return b;
}

What makes this constructive? I have not altered anything in the array "numbers".  What happens if you call this method 10 times? Find out!

A destructive way:
static int[] getAfterD(int[] numbers, int n)
{
for(int i=0; i<numbers.length; i++)
numbers[i] = numbers[i]*n;
return numbers;
}

In this case we have altered the array 'numbers'. What happens if you call this method 10 times? Find out!

On a final note, are arrays passed by value or reference? cheesy
Re: Coding Challenge 6: Working With Arrays by tundebabzy: 8:46am On Jul 19, 2011
The way arrays are passed is language dependent. In python, all objects are passed by reference, in java arrays are passed by reference. In C# you can either pass arrays by reference or by value. And I know you can't have a destructive method from objects passed by value.

To make this easier, just tell me which line in the closestNum() code alters the object - the numbers array. That way I can figure out what I have been missing.

(1) (Reply)

Pagination / Facebook Launches Techprep: ‘there Will Be Over 1M Programming Jobs By 2020’ / Wants To Deploy A Codeigniter Project Live

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 57
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.