落書きノート

ふと自分が気になった事を書いてます

C言語でアルゴリズムとデータ構造その2 前記事の修正版

考えるプログラムの問題は、結構穴が出来ますね。寝ながら考えているとそう思います。チェック漏れがあったので、ソースコードを修正しました。

新・明解C言語によるアルゴリズムとデータ構造

新・明解C言語によるアルゴリズムとデータ構造

// q3_9

#include <stdio.h>
#include <stdlib.h>

int int_cmpr(const int *a, const int *b) {
  if(*a < *b)
    return -1;
  else if(*a > *b)
    return 1;
  else
    return 0;
}

int *search(int *x, int *p, int n) {
  int i = n - 1;
  int key = x[n];
  int *answer = p;
  while(1) {
    if(i == -1)
      break;
    if(x[i] == key)
      answer = x + i;
    i--;
  }
  return answer;
}

void *bsearchx(const void *key, const void *base, size_t nmemb,
                size_t size, int (*compar)(const void *, const void *)) {
  int pl = 0;
  int pr = nmemb - 1;
  int pc;
  
  do {
    pc = (pl + pr) / 2;
    if(compar(base + pc * size, key) == 0)
      return (void *)base + pc * size;
    else if(compar(base + pc * size, key) == 1)
      pl = pc + 1;
    else
      pr = pc - 1;
  } while (pl <= pr);
  
  return NULL;
}

int main(void) {
  int i, nx, ky;
  int *x, *p;

  puts("bsearch関数による探索");
  printf("要素数 : ");
  scanf("%d", &nx);
  x = calloc(nx, sizeof(int));
  printf("降順に入力してください。\n");
  printf("x[0] : ");
  scanf("%d", &x[0]);
  
  for(i = 1; i < nx; i++) {
    do {
      printf("x[%d] : ", i);
      scanf("%d", &x[i]);
    } while (x[i] > x[i - 1]);
  }
  
  printf("探す値 : ");
  scanf("%d", &ky);
  
  p = bsearchx(&ky,
                x,
                nx,
                sizeof(int),
                (int (*)(const void *, const void *))int_cmpr
                );
  
  if(p == NULL)
    puts("探索に失敗しました。");
  else {
    p = search(x, p, (int)(p - x));
    printf("%dはx[%d]にあります。\n", ky, (int)(p - x));
  }
  free(x);
  
  return 0;
}

C言語でアルゴリズムとデータ構造

今日はプログラミングが捗りました。Go言語とCrystal言語。ところで今日の最後にこの本の問題を解いてます。久しぶりにやりました。二分探索法と線形探索法を使った問題です。世界で闘うプログラミング力を鍛える本、いつやるんでしょうかね。自分でも思います。

新・明解C言語によるアルゴリズムとデータ構造

新・明解C言語によるアルゴリズムとデータ構造

// q3_8

#include <stdio.h>
#include <stdlib.h>

int int_cmpr(const int *a, const int *b) {
  if(*a < *b)
    return -1;
  else if(*a > *b)
    return 1;
  else
    return 0;
}

void *binsearch(const void *key, const void *base, size_t nmemb,
                size_t size, int (*compar)(const void *, const void *)) {
  int pl = 0;
  int pr = nmemb - 1;
  int pc;

  do {
    pc = (pl + pr) / 2;
    if(compar(base + pc * size, key) == 0)
      return (void *)base + pc * size;
    else if(compar(base + pc * size, key) == 1)
      pl = pc + 1;
    else
      pr = pc - 1;
  } while (pl <= pr);

  return NULL;
}

int main(void) {
  int i, nx, ky;
  int *x, *p;

  puts("bsearch関数による探索");
  printf("要素数 : ");
  scanf("%d", &nx);
  x = calloc(nx, sizeof(int));
  printf("降順に入力してください。\n");
  printf("x[0] : ");
  scanf("%d", &x[0]);
  
  for(i = 1; i < nx; i++) {
    do {
      printf("x[%d] : ", i);
      scanf("%d", &x[i]);
    } while (x[i] > x[i - 1]);
  }
  
  printf("探す値 : ");
  scanf("%d", &ky);
  
  p = binsearch(&ky,
                x,
                nx,
                sizeof(int),
                (int (*)(const void *, const void *))int_cmpr
                );
  
  if(p == NULL)
    puts("探索に失敗しました。");
  else
    printf("%dはx[%d]にあります。\n", ky, (int)(p - x));
  free(x);
  
  return 0;
}

