• 0

[algorithms] Two problems


Question

Hello, I am reading Mark Allen Weiss' Data Structures and Algorithm Analysis in Java, 2nd edition, and I can't seem to be able to resolve the most simple problems. This is the manual for my course on algorithms, but the problems aren't assignements per say.

Problem 1.3 :

Write a method to output an arbitrary double number (which might be negative) using only printDigit for I/O.

printDigit is not in the Java standard, it's defined a few pages before as "will take a single-digit number and output it to the terminal", but I have to implement it myself.

So in other words, I have to output an arbitrary double one digit at a time, in decimal representation. Now, with a positive integer I can just do :

public class Exercice3 {

	public static void main(String[] args) {
		printOut(1329);
	}

	// Recursive method that prints a positive integer one character at a time
	public static void printOut(int n) {
		if (n>= 10) {
			printOut(n / 10);
		}
		printDigit(n % 10);
	}

	public static void printDigit(int n) {
		if (0 <= n && n <= 9) {
			System.out.print(n);
		}
	}
}

However, for the double, what should be the base case, in other words : where does the recursion stop ? The number can have any number of decimals after 0.

***********************

Problem 1.4 :

C allows statement of the form

#include filename

which reads filename and inserts its contents in place of the include statement. Include statements may be nested; in other words, the file filename may itself contain an include statement, but, obviously, a file can't include itself in any chain. Write a program that reads in a file and outputs the file as modified by the include statements.

I simply don't understand the question. How can include statements modify a file that I am able to output within the program ? Should the program be written in C (wtf, it's a Java book) ?

Thanks for any help

Edited by Dr_Asik
Link to comment
https://www.neowin.net/forum/topic/721948-algorithms-two-problems/
Share on other sites

3 answers to this question

Recommended Posts

  • 0
Problem 1.4 :

C allows statement of the form

#include filename

which reads filename and inserts its contents in place of the include statement. Include statements may be nested; in other words, the file filename may itself contain an include statement, but, obviously, a file can't include itself in any chain. Write a program that reads in a file and outputs the file as modified by the include statements.

I simply don't understand the question. How can include statements modify a file that I am able to output within the program ? Should the program be written in C (wtf, it's a Java book) ?

I think this is what it's telling you to do:

Write a program which parses any file for #include statements, and replaces the include statement with the contents of the file it imports. Because the files being imported probably also contain #include statements, scan all imported files for #include statements and so forth. Output the modifications to a new file.

The thing about the chains, what this means is that the same file can be imported twice, causing the program to go into an infinite loop.

  • 0

Thanks. Unfortunately I would have to take into account preprocessor directives to avoid including file multiple time and cyclic dependencies (#ifndef _myclass_h #include ... #endif), and it would be a pain. Ok ok it's recursive, I get it. ;)

I still can't do the double displaying thingy though.

Number 5 is easy though :

Write a recursive method that returns the number of 1's in the binary representation of N.

Answer :

	int numberOfOnes(int N) {
		if (N > 1) {
			return numberOfOnes(N / 2) + (N%2==0? 0:1);
		}
		return N;
	}

  • 0

edit: opps... I just read you know the answer already...

Re: Problem 1.4 - I think this is what it is saying.

Master.txt file - non java - your java program process it

#include a.txt;
#include b.txt;
#include c.txt;

a.txt

Hi

b.txt

How

c.txt

Are

run java program on master.txt - program outputs master.out.txt file

master.out.txt

Hi
How
Are

get it???? your java program reads imports and makes a file that joins all the contents of the include files...

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • well you can add a GPU for around $500, that's still around the price of Steam Machine but overall significantly better in performance.
    • Fresh CachyOS install with Niri - I guess it's a little orange, but I'm working on it
    • FastStone Image Viewer 8.5 by Razvan Serea FastStone Image Viewer is a fast, stable, user-friendly image browser, converter and editor. It has a nice array of features that include image viewing, management, comparison, red-eye removal, emailing, resizing, cropping, retouching and color adjustments. Its innovative but intuitive full-screen mode provides quick access to EXIF information, thumbnail browser and major functionalities via hidden toolbars that pop up when your mouse touches the four edges of the screen. Other features include a high quality magnifier and a musical slideshow with 150+ transitional effects, as well as lossless JPEG transitions, drop shadow effects, image annotation, scanner support, histogram and much more. It supports all major graphic formats (BMP, JPEG, JPEG 2000, animated GIF, PNG, PCX, PSD, EPS, TIFF, WMF, ICO and TGA) and popular digital camera RAW formats (CRW, CR2, NEF, PEF, RAF, MRW, ORF, SRF, ARW, SR2, RW2 and DNG). FastStone Image Viewer features: Image browser and viewer with a familiar Windows Explorer-like user interface Support for many popular image formats and PDF viewing True Full Screen viewer with convenient image zoom support and unique fly-out menu panels Crystal-clear and customizable one-click image magnifier Powerful image editing tools: Resize/resample, rotate/flip, crop, sharpen/blur, adjust lighting/colors/curves/levels etc. Eleven re-sampling algorithms to choose from when resizing images Image color effects: gray scale, sepia, negative, Red/Green/Blue adjustment Image special effects: drop shadow, framing, bump map, sketch, oil painting, lens Draw texts, lines, highlights, rectangles, ovals and callout objects on images Clone Stamp and Healing Brush Superior red-eye effect removal/reduction with completely natural looking end result Multi-level Undo/Redo capability Single click to switch between best fit and actual size mode Image management, including file tagging, rating and drag-and-drop to copy/move/re-arrange files Histogram display with color counter feature Compare images side-by-side (up to 4 at a time) to easily cull those forgettable shots Image EXIF metadata support (plus comment editing for JPEGs) Configurable batch processing to convert/rename large or small collections of images Slideshow with 150+ transition effects and music support (MP3, WMA, WAV...) Create efficient image attachments for emailing to family and friends Print images with full page-layout control Create fully configurable contact sheets Create memorable artistic image montages from your family photos for personalized desktop wallpapers (Wallpaper Anywhere) Acquire images from scanners. Support batch scanning to PDF, TIFF, JPEG and PNG Versatile screen capture capability Powerful Save As interface to compare image quality and control generated file size Run favorite external editors with one keystroke from within Image Viewer Offer portable version of the program which can be run from a removable storage device Configurable mouse wheel support Support themes (bright, gray and dark) Support dual-monitor configurations Support touch interface (tap, swipe, pinch) Support dual instances Play video and audio files (Third party codecs may be required for old versions of Windows) And much more... FastStone Image Viewer 8.5 changelog: Added support for SVG format Added Start importing automatically and Handle duplicate file names automatically options to the Import Photos and Videos tool WebP files can now be rotated and saved with a single click Enhanced dark theme support in the PDF viewer Fixed a bug where some links in PDF files were not clickable Other improvements and bug fixes Download: FastStone Image Viewer 8.5 | Portable | ~15.0 MB (Freeware) View: FastStone Image Viewer Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Rookie
      DaviKar went up a rank
      Rookie
    • Dedicated
      HidekoYamamoto94 earned a badge
      Dedicated
    • One Month Later
      timbobit earned a badge
      One Month Later
    • One Month Later
      nates earned a badge
      One Month Later
    • Week One Done
      Almohandis earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      461
    2. 2
      +Edouard
      160
    3. 3
      PsYcHoKiLLa
      110
    4. 4
      Michael Scrip
      85
    5. 5
      Steven P.
      69
  • Tell a friend

    Love Neowin? Tell a friend!