// q3_9

#include <stdio.h>
#include <stdlib.h>

int int_cmpr(const int *a, const int *b) {
  if(*a < *b)
    return -1;
  else if(*a > *b)
    return 1;
  else
    return 0;
}

int *search(int *x, int *p, int n) {
  int i = n - 1;
  int key = x[n];
  while(1) {
    if(i == -1)
      return p;
    if(x[i] == key)
      return x + i;
    i--;
  }
}

void *bsearchx(const void *key, const void *base, size_t nmemb,
                size_t size, int (*compar)(const void *, const void *)) {
  int pl = 0;
  int pr = nmemb - 1;
  int pc;
  
  do {
    pc = (pl + pr) / 2;
    if(compar(base + pc * size, key) == 0)
      return (void *)base + pc * size;
    else if(compar(base + pc * size, key) == 1)
      pl = pc + 1;
    else
      pr = pc - 1;
  } while (pl <= pr);
  
  return NULL;
}

int main(void) {
  int i, nx, ky;
  int *x, *p;

  puts("bsearch関数による探索");
  printf("要素数 : ");
  scanf("%d", &nx);
  x = calloc(nx, sizeof(int));
  printf("降順に入力してください。\n");
  printf("x[0] : ");
  scanf("%d", &x[0]);
  
  for(i = 1; i < nx; i++) {
    do {
      printf("x[%d] : ", i);
      scanf("%d", &x[i]);
    } while (x[i] > x[i - 1]);
  }
  
  printf("探す値 : ");
  scanf("%d", &ky);
  
  p = bsearchx(&ky,
                x,
                nx,
                sizeof(int),
                (int (*)(const void *, const void *))int_cmpr
                );
  
  if(p == NULL)
    puts("探索に失敗しました。");
  else {
    p = search(x, p, (int)(p - x));
    printf("%dはx[%d]にあります。\n", ky, (int)(p - x));
  }
  free(x);
  
  return 0;
}

現在のEmacsの設定

Linux,macOS,Windowsのこの3つのOSなら全部これ一つで動かせるようにしました。フォントもmacOSのフォントに統一しようかと。GentooではNoto Sansをよく使っているのですが、やっぱりmacOSのフォントの方がいいですよね。Linux,WindowsEmacsでは今のところInconsolataを使っている状態ですが、また追々変えて試してみます。Sierraに同梱されているSF Mono Regularも気に入りました。フルネームはSan Francisco Monoという名前らしいです。Menloと同じように使えます。SF MonoかMenloどちらに統一しよう…。

;; Added by Package.el.  This must come before configurations of
;; installed packages.  Don't delete this line.  If you don't want it,
;; just comment it out by adding a semicolon to the start of the line.
;; You may delete these explanatory comments.

;; Added by Package.el.  This must come before configurations of
;; installed packages.  Don't delete this line.  If you don't want it,
;; just comment it out by adding a semicolon to the start of the line.
;; You may delete these explanatory comments.

(when (equal system-type 'darwin)
  
  ;; CUI settings

  (if (not window-system) (progn
                            (global-linum-mode t)
                            ))

  ;; GUI settings

  (if window-system (progn
                      
                      (defun add-to-load-path (&rest paths)
                        (let (path)
                          (dolist (path paths paths)
                            (let ((default-directory (expand-file-name (concat user-emacs-directory path))))
                              (add-to-list 'load-path default-directory)
                              (if (fboundp 'normal-top-level-add-subdirs-to-load-path)
                                  (normal-top-level-add-subdirs-to-load-path))))))

                      (add-to-load-path "original")

                      (require 'package)
                      (add-to-list 'package-archives '("melpa-stable" . "http://stable.melpa.org/packages/"))
                      (add-to-list 'package-archives '("melpa" . "http://melpa.milkbox.net/packages/"))
                      (add-to-list 'package-archives '("marmalade" . "http://marmalade-repo.org/packages/"))
                      (add-to-list 'package-archives '("org" . "http://orgmode.org/elpa/"))
                      (add-to-list 'package-archives '("gnu" . "http://elpa.gnu.org/packages/"))
                      (package-initialize)

                      (require 'color-theme)
                      (color-theme-initialize)
                      (color-theme-midnight)

                      (progn
                        (set-face-foreground 'mode-line "white")
                        (set-face-background 'mode-line "#0000cd")
                        (set-face-background 'region "white")
                        )

                      (require 'tabbar)
                      (tabbar-mode)
                      (setq tabbar-mwheel-mode nil)
                      (setq tabbar-buffer-groups-function nil)
                      (set-face-attribute 'tabbar-default nil :background "#a3ffa3" :foreground "#696969" :family "Menlo")
                      (set-face-attribute 'tabbar-selected nil :background "#00ff00" :foreground "black" :box nil)
                      (set-face-attribute 'tabbar-modified nil :background "#a3ffa3" :foreground "#696969" :box nil)
                      
                      ;; (set-face-attribute 'default nil :family "Menlo" :height 120)

                      ;; (custom-set-faces
                      ;;  '(default ((t (:inherit autoface-default :height 120 :family "Menlo"))) t))

                      (setq x-select-enable-clipboard nil)
                      (setq save-interprogram-paste-before-kill nil)
                      (setq yank-pop-change-selection nil)
                      (setq x-select-enable-clipboard-manager nil)
                      (setq x-select-enable-primary t)
                      (setq mouse-drag-copy-region t)

                      (defun copy-from-osx ()
                        (shell-command-to-string "pbpaste"))

                      (defun paste-to-osx (text &optional push)
                        (let ((process-connection-type nil))
                          (let ((proc (start-process "pbcopy" "*Messages*" "pbcopy")))
                            (process-send-string proc text)
                            (process-send-eof proc))))

                      (setq interprogram-cut-function 'paste-to-osx)
                      (setq interprogram-paste-function 'copy-from-osx)

                      (define-key global-map (kbd "C-x C-c") 'clipboard-kill-ring-save)
                      (define-key global-map (kbd "C-x C-x") 'clipboard-kill-region)
                      (define-key global-map (kbd "C-x C-k") 'kill-line)
                      (define-key global-map (kbd "C-x C-s") 'save-buffer)
                      (define-key global-map (kbd "C-x C-a") 'mark-whole-buffer)
                      (define-key global-map (kbd "C-x C-v") 'clipboard-yank)
                      (define-key global-map (kbd "C-x C-z") 'undo)
                      (define-key global-map (kbd "C-s") 'isearch-forward)

                      (tool-bar-mode 0)

                      (global-set-key [f1] 'neotree-toggle)
                      (setq neo-show-hidden-files t)
                      (setq neo-create-file-auto-open t)
                      (setq neo-persist-show t)
                      (setq neo-keymap-style 'concise)
                      (setq neo-smart-open t)
                      (setq neo-vc-integration '(face char))
                      (when neo-persist-show
                        (add-hook 'popwin:before-popup-hook
                                  (lambda () (setq neo-persist-show nil)))
                        (add-hook 'popwin:after-popup-hook
                                  (lambda () (setq neo-persist-show t))))

                      (prefer-coding-system 'utf-8)

                      (setq make-backup-files nil)

                      (setq delete-auto-save-files t)

                      (setq-default tab-width 4 indent-tabs-mode nil)

                      (setq eol-mnemonic-dos "(CRLF)")
                      (setq eol-mnemonic-mac "(CR)")
                      (setq eol-mnemonic-unix "(LF)")

                      (add-to-list 'default-frame-alist '(alpha . (0.85 0.85)))

                      (column-number-mode t)

                      (global-linum-mode t)

                      (blink-cursor-mode 0)

                      (global-hl-line-mode t)

                      (show-paren-mode 1)
                      (setq show-paren-style 'expression)

                      (global-whitespace-mode 1)
                      (setq whitespace-space-regexp "\x3000+")
                      (set-face-foreground 'whitespace-newline "gray40")

                      (require 'cl)
                      (dolist (d '((space-mark ?\ ) (newline-mark ?\n)))
                        (setq whitespace-display-mappings
                              (delete-if
                               '(lambda (e) (and (eq (car d) (car e))
                                                 (eq (cadr d) (cadr e))))
                               whitespace-display-mappings)))

                      (dolist (e '((space-mark   ?\x3000 [?\□])
                                   (newline-mark ?\n     [?\u21B5 ?\n] [?$ ?\n])))
                        (add-to-list 'whitespace-display-mappings e))

                      (dolist (d '(face lines space-before-tab
                                        indentation empty space-after-tab tab-mark))
                        (setq whitespace-style (delq d whitespace-style)))

                      (setq scroll-conservatively 1)

                      (setq kill-whole-line t)

                      (require 'dired-x)

                      (defun my-bell-function ()
                        (unless (memq this-command
                                      '(isearch-abort abort-recursive-edit exit-minibuffer
                                                      keyboard-quit mwheel-scroll down up next-line previous-line
                                                      backward-char forward-char))
                          (ding)))
                      (setq ring-bell-function 'my-bell-function)

                      (custom-set-variables
                       ;; custom-set-variables was added by Custom.
                       ;; If you edit it by hand, you could mess it up, so be careful.
                       ;; Your init file should contain only one such instance.
                       ;; If there is more than one, they won't work right.
                       '(package-selected-packages
                         (quote
                          (go-mode haskell-mode tabbar-ruler tabbar tuareg neotree color-theme))))
                      (custom-set-faces
                       ;; custom-set-faces was added by Custom.
                       ;; If you edit it by hand, you could mess it up, so be careful.
                       ;; Your init file should contain only one such instance.
                       ;; If there is more than one, they won't work right.
                       )

                      (add-to-list 'auto-mode-alist '("\\.ml[iylp]?" . tuareg-mode))
                      (autoload 'tuareg-mode "tuareg" "Major mode for editing OCaml code" t)
                      (autoload 'tuareg-run-ocaml "tuareg" "Run an inferior OCaml process." t)
                      (autoload 'ocamldebug "ocamldebug" "Run the OCaml debugger" t)

                      ;; crystal-mode
                      (autoload 'crystal-mode "crystal-mode" "Major mode for crystal files" t)
                      (add-to-list 'auto-mode-alist '("\\.cr$" . crystal-mode))
                      (add-to-list 'interpreter-mode-alist '("crystal" . crystal-mode))

                      ))
  )

(when (equal system-type 'gnu/linux)
  (package-initialize)
  (setq package-archives
        '(("gnu" . "http://elpa.gnu.org/packages/")
          ("melpa" . "http://melpa.org/packages/")
          ("org" . "http://orgmode.org/elpa/")))

  (add-to-list 'auto-mode-alist '("\\.ml[iylp]?" . tuareg-mode))
  (autoload 'tuareg-mode "tuareg" "Major mode for editing OCaml code" t)
  (autoload 'tuareg-run-ocaml "tuareg" "Run an inferior OCaml process." t)
  (autoload 'ocamldebug "ocamldebug" "Run the OCaml debugger" t)

  (require 'color-theme)
  (color-theme-initialize)
  (color-theme-midnight)

  (setq x-select-enable-clipboard nil)
  (setq save-interprogram-paste-before-kill nil)
  (setq yank-pop-change-selection nil)
  (setq x-select-enable-clipboard-manager nil)
  (setq x-select-enable-clipboard t)
  (setq x-select-enable-primary t)
  (setq mouse-drag-copy-region t)

  (tool-bar-mode 0)

  (global-set-key [f1] 'neotree-toggle)
  (setq neo-show-hidden-files t)
  (setq neo-create-file-auto-open t)
  (setq neo-persist-show t)
  (setq neo-keymap-style 'concise)
  (setq neo-smart-open t)
  (setq neo-vc-integration '(face char))
  (when neo-persist-show
    (add-hook 'popwin:before-popup-hook
              (lambda () (setq neo-persist-show nil)))
    (add-hook 'popwin:after-popup-hook
              (lambda () (setq neo-persist-show t))))

  (progn
    (set-face-foreground 'mode-line "white")
    (set-face-background 'mode-line "blue")
    (set-face-background 'region "white")
    )

  (prefer-coding-system 'utf-8)
  (global-set-key (kbd "C-j") 'toggle-input-method)

  (setq make-backup-files nil)

  (setq delete-auto-save-files t)

  (setq-default tab-width 4 indent-tabs-mode nil)

  (setq eol-mnemonic-dos "(CRLF)")
  (setq eol-mnemonic-mac "(CR)")
  (setq eol-mnemonic-unix "(LF)")

  (add-to-list 'default-frame-alist '(alpha . (0.85 0.85)))

  (column-number-mode t)

  (global-linum-mode t)

  (blink-cursor-mode 0)

  (global-hl-line-mode t)

  (show-paren-mode 1)
  (setq show-paren-style 'expression)

  (global-whitespace-mode 1)
  (setq whitespace-space-regexp "\x3000+")
  (set-face-foreground 'whitespace-newline "gray40")

  (dolist (d '((space-mark ?\ ) (newline-mark ?\n)))
    (setq whitespace-display-mappings
          (delete-if
           '(lambda (e) (and (eq (car d) (car e))
                             (eq (cadr d) (cadr e))))
           whitespace-display-mappings)))

  (dolist (e '((space-mark   ?\x3000 [?\□])
               (newline-mark ?\n     [?\u21B5 ?\n] [?$ ?\n])))
    (add-to-list 'whitespace-display-mappings e))

  (dolist (d '(face lines space-before-tab
                    indentation empty space-after-tab tab-mark))
    (setq whitespace-style (delq d whitespace-style)))

  (setq scroll-conservatively 1)

  (setq kill-whole-line t)

  (require 'dired-x)

  (defun my-bell-function ()
    (unless (memq this-command
                  '(isearch-abort abort-recursive-edit exit-minibuffer
                                  keyboard-quit mwheel-scroll down up next-line previous-line
                                  backward-char forward-char))
      (ding)))
  (setq ring-bell-function 'my-bell-function)

  (custom-set-faces
   ;; custom-set-faces was added by Custom.
   ;; If you edit it by hand, you could mess it up, so be careful.
   ;; Your init file should contain only one such instance.
   ;; If there is more than one, they won't work right.
   '(default ((t (:foundry "Inconsolata" :family "Inconsolata" :height 120)))))

  (set-fontset-font t 'japanese-jisx0208 (font-spec :family "Noto Sans Mono CJK JP" :size 14))

  (define-key global-map (kbd "C-x C-c") 'clipboard-kill-ring-save)
  (define-key global-map (kbd "C-x C-x") 'clipboard-kill-region)
  (define-key global-map (kbd "C-x C-k") 'kill-line)
  (define-key global-map (kbd "C-x C-s") 'save-buffer)
  (define-key global-map (kbd "C-x C-a") 'mark-whole-buffer)
  (define-key global-map (kbd "C-x C-v") 'clipboard-yank)
  (define-key global-map (kbd "C-x C-z") 'undo)
  (define-key global-map (kbd "C-s") 'isearch-forward)

  (require 'tabbar)
  (tabbar-mode)
  (setq tabbar-mwheel-mode nil)
  (setq tabbar-buffer-groups-function nil)
  (set-face-attribute 'tabbar-default nil :background "#a3ffa3" :foreground "#696969" :family "Inconsolata")
  (set-face-attribute 'tabbar-selected nil :background "#00ff00" :foreground "black" :box nil)
  (set-face-attribute 'tabbar-modified nil :background "#a3ffa3" :foreground "#696969" :box nil)
  (custom-set-variables
   ;; custom-set-variables was added by Custom.
   ;; If you edit it by hand, you could mess it up, so be careful.
   ;; Your init file should contain only one such instance.
   ;; If there is more than one, they won't work right.
   '(package-selected-packages (quote (haskell-mode tuareg tabbar color-theme))))

  )

(when (equal system-type 'windows-nt)
  (require 'package)
  (setq package-archives
        '(("gnu" . "http://elpa.gnu.org/packages/")
          ("melpa" . "http://melpa.org/packages/")
          ("org" . "http://orgmode.org/elpa/")))
  (package-initialize)
  (add-to-list 'auto-mode-alist '("\\.ml[iylp]?" . tuareg-mode))
  (autoload 'tuareg-mode "tuareg" "Major mode for editing OCaml code" t)
  (autoload 'tuareg-run-ocaml "tuareg" "Run an inferior OCaml process." t)
  (autoload 'ocamldebug "ocamldebug" "Run the OCaml debugger" t)

  (require 'color-theme)
  (color-theme-initialize)
  (color-theme-midnight)

  (set-default-coding-systems 'utf-8-dos)

  (global-set-key (kbd "C-j") 'toggle-input-method)

  (setq x-select-enable-clipboard nil)
  (setq save-interprogram-paste-before-kill nil)
  (setq yank-pop-change-selection nil)
  (setq x-select-enable-clipboard-manager nil)
  (setq x-select-enable-primary t)
  (setq mouse-drag-copy-region t)

  (tool-bar-mode 0)

  (global-set-key [f1] 'neotree-toggle)
  (setq neo-show-hidden-files t)
  (setq neo-create-file-auto-open t)
  (setq neo-persist-show t)
  (setq neo-keymap-style 'concise)
  (setq neo-smart-open t)
  (setq neo-vc-integration '(face char))
  (when neo-persist-show
    (add-hook 'popwin:before-popup-hook
              (lambda () (setq neo-persist-show nil)))
    (add-hook 'popwin:after-popup-hook
              (lambda () (setq neo-persist-show t))))

  (progn
    (set-face-foreground 'mode-line "white")
    (set-face-background 'mode-line "blue")
    (set-face-background 'region "white")
    )

  (setq make-backup-files nil)

  (setq delete-auto-save-files t)

  (setq-default tab-width 4 indent-tabs-mode nil)

  (setq eol-mnemonic-dos "(CRLF)")
  (setq eol-mnemonic-mac "(CR)")
  (setq eol-mnemonic-unix "(LF)")

  (add-to-list 'default-frame-alist '(alpha . (0.85 0.85)))

  (column-number-mode t)

  (global-linum-mode t)

  (blink-cursor-mode 0)

  (global-hl-line-mode t)

  (show-paren-mode 1)
  (setq show-paren-style 'expression)

  (global-whitespace-mode 1)
  (setq whitespace-space-regexp "\x3000+")
  (set-face-foreground 'whitespace-newline "gray40")

  (dolist (d '((space-mark ?\ ) (newline-mark ?\n)))
    (setq whitespace-display-mappings
          (delete-if
           '(lambda (e) (and (eq (car d) (car e))
                             (eq (cadr d) (cadr e))))
           whitespace-display-mappings)))

  (dolist (e '((space-mark   ?\x3000 [?\□])
               (newline-mark ?\n     [?\u21B5 ?\n] [?$ ?\n])))
    (add-to-list 'whitespace-display-mappings e))

  (dolist (d '(face lines space-before-tab
                    indentation empty space-after-tab tab-mark))
    (setq whitespace-style (delq d whitespace-style)))

  (setq scroll-conservatively 1)

  (setq kill-whole-line t)

  (require 'dired-x)

  (defun my-bell-function ()
    (unless (memq this-command
                  '(isearch-abort abort-recursive-edit exit-minibuffer
                                  keyboard-quit mwheel-scroll down up next-line previous-line
                                  backward-char forward-char))
      (ding)))
  (setq ring-bell-function 'my-bell-function)

  (set-face-attribute 'default nil :family "inconsolata" :height 120)
  (set-fontset-font nil 'japanese-jisx0208 (font-spec :family "メイリオ"))
  (setq face-font-rescale-alist '(("メイリオ" . 0.9)))

  (define-key global-map (kbd "C-x C-c") 'clipboard-kill-ring-save)
  (define-key global-map (kbd "C-x C-x") 'clipboard-kill-region)
  (define-key global-map (kbd "C-x C-k") 'kill-line)
  (define-key global-map (kbd "C-x C-s") 'save-buffer)
  (define-key global-map (kbd "C-x C-a") 'mark-whole-buffer)
  (define-key global-map (kbd "C-x C-v") 'clipboard-yank)
  (define-key global-map (kbd "C-x C-z") 'undo)
  (define-key global-map (kbd "C-s") 'isearch-forward)

  (require 'tabbar)
  (tabbar-mode)
  (setq tabbar-mwheel-mode nil)
  (setq tabbar-buffer-groups-function nil)
  (set-face-attribute 'tabbar-default nil :background "#a3ffa3" :foreground "#696969" :family "inconsolata")
  (set-face-attribute 'tabbar-selected nil :background "#00ff00" :foreground "black" :box nil)
  (set-face-attribute 'tabbar-modified nil :background "#a3ffa3" :foreground "#696969" :box nil)

  (custom-set-variables
   ;; custom-set-variables was added by Custom.
   ;; If you edit it by hand, you could mess it up, so be careful.
   ;; Your init file should contain only one such instance.
   ;; If there is more than one, they won't work right.
   '(package-selected-packages (quote (haskell-mode neotree tuareg tabbar color-theme))))
  (custom-set-faces
   ;; custom-set-faces was added by Custom.
   ;; If you edit it by hand, you could mess it up, so be careful.
   ;; Your init file should contain only one such instance.
   ;; If there is more than one, they won't work right.
   )
  )

Pythonで不定期練習

解きながら学ぶJava 入門編

解きながら学ぶJava 入門編

# q2_6

# coding: utf-8

n = input("整数値 : ")
print "10を加えた値は%dです。" % (n + 10)
print "10を減じた値は%dです。" % (n - 10)

# q2_7

# coding: utf-8

n = input("整数値 : ")
print "最下位桁を除いた値は%dです。" % (n / 10)
print "最下位桁は%dです。" % (n % 10)

# q2_8

# coding: utf-8

x = input("xの値 : ")
y = input("yの値 : ")
print "合計は%fです。" % (x + y)
print "平均は%fです。" % ((x + y) / 2)

# q2_9

# coding: utf-8

print "三角形の面積を求めます。"
bottom = input("底辺 : ")
height = input("高さ : ")
print "面積は%fです。" % (bottom * height / 2)

# q2_10

# coding: utf-8
import math
print "球の表面積と体積を求めます。"
r = input("半径 : ")
print "表面積は%fです。" % (4 * math.pi * r * r)
print "体積は%fです。" % (4 * math.pi * r * r * r / 3)

# q2_11

# coding: utf-8
import random
print "3個の乱数を生成しました。"
print "1桁の正の整数 : %d" % random.randint(1, 9)
print "1桁の負の整数 : %d" % random.randint(-9, -1)
print "2桁の正の整数 : %d" % random.randint(10, 99)

# q2_12

# coding: utf-8
import random
n = input("整数値 : ")
print "その値±5の乱数を生成しました。"
print "値は%dです。" % (random.randrange(11) + n - 5)

# q2_12 別解その1

# coding: utf-8
import random
n = input("整数値 : ")
print "値は%dです。" % (random.random() * 10 + n - 5)

# q2_12 別解その2

# coding: utf-8
import random
n = input("整数値 : ")
print "値は%dです。" % random.randint(n - 5, n + 5)

Go言語で不定期練習

解きながら学ぶJava 入門編

解きながら学ぶJava 入門編

// q3-1

package main

import (
    "fmt"
    "bufio"
    "os"
    "strconv"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    fmt.Print("整数値 : ")
    scanner.Scan()
    n, _ := strconv.Atoi(scanner.Text())
    if n < 0 {
        fmt.Println("その値は負です。")
    }
}

// q3-2

package main

import (
    "fmt"
    "math"
)

func main() {
    var stdin float64
    fmt.Print("整数値 : ")
    fmt.Scan(&stdin)
    fmt.Printf("その絶対値は%.0fです。\n", math.Abs(stdin))
}

// q3-3

package main

import "fmt"

func main() {
    var a, b int
    fmt.Print("変数A : ")
    fmt.Scan(&a)
    fmt.Print("変数B : ")
    fmt.Scan(&b)
    if a % b == 0 {
        fmt.Println("BはAの約数です。")
    } else {
        fmt.Println("BはAの約数ではありません。")
    }
}

// q3-4

package main

import "fmt"

func main() {
    var a, b int
    fmt.Print("変数A : ")
    fmt.Scan(&a)
    fmt.Print("変数B : ")
    fmt.Scan(&b)
    if !(a % b == 0) {
        fmt.Println("BはAの約数ではありません。")
    } else {
        fmt.Println("BはAの約数です。")
    }
}

// q3-5

package main

import "fmt"

func main() {
    var a int
    fmt.Print("整数値 : ")
    fmt.Scan(&a)
    if a > 0 {
        fmt.Println("その値は正です。")
    } else if a == 0 {
        fmt.Println("その値は0です。")
    } else {
        fmt.Println("その値は負です。")
    }
}

// q3-7

package main

import "fmt"

func main() {
    var a,b int
    fmt.Print("変数a : ")
    fmt.Scan(&a)
    fmt.Print("変数b : ")
    fmt.Scan(&b)
    if a > b {
        fmt.Println("aの方が大きいです。")
    } else if a < b {
        fmt.Println("bの方が大きいです。")
    } else {
        fmt.Println("aとbは同じ値です。")
    }
}

// q3-8

package main

import "fmt"

func main() {
    var a int
    fmt.Print("整数値 : ")
    fmt.Scan(&a)
    if a % 5 == 0 {
        fmt.Println("その値は5で割り切れます。")
    } else {
        fmt.Println("その値は5で割り切れません。");
    }
}

Javaで不定期練習

解きながら学ぶJava 入門編

解きながら学ぶJava 入門編

// 問題6-21 別解

import java.util.Scanner;

class q6_21_another {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("クラス数 : ");
        int class_num = scan.nextInt();
        int[][] point = new int[class_num][];
        int ninzu = 0;
        for(int i = 0; i < point.length; i++) {
            System.out.printf("\n%d組の人数 : ", i + 1);
            int num = scan.nextInt();
            point[i] = new int[num];
            ninzu += num;
            for(int j = 0; j < point[i].length; j++) {
                System.out.printf("%d組%d番の点数 : ", i + 1, j + 1);
                point[i][j] = scan.nextInt();
            }
        }

        System.out.println("  組 |    合計    平均");
        System.out.println("-----+----------------");
        int total = 0;
        for(int i = 0; i < point.length; i++) {
            int sum = 0;
            for(int j = 0; j < point[i].length; j++) {
                sum += point[i][j];
            }
            total += sum;
            System.out.printf("%2d組 | %7d %7.1f\n", i + 1, sum, (double)sum / point[i].length);
        }
        System.out.println("-----+----------------");
        System.out.printf("  計 | %7d %7.1f\n", total, (double)total / ninzu);
    }
}

// 問題7-1

import java.util.Scanner;

class q7_1 {
    public static int signOf(int n) {
        return n > 0 ? 1 : n == 0 ? 0 : -1;
    }
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("整数x : ");
        int answer = scan.nextInt();
        if(signOf(answer) == 1)
            System.out.println("signOf(x)は1です。");
        else if(signOf(answer) == 0)
            System.out.println("signOf(x)は0です。");
        else
            System.out.println("signOf(x)は-1です。");
    }
}

// 問題7-2

import java.util.Scanner;

class q7_2 {
    public static int min(int a, int b, int c) {
        int min = a;
        if(min > b) min = b;
        if(min > c) min = c;
        return min;
    }
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("整数a : ");
        int a = scan.nextInt();
        System.out.print("整数b : ");
        int b = scan.nextInt();
        System.out.print("整数c : ");
        int c = scan.nextInt();
        System.out.println("最小値は" + min(a, b, c) + "です。");
    }
}

// 問題7-3

import java.util.Scanner;

class q7_3 {
    public static int med(int a, int b, int c) {
        int answer;
        if(b >= a && a >= c || c >= a && a >= b)
            answer = a;
        else if(a >= b && b >= c || c >= b && b >= a)
            answer = b;
        else
            answer = c;
        return answer;
    }
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("整数a : ");
        int a = scan.nextInt();
        System.out.print("整数b : ");
        int b = scan.nextInt();
        System.out.print("整数c : ");
        int c = scan.nextInt();
        System.out.println("中央値は" + med(a, b, c) + "です。");
    }
}

// 問題7-3 別解

import java.util.Scanner;

class q7_3_another {
    public static int med(int a, int b, int c) {
        if(a >= b)
            if(b >= c)
                return b;
            else if(a <= c)
                return a;
            else
                return c;
        else if(a > c)
            return a;
        else if(b > c)
            return c;
        else
            return b;
    }
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("整数a : ");
        int a = scan.nextInt();
        System.out.print("整数b : ");
        int b = scan.nextInt();
        System.out.print("整数c : ");
        int c = scan.nextInt();
        System.out.println("中央値は" + med(a, b, c) + "です。");
    }
}

ああー、今日は疲れた…。

Swift iOSアプリ タブブラウザ作成 途中経過

仕様が変わったらしくコードがこんな感じになりました。

import UIKit

class ViewController: UIViewController, UIWebViewDelegate, UISearchBarDelegate {

    @IBOutlet weak var webview: UIWebView!
    @IBOutlet weak var searchbar: UISearchBar!
    
    let search_engine_url = "https://www.google.co.jp/search?q="
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.webview.delegate = self
        self.searchbar.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        if(searchbar.isFirstResponder) {
            searchbar.resignFirstResponder()
        }
    }
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        let original_url = search_engine_url + searchbar.text!
        let req_url = URL(string: original_url)
        let req = URLRequest(url: req_url!)
        self.webview.loadRequest(req)
    }
}

まだ出来てませんが、この辺りだけでもちょっと苦戦したので今回はここまでにしておきます。AutoLayoutは以前にやったことがあるので割りと簡単に出来ました。これが終わったら本格的にAndroidアプリを…。

f:id:kh2n:20170716174524p:plain